简体   繁体   English

如何在输入有效输入之前询问用户特定的字符串和循环?

[英]How to ask the user for a specific string and loop until valid input is entered?

I am using Python 3.0. 我正在使用Python 3.0。 I'm trying to ask the user to enter the string 'Small', 'Medium' or 'Large' and raise an error if none of those are entered and then ask for input again. 我试图要求用户输入字符串“ Small”,“ Medium”或“ Large”,如果没有输入任何内容,则会引发错误,然后再次要求输入。

while True:

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

Why doesn't this work? 为什么不起作用? Even if a number is entered the program continues and comes to an error at the end. 即使输入了数字,程序仍会继续运行并最终出错。

input always returns a str , so str(input()) never raises a ValueError . input始终返回一个str ,因此str(input())永远不会引发ValueError

You're confusing a string with a word. 您正在将字符串与单词混淆。 A string is just a series of characters. 字符串只是一系列字符。 For example "123hj -fs9f032@RE#@FHE8" is a perfectly valid sequence of characters, and thus a perfectly valid string. 例如, "123hj -fs9f032@RE#@FHE8"是一个完全有效的字符序列,因此是一个完全有效的字符串。 However it is clearly not a word. 但是,这显然不是一个词。

Now, if a user types in "1234", Python won't try to think for you and turn it into an integer, it's just a series of characters - a "1" followed by a "2" followed by a "3" and finally a "4". 现在,如果用户输入“ 1234”,Python不会尝试为您考虑并将其变成整数,它只是一系列字符-“ 1”后跟“ 2”,再后跟“ 3”最后是“ 4”。

You must define what qualifies as a word, and then check the entered string if it matches your definition. 您必须定义什么才是单词,然后检查输入的字符串是否符合您的定义。

For example: 例如:

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) + ".")

You can simply do as follows: 您可以简单地执行以下操作:

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)

There is no need for any try and error here. 这里不需要任何尝试和错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM