简体   繁体   中英

Python - Try/Except with sum function

im new to python and im practicing so i am doing a sum function, and now i want to show a message error when entering something that is not a number i tried with try/excpet and it kind of worked but sometimes it dont, here is the code i have now:

def sum(num_1, num_2):
    sum_total = num_1 + num_2
    print('The answer is:',sum_total)
    return sum_total

def app_sum():
    try:
        inp_1 = int(input('Number 1?: '))
    except ValueError:
        print('Invalid input, try again')
        app_sum()

    try:
        inp_2 = int(input('Number 2?: '))
    except ValueError:
        print('Invalid input, try again')
        app_sum()

    sum(inp_1,inp_2)

app_sum()

And this is the output i have:

Number 1?: 1
Number 2?: 2
The answer is: 3

Number 1?: A
Invalid input, try again
Number 1?: 1
Number 2?: A
Invalid input, try again
Number 1?: 1
Number 2?: 1
The answer is: 2
Traceback (most recent call last):
  File "suma.py", line 9, in app_sum
    inp_1 = int(input('Number 1?: '))
ValueError: invalid literal for int() with base 10: 'A'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "suma.py", line 24, in <module>
    app_sum()
  File "suma.py", line 12, in app_sum
    app_sum()
  File "suma.py", line 20, in app_sum
    sum(inp_1,inp_2)
UnboundLocalError: local variable 'inp_2' referenced before assignment

The reason you get this error is because there is a scenario in which you make it to the end of the program,

sum(inp_1,inp_2)

without actually defining inp_1 or inp_2. This is because when you hit the "except", you are running the program again. This doesn't "kill" the failed program, it just starts another instance of it. When that instance finishes, the first instance also wants to conclude, but like we mentioned earlier it has a missing variable, and thus throws the error. See Stacks ;

Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, ie the plate which has been placed at the bottommost position remains in the stack for the longest period of time...

Though the last "plate" remains in the stack the longest, it still needs to come off. In our case the "last plate" is the instance of app_sum() which has bad inputs. When it comes off the stack it gives you the error you included in your post.

Try this instead:

def sum(num_1, num_2):
    sum_total = num_1 + num_2
    print('The answer is:',sum_total)
    return sum_total

def app_sum():
    while True:
        try:
            inp_1 = int(input('Number 1?: '))
            inp_2 = int(input('Number 2?: '))
            break
        except ValueError:
            print('Invalid input, try again')
    sum(inp_1, inp_2)
app_sum()

Output looks like this:

root@alarmux:/home/abdmin/python# ./test.py
Number 1?: 1
Number 2?: 2
The answer is: 3
root@alarmux:/home/abdmin/python# ./test.py
Number 1?: a
Invalid input, try again
Number 1?: 2
Number 2?: 3
The answer is: 5

Instead of recursion, you could repeat until a valid answer is given:

def sum(num_1, num_2):
    sum_total = num_1 + num_2
    print('The answer is:',sum_total)
    return sum_total

def app_sum():
    inp_1 = None
    while inp_1 is None:
        try:
            inp_1 = int(input('Number 1?: '))
        except ValueError:
            print('Invalid input, try again')
    inp_2 = None
    while inp_2 is None:
        try:
            inp_2 = int(input('Number 2?: '))
        except ValueError:
            print('Invalid input, try again')

    sum(inp_1,inp_2)

app_sum()

Example output:

Number 1?: fjksdfsdflkj
Invalid input, try again
Number 1?: 3
Number 2?: fds
Invalid input, try again
Number 2?: 4
The answer is: 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM