[Tutor] If elif not working in comparison

orbitz orbitz at drorbitz.ath.cx
Mon Mar 28 16:27:11 CEST 2005


Floats are inherintly inprecise.  So if thigns arn't working like you 
expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same 
number than you think.

On Mar 28, 2005, at 6:32 AM, Kent Johnson wrote:

> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list