这是我写的那段代码:
#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:无法将序列乘以“float”类型的非整数
请您参考如下方法:
这里有一些奇怪的部分,我将尝试分解它们。第一个是您实际询问的问题,它是由 input 返回字符串引起的,因此您实际上是在做这样的事情。我将小写变量名称以匹配 python style
cost = "2.50"
tax = 0.12
#...
cost * tax # multiplying str and float
通过调用 float 来包装对 input 的调用以转换 str
cost = float(input('Enter the MRP of device here '))
tax = 0.12
discount = 0.5
接下来您将进行这些额外调用 float(tax) 和 float(discount)。由于这两个都是 float 的,因此您不需要它。
x = x + y 还有一个简写语法,即 x += y 考虑到这两点,您可以调整计算行:
cost += cost * tax
cost += cost * discount
print(cost)
