如何仅使用以下三种选择之一使用while和try语句来处理用户输入的错误

问题描述

我是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 ...

,

尝试这样的事情:

  public onSubmit(): void {
    const formData = new FormData();
    Object.entries(yourObject).forEach(([key,value]) => {
      formData.append(key,value);
    });

    // At this point,formData should have what you need.
  }
,

要在某些选择中限制用户的输入,最好将这些选择放到一个列表中,然后按以下方式将输入与它们进行比较:

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()

因此,以后如果您想添加更多选择,可以通过修改options变量轻松地完成。 该代码将在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','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!')

请尝试以下代码:

您的代码是正确的,但只需要在有条件的情况下为所有情况添加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!')