Programming Fundamentals · Lesson 07
Reusable functions
Package a calculation into a named function with a parameter and a return value.
A function groups instructions under a name. Define one with def, choose a descriptive name, and place its parameters in parentheses. A parameter stands for a value that a caller supplies later.
Calling a function runs its instructions. A return statement sends a result back to the caller. The caller can store that result, use it in another expression, or print it.
Our workshop needs two cups per visitor. Putting the calculation in one function gives the rule one place to live even when several groups need supplies.
Read the example
def cups_needed(people):
return people * 2
morning = cups_needed(4)
afternoon = cups_needed(6)
print(morning + afternoon)
20
The first call returns 8 and the second returns 12. The last line adds the two values. Keeping print outside the function lets another caller reuse the calculation without displaying anything.
Try it yourself
Write a function called pencils_needed that takes a group size and returns three pencils per person. Call it with 7 and print the result.
Show a worked solution
def pencils_needed(people):
return people * 3
print(pencils_needed(7)) # 21
Check your understanding
Your lesson quiz
Answer all five questions. Score at least 4 out of 5 (80%) to pass. You can retry as often as you like.
Quiz progress is saved in this browser. View certificates →
Learn together
Was this lesson helpful?
Comments and reactions are not open yet.
Join the conversation
Ask a question or share what you learned. Your display name and comment will be public after review. Please leave out private information. How feedback is stored