【发布时间】:2020-11-19 21:13:58
【问题描述】:
我正在为一个学校项目编写一些代码,该项目要求用户输入 0-10 之间的数字,但我不知道为什么即使使用列表将输入转换为整数,我仍然会收到 TypeError。请问有什么帮助吗?我在 Wing IDE 101 上执行此操作。
numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
while True:
num = ''
while num == '':
try:
num = input("Please enter a number: ")
num = int(num)
except ValueError:
if num in numbers:
num = numbers.index(num)
num = int(num)
else:
print('Invalid input, please enter valid input')
if num == 0:
print("Thank you for using this program")
break
elif num < 0 or num > 10:
print("This is an invalid number, please enter a valid number.")
print()
continue
【问题讨论】:
-
您只是在做
bool(TypeError),即True,而不管num或您期望的任何条件。if TypeError的目的是什么? -
如果您想检查
TypeError,请在except中使用,例如。except ValueError, TypeError: do_something -
if TypeError 只是用来检查是否有一个。虽然它可以被删除。此外,如果删除了 if TypeError 和 elif num 10,则代码有效。
-
if TypeError不检查TypeError是否发生,它检查对象TypeError是否评估为True,它总是会的,你的条件基本上意味着TypeError是python中的东西。 -
@SayanipDutta 如果你删除我刚刚添加的 if TypeError 似乎没有理由你得到
elif num < 0 or num > 10: builtins.TypeError: '<' not supported between instances of 'str' and 'int',我不知道为什么。