0
hours = 0.0
while hours != int:
    try:
        hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
        break
    except ValueError:
        print "Invalid input. Please enter an integer value."
        hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))

Okay, so I am trying to make sure a user inputs an integer value. If I don't type in an integer the "Invalid input, Please enter an integer value." will come up and I will then enter in another non integer value and will end up getting an error message. So why does it work the first time and not the second?

John Emaus
  • 19
  • 2

1 Answers1

4

Use break statement to get out of the loop when user input correct integer string.

hours = 0.0
while True:
    try:
        hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
        break  # <---
    except ValueError:
        print "Invalid input. Please enter an integer value."
        # No need to get input here. If you don't `break`, `.. raw_input ..` will
        #   be executed again.

BTW, hours != int will always yield True. If you want to check type of the object you can use isinstance. But as you can see in the above code, you don't need it.

falsetru
  • 357,413
  • 63
  • 732
  • 636