Exerpad
Lesson · Chapter: Functions+10 XP for reading

Building Your Own Commands

Functions let you create your own reusable blocks of code, like building your own commands!

Defining a Function

Use def to create a function:

python
def greet():
print("Hello there!")

greet()
Output
Press Run to see the output.

Output:

Hello there!

Functions with Parameters

Parameters let you pass information to a function:

python
def greet(name):
print(f"Hello, {name}!")

greet("Alex")
greet("Sam")
Output
Press Run to see the output.

Output:

Hello, Alex!
Hello, Sam!

Returning Values

Use return to send a value back:

python
def double(n):
return n * 2

result = double(5)
print(result)
Output
Press Run to see the output.

Output:

10

Multiple Parameters

Functions can take more than one parameter:

python
def add(a, b):
return a + b

print(add(3, 4))
Output
Press Run to see the output.

Output:

7

Why Use Functions?

Without functions, you'd repeat the same code over and over:

python
# Without functions — lots of repeated code
print("Hello, Alex!")
print("Hello, Sam!")
print("Hello, Jordan!")

# With functions — much cleaner!
def greet(name):
print(f"Hello, {name}!")

greet("Alex")
greet("Sam")
greet("Jordan")
Output
Press Run to see the output.

Functions make your code shorter, cleaner, and easier to fix!