新聞中心
問題

創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的岳西網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
正在編寫一個接受用戶輸入的程序。
#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ù),它就會失敗:
C:\Python\Projects> canyouvote.py Please enter your age: dickety six Traceback (most recent call last): File "canyouvote.py", line 1, inage = 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!
當(dāng)輸入無意義的數(shù)據(jù)時,如何讓程序要求有效輸入而不是崩潰?
我如何拒絕像 那樣的值-1,int在這種情況下這是一個有效但無意義的值?
解決方法
完成此操作的最簡單方法是將input方法放入 while 循環(huán)中。使用continue時,你會得到錯誤的輸入,并break退出循環(huán)。
當(dāng)您的輸入可能引發(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.")以上就是python面對用戶無意義輸入的解決,希望對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
網(wǎng)頁名稱:創(chuàng)新互聯(lián)Python教程:python面對用戶無意義輸入的解決
網(wǎng)頁鏈接:http://m.fisionsoft.com.cn/article/codchhd.html


咨詢
建站咨詢
