[Tutor] If elif not working in comparison

Kent Johnson kent37 at tds.net
Mon Mar 28 13:32:27 CEST 2005


gerardo arnaez wrote:
> Hi all,
> I am trying to get a value dependant on initial vlaue inputed
> Depending on the value, I want the functiont to return a percentage
> For some reason, It seems to skip the first if state and just print
> out the 1st elif
> not sure what is going.

Are you sure you are passing a number to the function? If you are passing a value you received from 
raw_input it is a string.

> also, is there a cleaner way to write this?

I would use a list of value pairs. It separates the data from the code so it is easier to see what 
is going on. Here is a version that does this. It also ensures that the input value is a float:

def INRadjust(x):
     cutoffs = [
         (1, .15),
         (1.5, .12),
         (1.75, .1),
         (1.9, .05),
         (3.1, 0),
         (4.1, -.1),
         (5.1, -.2),
         (6.1, -.25),
         (7.1, -.3),
     ]

     x = float(x)  # make sure x is a number
     for cutoff, value in cutoffs:
         if x < cutoff:
             return value

     print "Notify doctor"

Kent
> -=-------------------------
> 
> 
> #! /usr/bin/env python
> '''
> Calulate the percent increase in dose given an INR value.
> '''
> 
> def INRadjust(x):
>     if x < 1:
>         return .15
>     elif x < 1.5:
>         return .12
>     elif x < 1.75:
>         return .1
>     elif x < 1.9:
>         return .05
>     elif x < 3.1:
>         return 0
>     elif x < 4.1:
>         return -.1
>     elif x < 5.1:
>         return -.2
>     elif x < 6.1:
>         return -.25
>     elif x < 7.1:
>         return -.3
>     else:
>         print "Notify Doctor"
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list