Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
tip and tax calculator
bill = price + tax + tip
price = raw_input("What is the price of the meal")
tax = price * .06
tip = price * 0.20
what is wrong with my code
I have tried everything
please answer and get back to me
a few things.
bill = price + tax + tip #You can't add up these values BEFORE calculating them
price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing
tax = price * .06 #So here you need to do float(price) * .06
tip = price * 0.20 #And float(price) here as well.
#Then your " bill = price + tax + tip " step goes here
First of all, you can't use variables that you haven't defined: in your code your are using bill = price + tax + tip but your program doesn't even know what price, tax and tip are yet, so that line should be at the end of the code, after you've asked the price and calculated tax and tip.
Then, you have raw_input, this function returns a string, if you want to convert it to a decimal number that you can multiply and add (float) you can use price = float(raw_input("what is the price of the meal"))
Correct that two things and it should work...
Heres a couple of things wrong with the code:
You're trying to calculate the total before some variables have been defined.
The raw_input function returns a string so you can't do proper mathematical calculations before you coerce it into an integer.
In calculate the tips/tax you should use a float with the whole number 1(1.20) to take the whole value of the bill + 20%.
Below is a code snippet that should work how you want and give you something to think about on how to pass dynamic values into the modifiers within the calculate_bill function for custom tip floats and custom tax floats:
def calculate_bill(bill, bill_modifiers):
for modifier in bill_modifiers:
bill = modifier(bill)
return bill
def calculate_tip(bill, percentage=1.20):
return bill * percentage
def calculate_tax(bill, percentage=1.06):
return bill * percentage
if __name__ == '__main__':
bill = int(input("What is the price of the meal: "))
total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
print(total_bill)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
# Sample line of text from file (Ford,F150,55000;)
filename = 'carPrice.txt'
def main():
all_prices= {}
try:
with open(filename) as fh:
for line in fh:
make, model, price = line.strip().split(',')
all_prices[(make,model)]=price.strip()
income = float(input("Enter your monthly income amount:"))
print("Your monthly income amount is",income,)
make = input("Enter Make of the car:")
print("You selected a",make,)
model = input("Enter Model of the car:")
print("You selected a",model,)
price_value=0
for x in price:
if x == (make,model):
price_value=price[x]
print("The price of that car is",price_value,)
payment = (price_value* 0.80)/60
print("The monthly payment is",payment,)
if (payment < 0.11*income):
print("The monthly payment of",payment,"= Acceptable Risk")
return "Acceptable"
else:
print("The monthly payment of",payment,"= Unacceptable Risk")
return "Unacceptable"
# Exception added to enable troubleshooting of errors on lines
except OSError as e:
print(e.errno)
if __name__ == '__main__':
main()
With respect, the code seems to be a bit all over the place, specifically in regards to price. If this is an exact copy of your code I think you may have lost track of what 'price' actually is.
For example here:
for x in price:
if x == (make,model):
price_value=price[x]
However, price here is a string value you pulled from the file e.g. £100. You're then iterating over that £, 1, 0, 0 and checking it against the make and model.
Finally you make the price_value an index of this string e.g.
price[x] # could be price["£"]
This would then cause an exception.
I'd go through your code again and look to make sure you're referencing price, price_value and all_prices where you actually want them
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!
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))
The following is what the output should look like:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $24.0
The code I entered is:
price_one = float(input('Enter price 1: '))
print(price_one)
price_two = float(input('Enter price 2: '))
print(price_two)
two_for_price = (price_one + price_two)-((price_one + price_two)*(20/100))
print("The 'two-for' price is $",two_for_price)
(The inputs are 10.0 and 20.0 respectively.)
But the output I am getting is:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $ 24.0
In the last line I need:
The 'two-for' price is $24.0
Please help me out!!
If i'm reading this correctly you just need to remove a space from your output.
Change your last line to this:
print("The 'two-for' price is ${0}".format(two_for_price))
Your underlying problem is that the print function behavior, given a list of items, is to print each item, separated by a space. This is often convenient for quick-and-dirty print-outs, but you want something more refined.
What you need to do is create a string with the proper spacing and then print that string out.
So you could do this:
print("The 'two-for' price is $" + str(two_for_price) + ".")
The problems are (a) that's kind of clumsy and unreadable and (b) it does not format properly, it's "$2.6" instead of "$2.60".
You can use either of two formatting mechanisms offered by Python, either explicit, like this:
print("The 'two-for' price is ${0}".format(two_for_price))
or implicit, like this
print("The 'two-for' price is $%f" % two_for_price)
Both of them look a little better, but the formatting errors are the same and worse ("$2.600000"!) respectively. Fortunately, both offer nice customizable formatting:
print("The 'two-for' price is ${0:.2f}".format(two_for_price))
and
print("The 'two-for' price is $%0.2f" % two_for_price)
Both of which look reasonably clean and display perfectly.
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 )))