[Tutor] am I missing another simpler structure?

Brian van den Broek bvande at po-box.mcgill.ca
Thu Dec 16 01:58:56 CET 2004


Hi all,

in Marc's check_range thread, I had proposed:

def check_in_range(value):

     in_range = False
     if 9 < value < 90:
         in_range = True
     return in_range

and DogWalker suggested the better:

def check_in_range(value):
     return 9 < value < 90

As I mentioned, I feel as though I have a mental block getting in the 
way of coming up with code in the smoother fashion of the second snippet 
above. As I have been making a lot of use of a construct (pattern?) 
similar to my code above, wherein I try something, and return True if it 
works, False if it doesn't, I've begun to wonder if I am overlooking a 
improvement similar to that in DogWalker's suggestion. As an example of 
the sort of thing I have been doing:

import datetime
def is_leap_year(year):
     '''-> boolean

     Returns True or False as year is, or is not, a leap year.
     '''
     is_leap = True
     try:
         datetime.date(year, 2, 29)
     except ValueError:
         is_leap = False
     return is_leap

Please ignore that there is a function in the calendar module to do 
exactly this, and that, as that library function does, it could be done 
by simply testing if the leap year conditions are met. In the general 
case, it doesn't seem that there will always be an easy conditional 
test. This function here was written so as to illustrate the structure 
I'm interested in, without the complications of the details of actual 
cases I have used.

(I hope that's clear enough--it felt much clearer before I'd spent the 
time drafting a post.)

Best to all,

Brian vdB


More information about the Tutor mailing list