溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python面對用戶無意義輸入問題怎么解決

發(fā)布時間:2022-05-27 15:22:33 來源:億速云 閱讀:109 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹了python面對用戶無意義輸入問題怎么解決的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇python面對用戶無意義輸入問題怎么解決文章都會有所收獲,下面我們一起來看看吧。

問題

正在編寫一個接受用戶輸入的程序。

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

只要用戶輸入有意義的數(shù)據(jù),程序就會按預(yù)期工作。

C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!

但如果用戶輸入無效數(shù)據(jù),它就會失?。?/p>

C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in <module>
    age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'

而不是崩潰,我希望程序再次要求輸入。像這樣:

C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!

當輸入無意義的數(shù)據(jù)時,如何讓程序要求有效輸入而不是崩潰?

我如何拒絕像 那樣的值-1,int在這種情況下這是一個有效但無意義的值?

解決方法

完成此操作的最簡單方法是將input方法放入 while 循環(huán)中。使用continue時,你會得到錯誤的輸入,并break退出循環(huán)。

當您的輸入可能引發(fā)異常時

使用try和except檢測用戶何時輸入無法解析的數(shù)據(jù)。

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        #age was successfully parsed!
        #we're ready to exit the loop.
        break
if age >= 18:
    print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

實現(xiàn)你自己的驗證規(guī)則

如果要拒絕 Python 可以成功解析的值,可以添加自己的驗證邏輯。

while True:
    data = input("Please enter a loud message (must be all caps): ")
    if not data.isupper():
        print("Sorry, your response was not loud enough.")
        continue
    else:
        #we're happy with the value given.
        #we're ready to exit the loop.
        break
 
while True:
    data = input("Pick an answer from A to D:")
    if data.lower() not in ('a', 'b', 'c', 'd'):
        print("Not an appropriate choice.")
    else:
        Break

結(jié)合異常處理和自定義驗證

以上兩種技術(shù)都可以組合成一個循環(huán)。

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
 
    if age < 0:
        print("Sorry, your response must not be negative.")
        continue
    else:
        #age was successfully parsed, and we're happy with its value.
        #we're ready to exit the loop.
        break
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

關(guān)于“python面對用戶無意義輸入問題怎么解決”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“python面對用戶無意義輸入問題怎么解決”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI