Brian van den Broek
bvande at po-box.mcgill.ca
Wed Dec 15 01:39:06 CET 2004
Marc Gartler said unto the world upon 2004-12-14 18:12:
> Hi all,
> I am fairly new to both Python & programming, and am attempting to
> create a function that will test whether some user input is an integer
> between 10 and 89, but the check isn't happening...
> def check_range(myrange):
> if range(myrange) != range(10,89):
> return "False"
> return "True"
> ...this gets called later via:
> if check_range(input):
> done = "True"
> return int(input)
> What am I doing wrong?
Welcome to Python and the list. :-)
Others have pointed out how to solve your immediate problem with in or a
comparison, and that you can just return True and False unquoted. (They
are special builtin objects, so making strings for them isn't needed.)
A minor correction to Kent's suggestion, though. He suggested to use
10 < x < 90, but since I gather you want 10 to return True, you need
9 < x < 90:
>>> 10 < 10 < 90
>>> 9 < 10 < 90
This sort of thing is an "off by 1 error" and will happen to you all the
I have a some style suggestions for you, too.
Try it this way:
>>> def check_in_range(value):
in_range = False
if 9 < value < 90:
in_range = True
This way, by setting a name to point to False, and over-riding that when
the test is met, there is only a single return statement. That is often
considered a good thing. This function is too small for it to matter
lots, but have multiple returns can make the debugging a bit harder.
Another tip is that for debugging such things it often helps to use
print statements when things don't go as expected. If you'd added them
to your original function like so:
>>> def check_range(myrange):
if range(myrange) != range(2,5):
[0, 1, 2]
[2, 3, 4]
The problem would have likely been much more clear.
More information about the Tutor