Jangalit
Jangalit

Reputation: 1

Limiting input to integers in a calculator program

I am a newbie of Python and I'm trying to make a program that asks the user to perform a calculation and input the result. If the user was right the program congratulates and if the user was wrong the program simply shows the correct answer

I've done everything and (maybe not the best code) it works, my problem is: when the user types anything letters instead of integers it crashes

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

thanks in advance :)

Upvotes: 0

Views: 135

Answers (2)

Mike McMahon
Mike McMahon

Reputation: 8624

It is VERY likely that you do not want to use the input() function:

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() would allow a user to input erroneous code into your application.

consider using raw_input()

there are a few ways to do this (this being arguably one of the simpler ways):

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

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113998

def get_user_int(prompt=""):
   while True:
       try:
          return int(input(prompt))
       except ValueError:
          pass

then use

answer = get_user_int()

also your program could be shorter

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)

alternatively instead of checking if int(user_answer) == num1 - num2 you could safely compare strings instead if user_anser == str(num1 - num2)

Upvotes: 2

Related Questions