Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python excepting input only if in range

Hi I want to get a number from user and only except input within a certain range.

The below appears to work but I am a noob and thought whilst it works there is no doubt a more elegant example... just trying not to fall into bad habits!

One thing I have noticed is when I run the program CTL+C will not break me out of the loop and raises the exception instead.

while True:
  try:
    input = int(raw_input('Pick a number in range 1-10 >>> '))
    # Check if input is in range
    if input in range(1,10):
      break
    else:
      print 'Out of range. Try again'
  except:
    print ("That's not a number")

All help greatly appreciated.

like image 683
hemmy Avatar asked Jul 21 '12 17:07

hemmy


People also ask

How do I allow only certain inputs in Python?

To only accept numbers as user input: Use a while True loop to loop until the user enters a number. Use the float() class to attempt to convert the value to a floating-point number. If the user entered a number, use the break statement to break out of the loop.

How do you check if an input is within a range in Python?

To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range. You can also check the other way around using not to the existing syntax.

Why does Python use except instead of catch?

The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.


1 Answers

Ctrl+C raises a KeyboardInterruptException, your try … except block catches this:

while True:
   try:
       input = int(raw_input('Pick a number in range 1-10 >>> '))
   except ValueError: # just catch the exceptions you know!
       print 'That\'s not a number!'
   else:
       if 1 <= input < 10: # this is faster
           break
       else:
           print 'Out of range. Try again'

Generally, you should just catch the exceptions you expect to happen (so no side effects appear, like your Ctrl+C problem). Also you should keep the try … except block as short as possible.

like image 167
dav1d Avatar answered Nov 03 '22 07:11

dav1d