Python excepting input only if in range

为君一笑 提交于 2020-01-02 04:07:11

问题


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.


回答1:


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.




回答2:


There are several items in your code that could be improved.

(1) Most importantly, it's not a good idea to just catch a generic exception, you should catch a specific one you are looking for, and generally have as short of a try-block as you can.

(2) Also,

  if input in range(1,10):

would better be coded as

  if 1 <= input < 10:

as currently function range() repeatedly creates a list of values form 1 to 9, which is probably not what you want or need. Also, do you want to include value 10? Your prompt seems to imply that, so then you need to adjust your call to range(1, 11), as the list generated will not include the upper-range value. and the if-statement should be changed to if 1 <= input <= 10:



来源:https://stackoverflow.com/questions/11594605/python-excepting-input-only-if-in-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!