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:
🐍 Open the code in Robo Python ↗Hello Sara 👋 Hello Omar 👋

📌 Another example: a function with two inputs
def takes the name and the age and prints a sentence.
def card(name, age):
print(name, "is", age, "years old")
card("Ali", 10)
card("Mona", 12)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Ali is 10 years old Mona is 12 years old
✍️ 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 hello function that prints Hello three times.
👀 Show the solution🙈 Hide the solution
def hello():
for i in range(3):
print("Hello")
hello()
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Hello Hello Hello
Result: Hello three times
Medium
A function line(n) that prints a line of n dashes.
👀 Show the solution🙈 Hide the 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🙈 Hide the 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.

