我在绝对初学者(第三版)中使用Python编程,不幸的是在游戏早期就遇到了问题。
有人能指出我以下代码有什么问题吗?
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")
错误:
"/Users/Gabe/Desktop/Python/Challene 2.3.py", line 5, in <module> + price_20 + "dollars") TypeError: Can't convert 'float' object to str implicitly
答案 0 :(得分:2)
由于您将float连接到字符串而未将其转换为字符串,因此您收到错误。您应该将float转换为字符串,或者只使用逗号分隔您的参数以进行打印。
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")
答案 1 :(得分:0)
如果你认为它更具可读性,请考虑这种替代格式:
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))
双倍百分比是为了逃避百分比字符&#34; %%&#34;,&#34;%d&#34;将您的变量转换为字符串中的十进制,但作为替代方案,您可以使用&#34;%f&#34;保持它作为一个浮动(并没有四舍五入到最接近的美元)。
参考:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations