【问题标题】:TypeError: can't multiply sequence by non-int of type 'float', I can't figure outTypeError:不能将序列乘以“float”类型的非整数,我不知道
【发布时间】:2017-07-14 23:18:26
【问题描述】:

这是我写的那段代码:

#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'

【问题讨论】:

标签: python


【解决方案1】:

这里有一些奇怪的部分,我会尝试分解它们。第一个是您实际询问的问题,这是由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)。由于这两个都已经是浮点数,所以你不需要这个。

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

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

【讨论】:

【解决方案2】:

原始输入为字符串,将其转换为浮点数

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)

【讨论】:

  • s/cast/convert。你为什么留下额外的float 电话?为什么不把对input 的调用包装起来,而不是把它分成两行呢?
  • 我想为他说清楚,试图了解他被困在哪里
  • @AbhinavTomar,请点击投票下方的V按钮接受答案
猜你喜欢
  • 2010-12-30
  • 2012-10-09
  • 1970-01-01
  • 2017-02-04
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
相关资源
最近更新 更多