我正在做一个练习,到目前为止(在其他线程的帮助下)代码非常好,现在几乎可以使用,但是.不能从数学的角度获得正确的结果。
这是密码:
#getting base prices from user
item1 = float(input('Enter the price of the first item: '))
item2 = float(input('Enter the price of the second item: '))
clubc = raw_input('Does customer have a club card? (Y/N): ')
tax = float(input('Enter tax rate, e.g. 5.5 for 5.5% tax: '))
basep = (item1 + item2)
print('Base price = ', basep)
#setting variables for calculation
addtax = (1 + (tax / 100))
#conditions for output
if item1 >= item2 and clubc == 'N':
priceafterd = float(item1 + (item2 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
elif item2 >= item1 and clubc == 'N':
priceafterd = float(item2 + (item1 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
if item1 >= item2 and clubc == 'Y':
priceafterd = float((item1 + (item2 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)
else:
priceafterd = float((item2 + (item1 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)这项练习需要编写一个程序来计算一个顾客在购买两种商品后必须支付的金额,这取决于促销广告、俱乐部卡和税收。
问题在于结果。作为投入的一个例子:
Enter price of the first item: 10
Enter price of the second item: 20
Does customer have a club card? (Y/N): y
Enter tax rate, e.g. 5.5 for 5.5% tax: 8.25
Base price = 30.00
Price after discounts = 22.50
Total price = 24.36相反,我得到了:
line 33, in <module>
print('Total price = ' + totalprice)
TypeError: cannot concatenate 'str' and 'float' objects语法怎么了?非常感谢!
发布于 2021-09-08 17:58:51
问题所在
在第二个条件中,您编写了print('Total price = ' + totalprice)行而不是print('Total price = ', totalprice),问题是:
totalprice有float类型,而'Total price = '是str,您要做的事情几乎像str() + float(),而且因为python不知道如何连接字符串和浮点数,所以会引发异常。
如何解决
1)在任何地方使用相同的print('Total price = ', totalprice)行
,为什么它能工作,而
print('Total price = ' + totalprice)却不工作?
因为print会自动将所有内容转换为字符串表示形式,所以可以这样想象print('Total price = ', totalprice)表达式:
print(str('Total price = ') + " " + str(totalprice))
2)将float转换为str并级联str
print('Total price = ' + str(totalprice))
str(totalprice)将totalprice从float转换为str,python知道如何将字符串连接在一起。
3)格式化
"Total price = {}".format(3.14)"等价于"Total price = 3.14"字符串,
所以print("Total price = {}".format(totalprice))也能工作
在python 3中,我们还有f刺:
f"Total price = {3.14}" == "Total price = 3.14"
print(f"Total price = {totalprice}")
https://stackoverflow.com/questions/69106313
复制相似问题