Help with python functions?

random832 at fastmail.us random832 at fastmail.us
Tue Oct 1 15:02:32 EDT 2013


On Tue, Oct 1, 2013, at 13:53, kjakupak at gmail.com wrote:
> I ended up with these. I know they're only like half right...
> I was wondering if any of you had to do this, what would you end up with?
> 
> # Question 1.a
> def temp(T, from_unit, to_unit):

Assuming this is temperature conversion. You should add a docstring.

>     if from_unit == 'C' or from_unit == 'c':

Consider normalizing the unit with .upper() at the top of the function
so you don't have to do this "or" case in every single section.

>         return 32 + (9/5)*T

You are ignoring the value of to_unit and returning the value in
fahrenheit. 

>     elif from_unit == 'K' or from_unit == 'k':
>         return T + 273.15

This conversion is simply wrong - it's the conversion _from_ celsius
_to_ kelvin.

>     elif from_unit == 'F' or from_unit == 'f':
>         return (5/9)*(T - 32)

You are ignoring the value of to_unit and returning the value in celsius

>     else:
>         return to_unit

I don't know what this is. It's probably wrong.


To implement a temperature conversion function, I would convert from the
unit given to kelvin, then convert from kelvin to the desired unit -
that way you don't have to implement every combination separately.

> # Question 1.b
> def comp(T1, u1, T2, u2):
>     if u1 != u2:
>         T1 = temp(T1, u1)

You're not passing in u2 here.

>     elif T2 > T1:
>         return -1
>     elif T1 > T2:
>         return 1
>     else:
>         return 0

> # Question 2
> def P(p_0, t, i):
>     Amount = P(1 + (i/100))
>     return P(1 + (t * i/12))

I don't know what this is.

Is this for homework?



More information about the Python-list mailing list