Help with python functions?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 23 09:56:45 EDT 2013


On Mon, 23 Sep 2013 05:57:34 -0700, kjakupak wrote:

> Can anyone help me with any of these please? Much appreciated. I
> honestly don't even know how to start them

Start by writing a function that does nothing:

def nothing():
    pass


Now change it so that it takes three arguments:

T, a temperature
from_unit, the temperature scale to convert from 
to_unit, the temperature scale to convert to


def nothing(T, from_unit, to_unit):
    pass


Now change the name of the function to match the name you were told to 
use:


def temp(T, from_unit, to_unit):
    pass


Now you're a third of the way done! All you need do now is write the 
logic of the function, and make sure it works.

What's the logic of the function? There are four cases:

(1) If from_unit is "C", and to_unit is "F", you need to convert T from 
Celsius to Fahrenheit. I'm sure you can find the formula for that if you 
google it.

(2) otherwise, if from_unit is "F", and to_unit is "C", you need to 
convert T from Fahrenheit to Celsius. Again, the formula to use is 
readily available in about a million reference books and web sites.

(3) otherwise, if from_unit and to_unit are the same (both "C", or both 
"F"). In this case, there is no conversion needed and you can just return 
T unchanged.

(4) otherwise, one or both of from_unit or to_unit must be something 
other than "C" or "F", e.g. "Z" or "Hello". In that case, you have to 
deal with the error. Have you learned about exceptions yet?

It may be acceptable to ignore case #4 -- you'll have to ask your teacher.

Then try it out and make sure it works! For example:

107.6°F == 42°C
-15°C = 5°F


Now you're done! On to the next function... 




-- 
Steven



More information about the Python-list mailing list