ุงู†ุชู‚ู„ ู„ู„ู…ุญุชูˆู‰
Robo EgyptRobo Egypt
โ˜ฐ Course contents
Robo Python: home
0. Lab tour1
1. The start5
2. Variables and input5
3. Conditions5
4. Loops5
5. Lists4
6. Functions4
7. Drawing with the turtle3
8. The project: the guess-the-number game3
9. Strings in depth1
10. Dictionaries (dict)3
11. Randomness and errors3
12. Classes and objects (class)2
13. Pro drawing and charts3
14. The final project: the quiz game2

๐Ÿ› ๏ธ 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:
0 C = 32.0 F
25 C = 77.0 F
37 C = 98.6 F
100 C = 212.0 F
๐Ÿ Open the code in Robo Python โ†—
The example in Robo Python: the code on the right and what appeared on the left
The example in Robo Python: the code on the right and what appeared on the left

๐Ÿ“Œ Another example: the other way: from Fahrenheit

C = (F โˆ’ 32) ร— 5 รท 9.

๐Ÿ The other way: from Fahrenheit
def to_c(f):
    return (f - 32) * 5 / 9

print(to_c(212))
print(to_c(32))
๐Ÿ–ฅ๏ธ The output in Robo Python:
100.0
0.0
๐Ÿ Open the code in Robo Python โ†—
โœ๏ธ Practise
Try the lesson's examples here: copy the code, change it, and click โ–ถ Run.
โœ๏ธ Practise here in the lessonor open the lab in a new page โ†—

๐ŸŽฏ Challenge yourself

Easy

A km_to_m function: a kilometre = 1000 metres.

๐Ÿ‘€ Show the solution
๐Ÿ Solution
def km_to_m(km):
    return km * 1000

print(km_to_m(3.5))
๐Ÿ–ฅ๏ธ The output in Robo Python:
3500.0
๐Ÿ Open the code in Robo Python โ†—

Result: 3500

Medium

A table: temperatures from 0 to 40 in steps of 10, and what they are in Fahrenheit.

๐Ÿ‘€ Show the solution
๐Ÿ 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:
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
๐Ÿ Open the code in Robo Python โ†—

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

When the program asks, we type: 98.6, then F.

๐Ÿ Solution
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:
Temperature: 98.6
Unit (C or F): F
37.0 C
๐Ÿ Open the code in Robo Python โ†—

Result: 98.6 F = 37.0 C

Finished the lesson? Mark it so your progress counts.