Problems with if/elif statement syntax

Scott David Daniels Scott.Daniels at Acm.Org
Thu Nov 22 12:37:39 EST 2007


Neil Webster wrote:
> Hi all,
> 
> I'm sure I'm doing something wrong but after lots of searching and
> reading I can't work it out and was wondering if anybody can help?
> 
> I've got the following block of code:
> 	if a >= 20 and a < 100:
> 		if c == "c":
> 			radius = 500
> 		else:
> 			radius = 250
> 	elif (a >= 100) and (a < 500):
> 		radius = 500
> 	elif (a >= 500) and (a < 1000):
> 		radius = 1000
> 	elif (a >= 1000) and (a < 3000):
> 		radius = 1500
> 	elif (a >= 3000) and (a < 5000):
> 		radius = 2000
> 	else:
> 		radius = 4000
> 
> No matter what value goes in for 'a' the radius always comes out as
> 4000.
> 
> What am I doing wrong?
> 
> Cheers
> 
> Neil
You might try something like:

     BOUNDS = [(500, 500), (1000, 1000),
               (3000, 1500), (5000, 2000), (0, 4000)]
     if a < 20:
         raise ValueError('Too tiny: %r' % a)
     if a < 100:
         if c == "c":
             radius = 500
         else:
             radius = 250
     else:
         for limit, radius in bounds:
             if a < limit:
                 break


on the theory that it makes it easier to see what you
are driving the number towards.  I'd even add an upper bound
check myself, so I could see other garbage coming in.

-Scott



More information about the Python-list mailing list