Tax discount for item calculator - python

How do i make a code where user input if rhe item they want has tax and then discount and then they input the percent of discount and all these price are added to the total cost

it is an easy concept , it will be something like this:
earnings = int(input("Insert your earnings : "))
taxes = 0.20
if earnings < 10000:
totTaxes = int(earnings * 0.20)
salary = earnings - totTaxes
print("Your Salary is ", salary)
print("The taxes amount are : ", totTaxes)
i think you are new in python, u can copy and run this script on python idle , its a simple python scrpts IDE that executes the scripts
this is the link to download it for windows LINK.
Good luck!

Related

Working with multiple input variables in Python 3

So I'm very new to coding and I'm learning python so I decided I'd try to make a loan calculator. I made it so when the user inputs their principle, interest rate, and years required to pay the loan in full, it will output their annual payment, their monthly payment, and their total payment for the loan. I made this and it worked. I decided to take it a step further and make it so that after this, if the user inputs their annual income, it will compare their monthly income to their monthly payment and tell them if they need to refinance or not.
Here's the program I made:
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
#lines 7-10 print the annual, monthly, and total payments made respectively
print("Annual payment: ${:,.2f}".format(payment))
print("Monthly payment: ${:,.2f}".format(payment/12))
print("Total paid for the life of the loan: ${:,.2f}".format(payment*years))
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
annualinc = float(input("Annual income: ")) #annualinc = the annual income
#to check if the user needs to refinance or not by comparing their monthly
income to their monthly payment
if (annualinc / 12) <= (payment / 12) and rate > .05:
print("You should refinance")
elif (annualinc / 12) <= (payment / 12):
print("You should seek financial counseling")
else:
print("If you make all your payments, your loan will be paid on time.")
The only way I could get the if statement to work is by having the user re-input every variable between the print statements and the if statement. Whenever I put the variable annualinc = float(input("Annual income: ") at the beginning of the program before the print statements or between the print statements and if statement it would break the line after it with a syntax error. Why did I have to ask for all the variables again and why could I not just ask for the variable annualinc by itself? And why does it not work when I put it with the first group of variables?
edit: I fixed it so I don't have to put in all the variables again! I was missing a parenthesis at the end of the line and I've been copy and pasting the line when I moved it around so the error traveled with it. Sorry for such a rookie mistake and thank you!
Would this suit you?
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
#lines 7-10 print the annual, monthly, and total payments made respectively
print("Annual payment: ${:,.2f}".format(payment))
print("Monthly payment: ${:,.2f}".format(payment/12))
print("Total paid for the life of the loan: ${:,.2f}".format(payment*years))
annualinc = float(input("Annual income: ")) #annualinc = the annual income
#to check if the user needs to refinance or not by comparing their monthly income to their monthly payment
if (annualinc / 12) <= (payment / 12) and rate > .05:
print("You should refinance")
elif (annualinc / 12) <= (payment / 12):
print("You should seek financial counseling")
else:
print("If you make all your payments, your loan will be paid on time.")
I just eliminated the redundant parts and it works on my machine!

How do you round a string in Python?

I am new to Python and a student, my college has chosen the worst book on earth for our course. I cannot find examples of any concepts, so I apologize in advance as I know these concepts are very basic. I hope you can help me.
I need to know how to use the round feature in a string. I find examples but they do not show the string, just simple numbers.
Here is what we are supposed to get as an output:
Enter the gross income: 12345.67
Enter the number of dependents: 1
The income tax is $-130.87 <---- this is what we are supposed to figure out
Here is the coding we are given to alter:
TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0
# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))
# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE
# Display the income tax
print("The income tax is $" + str(incomeTax))
As I do not have an NUMBER to plug into the formula - I have to figure out how to use "incomeTax" - I have no idea how to do this. THe book doesnt explain it. Help?
You can use format strings:
print("The income tax is ${:.2f}".format(incomeTax))
If you are using Python 3.6+, you can also use f-strings:
print(f"The income tax is ${incomeTax:.2f}")
You can round just before making it a string:
print("The income tax is $" + str(round(incomeTax,2)))
Output:
Enter the gross income: 12345.67
Enter the number of dependents: 1
The income tax is $-130.87
Im a student as well, with the same dumb book and HW.
I tried the above
str(round(incomeTax,2))
and it didn’t work. Maybe I typed something wrong. After playing around I found this to work
# Display the income tax
incomeTax = round(incomeTax,2)
print(“The income tax is $” + str(incomeTax))
I hope this helps some other poor soul searching the web for an answer!

Working with commas in output

I'm in an intro programming class and am lost. We've had several labs that required knowledge that we haven't been taught but I've managed to find out what I need on google (as nobody responds to the class message board) but this one has me pretty frustrated. I'll include a pastebin link here: https://pastebin.com/6JBD6NNA
`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))
time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))
rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))
interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`
So I need the output of the dollar amounts to have a comma ($27,500.00) but I have no idea how to do this. I've seen a couple of solutions on this site and others but I can't get them to work. PLEASE can someone help me?
In Python 2.7 or above, you can use
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
This is documented in PEP 378.
Source: Python Add Comma Into Number String
Here is a working example:
principal = float(input('Enter the Principal Value of your investment: $'))
time = int(input('\nEnter the Time(in years) you plan to save your investment: '))
rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))
interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
Your last line should be:
print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

Break Outside Loop with Previous Example

UPDATED:
This Code Works:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
# tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
# total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below\n")
while True:
subtotal = float(input("Enter the total price of your purchases:\t$").strip())
if subtotal == -1: break
tax = subtotal * nctaxrate
total = subtotal + tax
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
Here is the Original Question:
So I am learning Python and asked a previous question yesterday and was supplied with an awesome set of code that I decided to modify to work with an NC Sales Tax Estimator Program I wanted to create.
The one thing is that I am getting a break out loop error that I don't quite understand. I've searched and tried to understand the meaning but I know the code worked before. Also the tax code program I created from scratch :) worked before trying to add the fancy ability to submit many inputs in a loop until the user wanted to 'exit'.
Here is the Code:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below")
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
try:
subtotal = int(subtotal)
except ValueError:
print("That wasn't a number!")
try:
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
except KeyError:
print("")
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
P.S. I only added the KeyError because I researched that you must have an error statement after a try. I'm just a beginner so I'm attempting to create programs myself and reading "Python for the Absolute Beginner".
UPDATE:
I fixed the indentation but now I get the following traceback error:
Traceback (most recent call last):
File "C:/LearningPython/taxestimator.py", line 30, in <module>
tax = subtotal * nctaxrate
NameError: name 'subtotal' is not defined
I thought I defined it in the input ie.
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
Is it because the other defines (tax and total) that use the defined subtotal are defined before subtotal is defined? I tried moving them below the defined subtotal but it didn't work still.
Thanks for any Advice.
Best,
Steven
The main issue that you have is that Python requires whitespace to scope methods. Without that, then statements will run not as intended - for example:
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
will not break out of the loop with valid input (it will if you put a string there, but that's another matter). Also, if everything is to be in the scope of main(), every statement requires one level of indentation (or four lines of whitespace, if you prefer). As it stands, your while won't run in the scope of main().
Also, you make reference to subtotal before you actually give it a value. Since subtotalwasn't properly initialized, you won't have a value to use for it.
You would want to rewrite your code such that tax and total are defined after you define subtotal.
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
tax = subtotal * nctaxrate
total = subtotal + tax
Finally, if subtotal, total, and tax are properly defined (which, after the above, they will be), there will be no need for the superflous try...except statement when you wish to print the values out.
if subtotal.lower()=='exit':
break
needs to be indented probably ... unless that was just a typo when entering the question

Categories