๐ ๏ธ Section project: the temperature converter
Section 6: FunctionsLesson 6.3 ยท โฑ 10 min
๐ฏ Project goal
A function that converts temperature from Celsius to Fahrenheit, and we use it for several numbers.
def to_f(c):
return c * 9 / 5 + 32
for c in [0, 25, 37, 100]:
print(c, "C =", to_f(c), "F")
๐ฅ๏ธ The output in Robo Python:
๐ Open the code in Robo Python โ0 C = 32.0 F 25 C = 77.0 F 37 C = 98.6 F 100 C = 212.0 F

๐ Another example: the other way: from Fahrenheit
C = (F โ 32) ร 5 รท 9.
def to_c(f):
return (f - 32) * 5 / 9
print(to_c(212))
print(to_c(32))
๐ฅ๏ธ The output in Robo Python:
๐ Open the code in Robo Python โ100.0 0.0
โ๏ธ Practise
Try the lesson's examples here: copy the code, change it, and click โถ Run.
โ๏ธ Practise here in the lessonโ Close the labor open the lab in a new page โ
๐ฏ Challenge yourself
Easy
A km_to_m function: a kilometre = 1000 metres.
๐ Show the solution๐ Hide the solution
def km_to_m(km):
return km * 1000
print(km_to_m(3.5))
๐ฅ๏ธ The output in Robo Python:
๐ Open the code in Robo Python โ3500.0
Result: 3500
Medium
A table: temperatures from 0 to 40 in steps of 10, and what they are in Fahrenheit.
๐ Show the solution๐ Hide the solution
def to_f(c):
return c * 9 / 5 + 32
for c in range(0, 41, 10):
print(c, "C =", to_f(c), "F")
๐ฅ๏ธ The output in Robo Python:
๐ Open the code in Robo Python โ0 C = 32.0 F 10 C = 50.0 F 20 C = 68.0 F 30 C = 86.0 F 40 C = 104.0 F
Result: from 0 C = 32.0 F to 40 C = 104.0 F
Hard
Ask for the temperature and the unit (C or F) and convert it.
๐ Show the solution๐ Hide the solution
When the program asks, we type: 98.6, then F.
def to_f(c):
return c * 9 / 5 + 32
def to_c(f):
return (f - 32) * 5 / 9
t = float(input("Temperature: "))
unit = input("Unit (C or F): ")
if unit == "C":
print(to_f(t), "F")
else:
print(round(to_c(t), 1), "C")
๐ฅ๏ธ The output in Robo Python:
๐ Open the code in Robo Python โTemperature: 98.6 Unit (C or F): F 37.0 C
Result: 98.6 F = 37.0 C

