Python except range input only

Hi, I want to get a number from a user and only with the exception of input within a certain range.

The following shows what works, but I noob thought while it works. There is no doubt that this is a more elegant example ... just an attempt not to fall into bad habits!

One thing I noticed is that when I run the CTL + C program, it will not rip me out of the loop and throw an 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 not a number") 

All help is much appreciated.

+4
source share
2 answers

Ctrl + C raises a KeyboardInterruptException , your try … except block will catch 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\ 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 that you expect (so that there are no side effects, like your problem with Ctrl + C). You should also leave the try … except block as short as possible.

+4
source

There are several elements in the code that can be improved.

(1) Most importantly, it is not a good idea to just catch the general exception, you have to catch the specific one you are looking for, and usually have as few try blocks as possible.

(2) In addition,

  if input in range(1,10): 

better to code as

  if 1 <= input < 10: 

as a function at the moment, range () repeatedly creates a list of values ​​from 1 to 9 , which is probably not what you need or need. Also, do you want to include a value of 10 ? This seems to be a hint to you, so you need to set your call to range(1, 11) , since the generated list will not include the value of the upper range. and the if value should be changed to if 1 <= input <= 10:

+1
source

All Articles