[英]Limiting input to integers in a calculator program
我是Python的新手,我正在嘗試創建一個程序,要求用戶執行計算並輸入結果。 如果用戶是對的,程序會祝賀,如果用戶錯了,程序只會顯示正確的答案
我已經做了所有的事情(也許不是最好的代碼)它的工作原理,我的問題是:當用戶鍵入任何字母而不是整數時,它會崩潰
import random
def app():
numero1 = random.randint(100000, 1000000)
numero2 = random.randint(100000, 1000000)
if numero1 > numero2:
print('Quanto fa ' + str(numero1) + ' - ' + str(numero2) + '?')
answer = input()
if int(answer) == numero1 - numero2:
print("Esatto")
app()
else:
print ("Sbagliato, fa " + str(numero1 - numero2))
app()
elif numero1 < numero2:
print ('Quanto fa ' + str(numero2) + ' - ' + str(numero1) + '?')
answer = input()
if int(answer) == numero2 - numero1:
print("Esatto")
app()
else:
print ("Sbagliato, fa " + str(numero2 - numero1))
app()
elif numero1 == numero2:
print ('Quanto fa ' + str(numero1) + ' - ' + str(numero2) + '?')
answer = input()
if int(answer) == numero1 - numero2:
print("Esatto")
app()
else:
print ("Sbagliato, fa " + str(numero1 - numero2))
app()
app()
提前致謝 :)
def get_user_int(prompt=""):
while True:
try:
return int(input(prompt))
except ValueError:
pass
然后用
answer = get_user_int()
你的程序也可能更短
if numero2 > numero1:
numero2, numero1 = numero1, numero2
if get_user_int("{0} - {1} = ?".format(numero1,numero2)) == numero1 - numero2 :
print ("Essato!")
else:
print ("Answer:{0}".format(numero1-numero2)
或者不檢查if int(user_answer) == num1 - num2
你可以安全地比較字符串, if user_anser == str(num1 - num2)
它很可能是你不希望使用的input()
函數:
input([prompt])等效於eval(raw_input(prompt))。
此功能不會捕獲用戶錯誤。 如果輸入語法無效,則會引發SyntaxError。 如果評估期間出現錯誤,可能會引發其他異常。
如果加載了readline模塊,則input()將使用它來提供精細的行編輯和歷史記錄功能。
考慮使用raw_input()函數來獲取用戶的常規輸入。
input()
允許用戶將錯誤的代碼輸入到您的應用程序中。
考慮使用raw_input()
有幾種方法可以做到這一點(這可以說是更簡單的方法之一):
def get_int(prompt=""):
input = -1
while input < 0:
try:
input = int(raw_input("Enter a number:"))
except ValueError as err:
input = -1
# Handle the error?
return input
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.