Catching input errors

If I wanted to sanitize some user input, is there a more concise way to do that, rather than what I’ve got here, in this simple example?

print("Please enter two numbers at the inputs:")
error = 1
while error:
    try:
        n1 = int(input("1st Number: "))
        error = 0
    except ValueError:
        print("That was not a number")

error = 1
while error:
    try:
        n2 = int(input("2nd Number: "))
        error = 0
    except ValueError:
        print("That was not a number")

print(f"n1 + n2 = {n1+n2}")

edit: other than defining a function, that is.

Using your current code, you can do it slightly shorter using break, bypassing the need to have loop variables.

print("Please enter two numbers at the inputs:")
while True:
    try:
        n1 = int(input("1st Number: "))
        break
    except ValueError:
        print("That was not a number")

while True:
    try:
        n2 = int(input("2nd Number: "))
        break
    except ValueError:
        print("That was not a number")

print(f"n1 + n2 = {n1+n2}")

As you mentioned in your edit, using a function would be an even better way to proceed.

def get_number(prompt):
    while True:
         try:
             return int(input(prompt))
         except ValueError:
             print("That was not a number")

n1 = get_number("1st Number: ")
n2 = get_number("2nd Number: ")
print(f"{n1 + n2 = }")  # shorter version for Python 3.8+

Note that “2.3” is a number but not an integer. So you might want to ask for “whole numbers” or “integers” instead of simply “numbers”.

3 Likes

Thank you.

I like the use of prompt in the function; I’d not considered that. In fact, your function construct, is much better than the one I had in mind – very nice.
+1

edit:

That’s a valid point: I’ll edit the code thus…

return float(input(prompt))

… which will take care of that.

Thank you.