Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

error handling - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...