簡體   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