End-To-End Example: Temperature Conversions

First we will write two conversion functions:

  • f2c convert Fahrenheit temperature to Celsius
  • c2f convert Celsius temperature to Fahrenheit

Next, we'll test the functions by calling them. Once they're correct we will write our program to input a temperature and units, then convert to the other unit.


In [1]:
## function f2c
# argument: temp in F
# return temp in C

def f2c(temp_in_f):
    return (temp_in_f-32) * (5/9)

In [2]:
## function c2f
# argument : temp in C
# return: temp in F

def c2f(temp_in_c):
    return (9/5)*temp_in_c + 32

In [4]:
## Let's test our functions

#should be 100 C
print (f2c(212))

#shouod be 32 F
print(c2f(0))


100.0
32.0

In [11]:
## Main program here
temp = float(input("Enter temperature: "))
unit = input("In which unit [F/C] ?")
if unit == 'F':
    tempc = f2c(temp)
    print("%.1f in F is %.1f in C" % (temp,tempc))
elif unit =='C':
    tempf = c2f(temp)
    print("%.1f in C is %.1f in F" % (temp,tempf))
else:
    print("I don't understand unit %s" % (unit))


Enter temperature: 25
In which unit [F/C] ?C
25.0 in C is 77.0 in F

In [ ]: