options = ["Small", "Medium", "Large"]
while True:
car_type = input("The car type: ")
if car_type in options: break
print("The car type must be one of " + ", ".join(options) + ".")
valid_options = ['Small', 'Medium' , 'Large' ]
while True:
car_type = input('The car type: ') # input is already str. Any value entered is a string. So no error is going to be raised.
if car_type in valid_options:
break
else:
print('Not a valid option. Valid options are: ', ",".join(valid_options))
print("Thank you. You've chosen: ", car_type)
input
始终返回str
,因此str(input())
从不引发ValueError
。在你把字符串和单词搞混了。字符串只是一系列字符。例如,
"123hj -fs9f032@RE#@FHE8"
是一个完全有效的字符序列,因此是一个完全有效的字符串。然而,这显然不是一个词。在现在,如果用户输入“1234”,Python不会尝试为您考虑并将其转换为整数,它只是一系列字符-一个“1”,然后是“2”,然后是“3”,最后是“4”。在
必须定义限定为单词的内容,然后检查输入的字符串是否与定义匹配。在
例如:
您可以简单地执行以下操作:
这里不需要任何尝试和错误。在
相关问题 更多 >
编程相关推荐