You can save a block of code in a function so that you can re-use it.
This is a very important concept in programming.
Here’s an example of an “add_numbers” function.
1 2 3 4 5 6 7 8 9 10 11 | # Function example # adding numbers def add_numbers(x, y): z = x + y return z print(add_numbers(5, 10)) print(add_numbers(2, 6)) |
Output:
1 2 3 4 | 15 7 |
Here’s a more complicated function using a for
loop and if
statement.
1 2 3 4 5 6 7 8 9 10 11 | vegetable_list = ["broccoli", "carrots", "spinach"] def my_favorite_foods(food_list): food_i_like = ["broccoli", "spinach", "bananas"] for food in food_list: if food in food_i_like: print(food) my_favorite_foods(vegetable_list) |
Output:
1 2 3 4 | broccoli spinach |
We can re-use that function for a different food list.
1 2 3 4 5 6 7 8 9 10 11 | fruit_list = ["apples", "pears", "bananas", "blueberries"] def my_favorite_foods(food_list): food_i_like = ["broccoli", "spinach", "bananas"] for food in food_list: if food in food_i_like: print(food) my_favorite_foods(fruit_list) |
Output:
1 2 3 | bananas |
To assign the result of a function to a variable we need to use return
.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Example using a dictionary birthdays = {"John" : "2/2/1985", "Mary": "6/12/1998"} def find_birthday(first_name, birthday_dictionary): for name in birthday_dictionary: if name == first_name: return birthday_dictionary[name] Marys_birthday = find_birthday("Mary", birthdays) print(Marys_birthday) |
Output:
1 2 3 | 6/12/1998 |
Functions can also call other functions.
Let’s use the “add_numbers” function inside the “subtract_numbers” function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | def add_numbers(x, y): z = x + y return z def subtract_numbers(a, b): c = a - b return c # 10 - (2 + 3) = 5 math_calculation = subtract_numbers(10, add_numbers(2, 3)) print(math_calculation) |
Output:
1 2 3 | 5 |