Before we can use a user-defined function, we need to create it. To declare a function, you use the def keyword followed by the function name, parentheses, and a colon. You can also specify parameters inside the parentheses if your function needs to accept input values. The function body is indented below the declaration.
Here’s an example of a simple function that takes two parameters and prints their sum:
def add_numbers(a, b):
sum = a + b
print("The sum is:", sum)
#
By itself, the code above won’t actually output anything. Once we’ve created a function, we need to call it in order for anything to execute. To call a function, you simply write the function name followed by parentheses, and provide the required arguments if any. Here’s how you can call the add_numbers function:
# declare the function
def add_numbers(a, b):
sum = a + b
print("The sum is:", sum)
# call the function:
add_numbers(5, 10)
add_numbers(6, 7)
# output:
# The sum is: 15
# The sum is: 13
The above code is useful for printing the sum of two numbers to the screen, but it may often be more practical to store the sum of two numbers in a variable, so that we could further manipulate it as we wish. Rather than simply displaying the value to the screen, we can use the keyword return in order to hand the value back to the user, so that we could store it in a variable for instance. For example:
def add_numbers(a, b):
sum = a + b
return sum # return basically means "output"
result = add_numbers(5, 10)
print("The sum is:", result)
Notice how in the above segment of code, we choose to return the sum within the function rather than print it out right away. Then, when we call it, we have the ability to store that value in the result variable by using the = sign. Here’s another, more practical example, where we could return what the average value of a list is:
# declare a function to traverse a list of numbers, add them to a running sum, and then divide the sum by the number of values to find the average:
def average(list_of_nums):
sum = 0
for n in list_of_nums:
sum = sum + n
return sum / len(list_of_nums)
test_scores = [94, 87, 88, 71, 90, 100, 79]
class_average = average(test_scores) # call the function
print(class_average)
# output: 87.0
The nice thing about structuring our code using functions is that we can call functions as many times as we want once we’ve declared them. This means that if there are repetitive chunks of code within your program, it may make sense to define that chunk within a function, so that you can more easily call it using one line of code.
Using functions provides us with several advantages: