Python excepting input only if in range
Asked Answered
I

3

6

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.

Ide answered 21/7, 2012 at 17:59 Comment(3)
This seems like two completely separate questions... It's best to ask one question at a time. If you get two answers: one to the first question, and another to the second, how do you know which to accept?Weisman
Do you know that range(1,10) doesn't include 10? Your raw_input text suggests that you might want 10 to be acceptable.Presbyterial
Yes I knew 10 was out of the range, my mistake was to include it in the raw_input statement. Sorry just quickly put values in as an example. Thanks.Ide
H
7

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.

Heilman answered 21/7, 2012 at 18:3 Comment(4)
That should be < 10 given range(1, 10) by OPDamaging
I always thought an else statement could only follow an if or elif statement. I now know that is not so.Ide
@Ide Did you know that for and while loops may also be followed by an else statement in some cases?Delta
@lazyr No but I do now. Thanks! Also the example on the link is a about a million times shorter than the prime number program I wrote a few months ago... nice.Ide
D
1

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:

Damaging answered 21/7, 2012 at 18:2 Comment(3)
this is not a problem, it's just slowerHeilman
But it is a valid answer to the first "question". The OP wrote "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!" Personally though I feel that the OPs first "question" should be deleted or moved into a separate question, perhaps on codereview.SE.Weisman
Thanks Levon. Everything you said makes sense.Ide
A
-2

You can use this code:

def read_int(prompt, min, max):
    while True:
        try:
            val = int(input(prompt))
        except ValueError:
            print('Error: wrong input')
        else:
            if(min <= val < max): # this is faster
                break
            else:
                print('Error: the value is not within permitted range (min..max)')
    return val    


v = read_int("Enter a number from -10 to 10: ", -10, 10)

print("The number is:", v)
Aurist answered 8/4, 2022 at 11:41 Comment(1)
Please explain the code, why it solves the problem, how, etcEnarthrosis

© 2022 - 2024 — McMap. All rights reserved.