Joe Smith
Joe Smith

Reputation: 59

New to programming, inquiry

I'm using Python Programming for the Absolute Beginner (Third Edition) and have unfortunately run into problems early on in the game.

Can someone point out to me what is wrong with the following code?

price = float(input("Uh oh, looks like dinner is over. Time to calculate the tip! How much was the bill?"))

price_15 = price * .15

price_20 = price * .20

print("If you're feeling cheap you can give a 15% tip, which would be " + price_15 + "dollars. However, if you want do be a decent human being, you will give a 20% tip, which will set you back " + price_20 + "dollars")

Error:

"/Users/Gabe/Desktop/Python/Challene 2.3.py", line 5, in <module> + price_20 + "dollars") TypeError: Can't convert 'float' object to str implicitly

Upvotes: 0

Views: 57

Answers (2)

cm92
cm92

Reputation: 191

Consider this alternative format if you think its more readable:

print("If you're feeling cheap you can give a 15%% tip, which would be %d dollars. However, if you want do be a decent human being, you will give a 20%% tip, which will set you back %d dollars" % (price_15, price_20))

Double percents are to escape the percent character "%%", the "%d" converts your variable to decimal in the string, but as an alternative you can use "%f" to keep it as a float (and not have it rounded to the nearest dollar).

Reference: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Upvotes: 0

user3885927
user3885927

Reputation: 3503

You are getting error since you are concatenating float to a string without converting it it to a string. You should convert your float to string or just use commas to separate your arguments to print.

print("If you're feeling cheap you can give a 15% tip, which would be " + str(price_15) + "dollars. However, if you want do be a decent human being, you will give a 20% tip, which will set you back " + str(price_20) + "dollars")

print("If you're feeling cheap you can give a 15% tip, which would be " , price_15 , "dollars. However, if you want do be a decent human being, you will give a 20% tip, which will set you back " , price_20 , "dollars")

Upvotes: 2

Related Questions