انتقل للمحتوى
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

def: make a new command

Section 6: FunctionsLesson 6.1 · ⏱ 8 min

A function is a group of lines with a name; we write it once and use it many times. We make it with def.

def greet(name):
    print("Hello", name, "👋")

greet("Sara")
greet("Omar")
🖥️ The output in Robo Python:
Hello Sara 👋
Hello Omar 👋
🐍 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: a function with two inputs

def takes the name and the age and prints a sentence.

🐍 A function with two inputs
def card(name, age):
    print(name, "is", age, "years old")

card("Ali", 10)
card("Mona", 12)
🖥️ The output in Robo Python:
Ali is 10 years old
Mona is 12 years old
🐍 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 hello function that prints Hello three times.

👀 Show the solution
🐍 Solution
def hello():
    for i in range(3):
        print("Hello")

hello()
🖥️ The output in Robo Python:
Hello
Hello
Hello
🐍 Open the code in Robo Python ↗

Result: Hello three times

Medium

A function line(n) that prints a line of n dashes.

👀 Show the solution
🐍 Solution
def line(n):
    print("-" * n)

line(5)
line(10)
🖥️ The output in Robo Python:
-----
----------
🐍 Open the code in Robo Python ↗

Result: a line of 5, then a line of 10

Hard

A function box(w, h) that draws a rectangle of #.

👀 Show the solution
🐍 Solution
def box(w, h):
    for i in range(h):
        print("#" * w)

box(6, 3)
🖥️ The output in Robo Python:
######
######
######
🐍 Open the code in Robo Python ↗

Result: three lines of 6 # signs.

Finished the lesson? Mark it so your progress counts.