TypeError:不能将序列乘以非类型' float',我无法弄清楚

时间:2017-07-14 05:46:53

标签: python

这是我写的那段代码:

#This is the first ever piece of code I/'m Writing here
#This calculates the value after applying GST
#Example: here we are applying on a smartphone costing 10000
Cost = input('Enter the MRP of device here ')

Tax = 0.12
Discount = 0.05

Cost = Cost + Cost * float(Tax)
Total = Cost + Cost * float(Discount)

print(Total)

每当我尝试执行代码时,它会在输入后给出异常:

TypeError: can't multiply sequence by non-int of type 'float'

2 个答案:

答案 0 :(得分:1)

原始输入为字符串,将其转换为float

Cost = input('Enter the MRP of device here ')
Cost=float(Cost)
Tax = 0.12
Discount = 0.05

Cost = Cost + Cost * float(Tax)
Total = Cost + Cost * float(Discount)

print(Total)

答案 1 :(得分:1)

这里有一些奇怪的部分,我会尝试将它们分解。第一个是你实际上询问的是input返回一个字符串引起的问题,所以你实际上正在做这样的事情。我要将变量名称小写以匹配python style

cost = "2.50"
tax = 0.12
#...
cost * tax # multiplying str and float

通过调用float来转换str

来调整输入来解决此问题
cost = float(input('Enter the MRP of device here '))
tax = 0.12
discount = 0.5

接下来,您有这些额外的来电float(tax)float(discount)。由于这两个都是花车,你不需要这个。

还有一个x = x + y的简写语法,x += y考虑到这两点,您可以调整计算行:

cost += cost * tax
cost += cost * discount
print(cost)