0

I am a beginner in python and made a couple of programs, one of the same things I see, is that when ever I make a code like this do = int(input("Enter number >")) I accidentally type a letter, I want to be able to give like a wrong input message and try again, but python would always detect the difference in variable container.

2 Answers2

0

You can catch ValueError:

success = False
while not success:
    try:
        do = int(input("Enter number >"))
        success = True
    except ValueError:
        print("Wrong input, please try again")
mckbrd
  • 859
  • 9
  • 11
0

I would suggest having a validation function. You can then use this function in other Python programs in the future.

def validate_int(inp):
    try:
        int(inp)
        return True
    except Exception:
        print('Invalid input')
        return False

This function will return true or false depending on whether a number has been entered.

You can then call the function like this:

inp = input('Enter number >')

while validate_int(inp) == False:
    inp = input('Enter number >')