【问题标题】:TypeError can't multiply sequence by non-int of type 'str'TypeError 不能将序列乘以“str”类型的非整数
【发布时间】:2018-01-03 03:58:45
【问题描述】:

我的程序抛出这个错误:

File "C:\Users\...\Meal Price Calculator.py", 
line 6, in <module> meal = meal * tax 
TypeError: can't multiply sequence by  non-int of type 'str'

问题:

  • 我输入的符号有误吗?
  • 是标点符号吗?

我的代码:

meal = input('Enter Amount of Meal ')
tax = input('Enter tax percentage in decimal ')
tip = input('Enter tip percentage in decimal ')
meal = meal * tax
meal = meal / tip
print(meal)
input()

【问题讨论】:

  • 行尾的数字是多少?
  • 请使用代码格式,并删除行号。相反,复制粘贴您进入问题的实际错误回溯(因为 Python 通常比说“第 5 行出现错误”更清楚)。
  • 我不确定,他们在真实代码中,所以它一定是一个错字。
  • input() 返回一个字符串,总是 (*)。您必须自己将其转换为浮点数或整数,例如tax = float(tax)tip 同上。 ((*) 在 Python 3 中,即。)
  • 回溯:文件“C:\Users\Aiden M\Desktop\Files\Meal Price Calculator.py”,第 6 行,在 餐=餐*税类型错误:不能乘按“str”类型的非整数排序

标签: python windows


【解决方案1】:

符号没有错。
是不是标点符号。
问题在于您的变量类型。 就像@Evert 所说的那样,input() 总是返回一个字符串。您必须手动将其转换为浮点数或整数。
由于您要求输入为小数,因此您想使用浮点数。
你的代码是这样的:

meal = float(input('Enter Amount of Meal '))
tax = float(input('Enter tax percentage in decimal '))
tip = float(input('Enter tip percentage in decimal '))
meal = meal * tax
meal = meal / tip
print(meal)

( PS。除非你双击脚本来运行它,否则我看不到最后的输入点。我建议从命令行(cmd)运行 python 脚本。如果你需要帮助。)

阅读更多关于变量here

【讨论】:

  • 膳食变量也需要转换为整数或浮点数。
猜你喜欢
  • 2010-11-15
  • 2019-04-12
  • 2021-08-07
  • 2017-12-01
  • 2020-12-17
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多