When to Use a Function
When you receive a complicated programming problem with multiple steps, it’s a good idea to break that problem down into parts, and code those parts individually. This way, you can see which part(s) need to be fixed when your code has bugs.
Another scenario when you might want to use a function is when a certain task is repeated multiple times and cannot be modeled using loops. For instance, let’s say you're tasked with making a program that simulates a day in someone’s life. Many activities repeat in a day such as brushing your teeth. Using functions means that for those activities that repeat, only a call to a function is needed each time.
For example:
def brush_teeth(): # put toothpaste on brush # move brush across teeth
day_simulation program:
# wake up # brush teeth # eat breakfast # workout # study # eat lunch # brush teeth # play videogames # eat dinner # brush teeth
Do you see how we only have to write the program for brushing teeth once, and then we can use that.
Previous Section
11.3 ParametersNext Section
11.5 The Return StatementCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.