繁体   English   中英

如何使用 (while) 和 (try) 语句来处理来自三个选择之一的用户输入错误

[英]how to use (while) and (try) statements to handle errors of user inputs from one of three choices only

我是 Python 的初学者,我需要编写一个交互代码,其中我问用户你喜欢哪个 x、y 或 z? 我想使用 (while) 循环和 (try) 语句来这样做。

我尝试了以下内容:

q1 = input('Would like to see data of Washington, Chicago or New York? \n')

while q1 == 'Washington'or =='Chicago' or == 'New York'
    try:
        print()
        break
    except:
        print('invalid input, please select a name of a city!')

你试过这个吗?

q1 = input('Would like to see data of Washington, Chicago or New York? \n')

while q1 == 'Washington' or q1 =='Chicago' or q1 == 'New York':
    try:
        print()
        break
    except:
        print('invalid input, please select a name of a city!')

您需要为每个条件语句重复q1 ...

尝试这样的事情:

while true:
    q1 = input('Would like to see data of Washington, Chicago or New York? \n')
    if q1 not in [ 'Washington', 'Chicago', 'New York' ]:
        print('invalid input, please select a name of a city!')
    else:
        break

为了限制用户在某些选择中的输入,最好将这些选择放在一个列表中,然后将输入与它们进行比较,如下所示:

choices = ['Washington', 'Chicago', 'New York']
q1 = input("Would like to see data of Washington, Chicago or New York? \n")
while q1 not in choices:
    print('invalid input, please select a name of a city!')
    q1 = input()

所以以后如果你想添加更多的选择,你可以通过修改 choices 变量轻松地做到这一点。 此代码将阻塞在 while 循环中,直到用户输入是其中一个选项。 但是,用户输入必须与选项中的一个完全相同(区分大小写)(即芝加哥不起作用,它应该是带有大写“c”的芝加哥)。

我的建议(如果您不介意区分大小写的确切名称)是像这样选择所有小写字母:

choices = ['washington', 'chicago', 'new york']

然后将用户输入(小写)与选项进行比较,如下所示:

while q1.lower() not in choices:
    ...

解决方案-1

如果你想实现继续循环直到用户输入不正确的值,请尝试下面的代码。

while flag:
    q1 = input('Would like to see data of Washington, Chicago or New York? \n')
    try:
        if q1 in [ 'Washington', 'Chicago', 'New York' ]:
            print('your result is: ' + q1)
        else:
            flag=0
            print('Invalid input, please select a name of a city!')
            break
    except:
        flag=0
        print('Invalid input, please select a name of a city!')
        break

解决方案 - 2

我们可以通过使用 if-else 来实现这一点,但是如果您想使用 while 循环,请尝试下面的代码。

编辑代码

q1 = input('Would like to see data of Washington, Chicago or New York? \n')
flag = 0;
while (q1 == 'Washington' or q1 =='Chicago' or q1 == 'New York'):
    try:
        flag = 1
        break
    except:
        print('invalid input, please select a name of a city!')
        
if(flag):
    print('your result is: ' + q1)
else:
    print('Invalid input, please select a name of a city!')

请试试这段代码:

您的代码是正确的,但只需要在 while 条件下为所有情况添加 q1

q1 = input('Would like to see data of Washington, Chicago or New York? \n')

while (q1 == 'Washington' or q1 =='Chicago' or q1 == 'New York'):
    try:
        print('your result is: ' + q1)
        break
    except:
        print('invalid input, please select a name of a city!')

暂无
暂无

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

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