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:
text
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:
text
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:
text
10
Multiple Parameters
Functions can take more than one parameter:
python
def add(a, b):
return a + b
print(add(3, 4))
Output:
text
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")
Functions make your code shorter, cleaner, and easier to fix!