[Tutor] check_range
Marc Gartler
gartler at express.cites.uiuc.edu
Wed Dec 15 03:00:05 CET 2004
Thanks all, that was very helpful!
On Tuesday, December 14, 2004, at 06:39 PM, Brian van den Broek wrote:
> 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"
>> else:
>> return "True"
>> ...this gets called later via:
>> if check_range(input):
>> done = "True"
>> return int(input)
>> What am I doing wrong?
>> Thanks!
>
> Hi Marc,
>
> 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
> False
> >>> 9 < 10 < 90
> True
>
> This sort of thing is an "off by 1 error" and will happen to you all
> the time :-(
>
> 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
> return in_range
>
> >>> check_in_range(35)
> 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):
> print range(myrange)
> print range(2,5)
> if range(myrange) != range(2,5):
> return "False"
> else:
> return "True"
>
> >>> check_range(3)
> [0, 1, 2]
> [2, 3, 4]
> 'False'
>
> The problem would have likely been much more clear.
>
> HTH,
>
> Brian vdB
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list