您好,登錄后才能下訂單哦!
這篇文章主要介紹了python面對用戶無意義輸入問題怎么解決的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇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.")
只要用戶輸入有意義的數據,程序就會按預期工作。
C:\Python\Projects> canyouvote.py Please enter your age: 23 You are able to vote in the United States!
但如果用戶輸入無效數據,它就會失敗:
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!
當輸入無意義的數據時,如何讓程序要求有效輸入而不是崩潰?
我如何拒絕像 那樣的值-1,int在這種情況下這是一個有效但無意義的值?
解決方法
完成此操作的最簡單方法是將input方法放入 while 循環中。使用continue時,你會得到錯誤的輸入,并break退出循環。
當您的輸入可能引發異常時
使用try和except檢測用戶何時輸入無法解析的數據。
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.")
實現你自己的驗證規則
如果要拒絕 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
結合異常處理和自定義驗證
以上兩種技術都可以組合成一個循環。
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.")
關于“python面對用戶無意義輸入問題怎么解決”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“python面對用戶無意義輸入問題怎么解決”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。