[Tutor] check_range

Kent Johnson kent37 at tds.net
Wed Dec 15 13:43:57 CET 2004

Brian van den Broek wrote:
> DogWalker said unto the world upon 2004-12-15 00:32:
>> "Brian van den Broek" <bvande at po-box.mcgill.ca> said:
>>> 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
>> Shorter:
>>     def check_in_range(value):
>>         return 9 < value < 90
> Indeed. Good one. I never seem to think of such very direct ways, but 
> there you have it. It might say more about my psychology than anything 
> else, but I think I'd be tempted to put a brief comment on that code. 
> (Such as # returns True if the test, False otherwise.) My guess is that 
> if I had to read it more than twice, the time spent writing the comment 
> would be more than regained in spending less time scratching my head. 
> This might also be a matter of little experience, too.

Of course put a comment if you like, but this is very concise, idiomatic code and I hope you will 
get used to it so the comment is not needed.

The value of the expression '9 < value < 90' is actually a boolean True or False, so testing the 
expression and explicitly returning True or False is redundant. You are using four lines of code to 
do the work of one.

In general, Python's flexibility with boolean values is a strength of the language and I recommend 
you try to get comfortable with it.

> At any rate, I certainly would agree that yours is bound to be better in 
> any situation where speed of execution mattered a lot.

Or readability, IMO.


> Best,
> Brian vdB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list