我正在編寫一個(gè)必須接受用戶輸入的程序。#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!但如果他們犯了錯(cuò)誤,那就崩潰了: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!我怎么能做到這一點(diǎn)?如果我還想拒絕像這樣的上下文中-1的有效int但無意義的值,該怎么辦?
4 回答

動(dòng)漫人物
TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
雖然接受的答案是驚人的。我還想分享這個(gè)問題的快速入侵。(這也解決了負(fù)面年齡問題。)
f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or \ f(input("invalid input. Try again\nPlease enter your age: "))print(f(input("Please enter your age: ")))
PS此代碼適用于python 3.x.
添加回答
舉報(bào)
0/150
提交
取消