Functions
Functions allow you to group code into reusable blocks.
Instead of writing the same code multiple times, you can define a function once and use it whenever you need it.
Why use functions
Functions help you:
- avoid repeating code
- organize your program better
- make your code easier to read and maintain
Defining a function
In Python, you define a function using the def keyword:
def greet():
print("Hello")
Explanation
defis used to define a functiongreetis the name of the function()can contain parameters (we will see this next):starts the function body- the indented block is the code that runs when the function is called
Calling a function
Defining a function does not run it. You need to call it:
greet()
When this line runs, the code inside the function is executed.
Functions with parameters
Functions can take inputs, called parameters. Parameters allow you to pass data into a function so it can work with different values each time it is called.
def greet(name):
print("Hello " + name)
In this example, name is a parameter. When the function is called, the value you pass (called an argument) is assigned to this parameter.
greet("Alice")
greet("Bob")
Each time the function is called, it runs the same code but with a different value. This is what makes functions flexible and reusable.
A function can have multiple parameters:
def add(a, b):
print(a + b)
Here, a and b are parameters. When calling the function, you must provide values for both:
add(3, 5)
It is important to keep the order of parameters in mind, since values are assigned based on their position.
You can think of parameters as placeholders that will be filled when the function is used.
Variable number of parameters
In some situations, you may not know in advance how many arguments will be passed to a function. Python allows you to handle this using special syntax.
Using *args
The *args syntax allows a function to accept any number of positional arguments.
def add_numbers(*args):
total = 0
for number in args:
total += number
return total
You can call this function with different numbers of arguments:
print(add_numbers(1, 2))
print(add_numbers(1, 2, 3, 4))
Inside the function, args behaves like a tuple containing all the values that were passed.
Using **kwargs
The **kwargs syntax allows a function to accept any number of keyword arguments.
def print_user_info(**kwargs):
for key, value in kwargs.items():
print(key, value)
Example usage:
print_user_info(name="Alice", age=22)
In this case, kwargs is a dictionary where:
- the keys are the parameter names
- the values are the arguments passed to the function
When to use them
These patterns are useful when writing flexible functions that need to handle different inputs. However, they should be used carefully, as they can make code harder to read if overused.
Recursive functions
A recursive function is a function that calls itself.
This may sound unusual at first, but it is a useful technique for solving problems that can be broken down into smaller, similar steps.
Here is a simple example:
def countdown(n):
if n == 0:
print("Done")
else:
print(n)
countdown(n - 1)
When you call:
countdown(3)
The function will call itself multiple times, each time with a smaller value, until it reaches the base case (n == 0).
Every recursive function must have a base case. This is the condition where the function stops calling itself. Without it, the function would run indefinitely.
Recursive functions are often used for problems involving repetition or structures like trees, but for now it is enough to understand the idea of a function calling itself and gradually reaching a stopping point.
Returning values
Functions can also return values using the return keyword:
def add(a, b):
return a + b
You can store the result in a variable:
result = add(3, 5)
print(result)
Explanation
returnsends a value back to where the function was called- after
return, the function stops executing
Example
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(4))
print(is_even(7))
Exercise
- Write a function that takes a number and returns its square
- Write a function that takes a name and prints a greeting message (E.g. :
Hello {name}, nice to meet you!) - Write a function that checks if a number is positive or not
Notes
- Function names should be descriptive (e.g.
calculate_total) - Keep functions small and focused on one task
- Use
returnwhen you need to send data back