Lesson 13: Functions
A function is a reusable block of code designed to perform a specific task. Instead of writing the exact same lines of code over and over again throughout your program, you can wrap them inside a function and call it whenever you need it.
Why Do We Use Functions?
- Code Reusability: Write the logic once and use it as many times as you want without copying and pasting.
- Organization: Functions break large, complex programs down into smaller, easy-to-read pieces.
- Easier Maintenance: If you need to fix a bug or change how something works, you only update it in one place.
1. Defining and Calling a Function
In Python, we use the def keyword to define a function, followed by its name, round brackets (), and a colon :. The code inside the function must be indented.
# Defining the function
def greet():
print("Hello! Welcome to Python functions.")
# Calling (running) the function
greet()
2. Function Parameters & Arguments
Functions can accept input data called parameters. You pass values (known as arguments) inside the brackets when calling the function.
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alex") # Output: Hello, Alex!
greet_user("Sarah") # Output: Hello, Sarah!
You can also pass multiple parameters:
def add_numbers(a, b):
result = a + b
print(f"The sum is: {result}")
add_numbers(5, 10) # Output: The sum is: 15
3. The return Statement
Instead of just printing a result inside a function, most functions send a value back to the main program using the return keyword. Once Python hits a return statement, the function immediately stops executing and gives back the result.
def multiply(x, y):
return x * y
# We store the returned value in a variable
total = multiply(4, 3)
print(total) # Output: 12
Default Parameter Values
You can provide default values for parameters. If an argument isn't passed when calling the function, Python uses the default value:
def greet_person(name="guest"):
print(f"Welcome, {name}!")
greet_person() # Output: Welcome, guest!
greet_person("Emily") # Output: Welcome, Emily!
Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 13