7.3 Create user defined functions
7.3a How to create user-defined functions
Creating user-defined functions in Python is straightforward. Functions are defined using the def
keyword, followed by the function name and parentheses containing any parameters. The body of the function contains the code to be executed, and the function can optionally return a value using the return statement.
Here's a step-by-step guide on how to create and use user-defined functions.
-
Define the function - Use the
def
keyword, provide a name for your function, and specify any parameters in parentheses. Then, indent the body of the function. -
Add code to the function body - Write the code that you want to execute when the function is called.
-
Return a value (optional) - Use the
return
statement to return a value from the function. If no return statement is provided, the function returnsNone
by default. -
Call the function - Use the function name followed by parentheses to call the function and pass any required arguments.
Example 7.3.1 - Basic function definition and usage
# Define the function
def greet(name):
"""This function greets the person whose name is passed as an argument."""
print(f"Hello, {name}!")
# Call the function
greet("Keith")
Example 7.3.1 - Output
Hello, Keith!
Example 7.3.2 - Function with a return value
# Define the function
def add(a, b):
"""This function returns the sum of two numbers."""
return a + b
# Call the function and store the result
result = add(3, 5)
# Print the result
print(result)
Example 7.3.2 - Output
8
Example 7.3.3 - Function with default parameter values
# Define the function
def greet(name, greeting="Hello"):
"""This function greets the person with the specified greeting."""
print(f"{greeting}, {name}!")
# Call the function with both arguments
greet("Kim", "Hi")
# Call the function with only the name argument (default greeting will be used)
greet("Sue")
Hi, Kim! Hello, Sue!
Example 7.3.4 - Function with variable number of arguments
# Define the function
def summarize(*args):
"""This function prints the sum of all arguments."""
total = sum(args)
print(f"The sum is: {total}")
# Call the function with a variable number of arguments
summarize(1, 2, 3)
summarize(10, 20, 30, 40)
Example 7.3.4 - Output
The sum is: 6 The sum is: 100
Example 7.3.5 - Function with keyword arguments
# Define the function
def describe_pet(pet_name, animal_type="dog"):
"""This function prints a description of a pet."""
print(f"I have a {animal_type} named {pet_name}.")
# Call the function with keyword arguments
describe_pet(pet_name="Willie", animal_type="hamster")
describe_pet(pet_name="Bella")
Example 7.3.5 - Output
I have a hamster named Willie. I have a dog named Bella.
These examples cover basic and advanced usages of functions in Python, including default parameters, variable-length arguments, and keyword arguments. You can define functions to encapsulate reusable code blocks, making your programs modular and easier to maintain.
7.3b Using return
in functions
In Python, whether or not to use the return
statement in a function depends on the purpose of the function and what you want to achieve with it. Use return
when you need to send a value back to the caller for further use or when you want to exit the function based on a condition. Here's a detailed explanation of when and why to use return
:
1. To output a value - When you want your function to produce a result that can be used later in your code, you use the return
statement to send that result back to the caller. This is useful when you need the function to calculate or fetch data that will be used elsewhere.
Example 7.3.6 - To output a value
Example 7.3.6 - Output
8
2. To exit a function early - You can use return
to exit a function before it reaches the end, typically based on some condition.
Example 7.3.7 - To exit a function early
def check_even(number):
if number % 2 == 0:
return "Even"
return "Odd"
print(check_even(4))
print(check_even(7))
Example 7.3.7 - Output
Even Odd
3. To return multiple values - Python allows functions to return multiple values as a tuple. This can be handy for functions that need to return more than one piece of information. [tuples will be tackled in Section 8]
Example 7.3.8 - To return multiple values
def get_min_max(numbers):
return min(numbers), max(numbers)
min_val, max_val = get_min_max([1, 2, 3, 4, 5])
print(min_val, max_val)
Example 7.3.8 - Output
1 5
7.3c When return is not used
Omit return
(or use it without a value) when the function's primary purpose is to perform an action or cause a side effect, and no value needs to be passed back to the caller.
1. Performing an action without needing a result - If the function's purpose is to perform an action (like printing a message, modifying a global variable, or updating an object) and you do not need to return
any result, you can omit the return statement. By default, such functions return None
.
Example 7.3.9
Example 7.3.9 - Output
Hello, Jake!
2. Side effects - Some functions are designed to cause side effects (like modifying a list or an object, writing to a file, etc.) rather than computing and returning a value.
Example 7.3.10
def add_to_list(my_list, item):
my_list.append(item)
my_list = [1, 2, 3]
add_to_list(my_list, 4)
print(my_list)
Example 7.3.10 - Output
[1, 2, 3, 4]
Exercise 7.3.1 - Write a Python function called calculate_grade
that takes a single argument score
, which is a number between 0 and 100. The function should return the letter grade based on the following scale:
- A for scores 90 and above
- B for scores between 80 and 89
- C for scores between 70 and 79
- D for scores between 60 and 69
- F for scores below 60
Additionally, write code to test this function with different scores and print the results.
Exercise 7.3.1 - Model Answer - Make sure to work out the exercise before checking the model answer.