Search code examples
pythonif-statementuser-input

How do I give an invalid message for strings that cannot be converted to an integer, via the input() function in Python?


I am trying to write a program that issues responses to a user depending on the response he/she gives to the question "What is your height?".

I am having trouble with lines 4-7, where I am trying to ask the user to enter a valid prompt (i.e., prevent receiving a string that cannot be converted to an integer).

My code is here:

#ask for user's height, and convert reply into an integer
height = int(input("What is your height?"))

#check if user's input can be converted to an integer
if type(height) != int:
    print("Please enter a valid number")
    height = int(input("What is your height?")

#give user a response, based on user's height
if height > 180: 
    print("Your height, " + str(height) + ", is above average")
elif height > 155: 
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")

Any help/advice is much appreciated!


Solution

  • Handle the exception and repeat until you get a valid number:

    while True:
        try:
            height = int(input("What is your height? "))
            break
        except ValueError:
            print("Please enter a valid number")
    
    if height > 180: 
        print("Your height, " + str(height) + ", is above average")
    elif height > 155: 
        print("Your height, " + str(height) + ", is average")
    else:
        print("Your height, " + str(height) + ", is below average")
    

    Example session:

    What is your height?: abc
    Please enter a valid number
    What is your height?: xyz
    Please enter a valid number
    What is your height?: 180
    Your height, 180, is average