[Tutor] Finding if a passed variable is within to set parameters

Alan Gauld alan.gauld at btinternet.com
Tue Oct 11 02:46:47 CEST 2011

On 10/10/11 23:13, Mike Nickey wrote:

> What I want is to have the user be able to enter 1 through 8 and have
> the information pass fine but anything else would cause the user to
> repeat the process.

if not (1 <= value <= 8):
    # handle error
else: # carry on as planned

> I'm using a while loop to try to do this.

You will need a loop if you want to keep trying till
the user gets it right

> The only other thing I can think of to do is incorporate
 > a list and see if I can check the list to complete this.

That's another option, particularly common with characters:

if ch not in "yYnNqQ":
     # deal with error
else: # carry on

For your case it could be

if value not in range(1,9):
     # handle error
else: # carry on

But the <=> test above is more efficient, especially
for large ranges.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list