mardi 3 janvier 2017

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 (ie, 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!

Aucun commentaire:

Enregistrer un commentaire