【问题标题】:Lab: calculate discounts实验室:计算折扣
【发布时间】:2021-11-05 10:03:24
【问题描述】:

我正在做一个练习,到目前为止,代码(在其他线程的一些帮助下)现在可以几乎正常工作,但是......无法获得正确的结果作为数学观点。

代码如下:

#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

语法有什么问题?非常感谢!

【问题讨论】:

  • 您使用的是 python 2.x 吗?如果没有,你为什么使用raw_input?如果是这样,为什么是在 2021 年? :)
  • 你说得对,坏习惯很难改掉! :D

标签: python python-2.x


【解决方案1】:

问题

在第二个条件中你写了print('Total price = ' + totalprice) 行而不是print('Total price = ', totalprice),问题在于:

totalpricefloat 类型,同时'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 并连接strs

print('Total price = ' + str(totalprice))

str(totalprice)totalpricefloat 转换为 str,python 知道如何将字符串连接在一起。

3) 格式化

"Total price = {}".format(3.14)" 等价于"Total price = 3.14" 字符串,
所以print("Total price = {}".format(totalprice)) 也可以工作

在 python 3 中我们也有 f-stings:

f"Total price = {3.14}" == "Total price = 3.14"

print(f"Total price = {totalprice}")

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多