How do you input integers using input in Python

Your third attempt is correct – but what is happening to guess_row before/after this code? For example, consider the following:

a = "Hello"
try:
    a = int(input("Enter a number: "))
except ValueError:
    print("Not an integer value...")
print(str(a))

If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print “Hello” instead.

You can refine this so that an invalid number will prompt the user to re-enter the value:

a = None
while a is None:
    try:
        a = int(input("Enter a number: "))
    except ValueError:
        print("Not an integer value...")
print(str(a))

Leave a Comment