如何向用户请求一个特定的字符串和循环,直到输入有效的输入?

2024-04-30 02:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.0。我试图让用户输入字符串'Small'、'Medium'或'Large',如果这些都没有输入,就会引发一个错误,然后再次请求输入。在

while True:

    try:
        car_type = str(input('The car type: '))
    except ValueError:
        print('Car type must be a word.')
    else:
         break

为什么这个不管用?即使输入了一个数字,程序仍会继续并在结尾处出错。在


Tags: the字符串用户trueinputtype错误car
2条回答

input始终返回str,因此str(input())从不引发ValueError。在

你把字符串和单词搞混了。字符串只是一系列字符。例如,"123hj -fs9f032@RE#@FHE8"是一个完全有效的字符序列,因此是一个完全有效的字符串。然而,这显然不是一个词。在

现在,如果用户输入“1234”,Python不会尝试为您考虑并将其转换为整数,它只是一系列字符-一个“1”,然后是“2”,然后是“3”,最后是“4”。在

必须定义限定为单词的内容,然后检查输入的字符串是否与定义匹配。在

例如:

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)

这里不需要任何尝试和错误。在

相关问题 更多 >