我是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()
提前感谢:)
然后使用
你的程序也可以缩短
或者不检查
if int(user_answer) == num1 - num2
,您可以安全地比较字符串而不是if user_anser == str(num1 - num2)
很可能您不想使用
input()
函数:input()
将允许用户在应用程序中输入错误的代码。你知道吗考虑使用
raw_input()
有几种方法可以做到这一点(这可以说是一种更简单的方法):
相关问题 更多 >
编程相关推荐