我正在做一個簡單的 python 練習,我會問一系列問題并從用戶那里獲得輸入。我用“輸入您的年齡”提示用戶,如果用戶輸入年齡的字母值而不是 int,我希望程式繼續運行而不是損壞,因為我正在轉換為 int 以計算年齡是否小于 18 或大于并且如果它在特定年齡之間。我無法將字母轉換為 int。
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " age "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
uj5u.com熱心網友回復:
使用 try/except。
age = input("Please enter your age: ")
try:
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " age "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
except:
print("Please enter a number")
如果您的 int 轉換失敗,代碼將跳轉到 except 而不是崩潰。
如果你想讓用戶重試,你可以寫這樣的東西。請注意您使用的范圍和負數。
age = input("Please enter your age: ")
ageNum = 0
while(ageNum <= 0):
try:
ageNum = int(age)
if (ageNum) < 18 or ageNum > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
elif ...
except:
print("Please enter a valid number")
uj5u.com熱心網友回復:
我會使用一個while回圈,例如
while int(age) != age:
input("Age must be an integer.\nPlease try again.")
正如@Barmar 所說,您需要檢查您的 if 陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439087.html
標籤:Python python-3.x 输入 用户输入
