Functions are one of the most important topics to master when programming in Python. They help us organize our code, make it easier to understand, avoid repeating code, and make our program run more efficiently. That’s a lot of benefits! Up to this point, without functions, our program runs like a long morning to do list:
Functions allow us to break the long list into conceptual blocks of tasks, where each block would be a specific function:
When we use these morning functions, our code is much easier to read and understand:
And if your brother wakes up and wants toast and eggs as well, you can call those functions again with only 2 lines instead of the original 11:
The same logic above applies to using functions in Python. Functions complete a specific job that may require a series of tasks. When we want to run the function, all we have to do is define the function, specifying the desired tasks or commands, and then call the function to run through those tasks. We can even give the function inputs, called parameters, that provide extra information for the function to use – like the number of eggs desired for the Make Eggs function above.
Take a look at the following slides to see an example in Python:
As you can see from the last slide, using the triple_number()
function makes our program much more efficient.
Here are a few important points when making functions in your program:
triple_number()
should not triple a number AND add 10. That would be confusing.Take a look at this example in the code editor below.
num
outside of the function? Try writing print(num)
outside of the function. def
when you are defining the triple_number()
function. What happens?This next example takes in two parameters in order to calculate the area and perimeter of a rectangle.
w
for width and then l
for length, in that order. What happens if you reverse the numbers in a call statement?
The code snippet below comes from a wedding invite program, in which the guest is asked if they prefer a vegetarian or meat meal. Based on the guest’s choice, the function food_item()
then prints out the relevant meal.
Use the editor below to try to build out some functions of your own. Remember, you need to both define the function and call it in order to see the results.