在计算器程序中将输入限制为整数

2024-07-05 14:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

提前感谢:)


Tags: 用户answer程序appinputifrandomint
2条回答
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]) Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

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

相关问题 更多 >