0

I've been working on a sleep calculator that needs a validation error message. The code that I need to validate is:

hourspernight = int(input("How many hours do you sleep in a day?")
hoursperweek = hourspernight * 7
input("You Sleep for",hoursperweek,"hours every week!")

I need to add validation so that, if the user inputs a character that is not an integer, it shows an error message asking for an integer.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

Use a try/except inside a while loop which will keep asking for input until the user enters something valid:

while True:
    try:
       hourspernight = int(input("How many hours do you sleep in a day?"))
       break
    except ValueError:
        print("Invalid input")

hoursperweek = hourspernight * 7
print ("You Sleep for {} hours every week!".format(hoursperweek))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thanks soo much, funnily enough i found the answer half an hour ago my ones a bit different though as i added another validation wait ill show you – Infynite Life Jan 27 '15 at 23:28
  • I presumed the second input should have been a print as you don't seen to be asking anything, you can either add a separate except block or just add it to the same – Padraic Cunningham Jan 27 '15 at 23:44