Module 05 · Lesson 01
Functions & Modular Code
Package reusable code with def: give a function parameters, call it with arguments, send results back with return, and document it with a docstring.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Define and call
- Return a result
- Local names
- Follow a call
Name a piece of work
A function is a set of lines with a name. Write it once, then run it whenever you like by calling its name.
def
def greet(name):creates a function. The indented lines under it are its body.Parameters
Names in the brackets are the inputs.
greet("Ana")givesnamethe value"Ana".return
returnsends an answer back to the line that called the function, and ends it.Call it
Brackets run it:
greet("Bo"). Without brackets, nothing happens.
Functions everywhere
You have used functions since your first line of Python.
- Built in
print(),len()andround()are functions someone else wrote for you. - Game moves
jump(),shoot()andcollect_coin()each run when a key is pressed. - CalculatorsEach button calls one small function that does one sum.
- WebsitesPressing Send calls a function that checks your message and posts it.
The first line of a function
Every function starts with a line like this. Tap each part to see its job.
Part 1 of 5
define:def means "define a function". It stores the lines below; it does not run them yet.
Write and call functions
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6First function
Define once, call as often as you like.
Your turn: Add a second parameter, mood, and print it in the greeting.
def greet(name):
print(f"Hi {name}!")
greet("Ana")
greet("Bo")
greet("Cy")Press Run to see what it prints.Watch Python jump into a function
Press Step to run one line at a time. Watch Python jump into the function and back out again.
Ready. Press Step to run the first line.
- def area(width, height):
- result = width * height
- return result
- room = area(4, 3)
- garden = area(5, 2)
- print(room + garden)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Does the hi appear?
def f():
return 3
print("hi")
print(f())0 of 6 answered
Common function misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
def name(param1, param2):
"""What the function does."""
result = param1 + param2
return result # hand the value back; ends the function
value = name(3, 4) # call with arguments
def nothing(): pass # no return gives None
return a, b # several values as a tuplePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A reusable price calculator
Write a function that takes a price and a discount percentage and returns the final price rounded to 2 places. Use it for three items and a basket total.
def discounted(price, percent):
"""Return price after taking off percent per cent, rounded to 2 places."""
return round(price * (100 - percent) / 100, 2)
shoes = discounted(60, 25)
coat = discounted(120, 10)
hat = discounted(15, 0)
print(shoes, coat, hat)
print("Basket:", round(shoes + coat + hat, 2))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Printing instead of returning
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
def square(n):
print(n * n)
result = square(4) + 1Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Cooking
Converting recipe quantities
A recipe website lets readers scale a recipe for a different number of people. One small function does the scaling for every ingredient.
Why Python fits
The scaling rule lives in one function with a docstring, and the loop calls it for each ingredient. Serving a different number of people changes one argument, not every line.
Pythondef scale(amount, serves, wanted): """Return amount scaled from serves people to wanted people.""" return round(amount * wanted / serves, 1) recipe = [("flour (g)", 200), ("milk (ml)", 300), ("eggs", 2)] for name, amount in recipe: print(f"{name}: {scale(amount, 4, 6)}")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Can a function call itself?
Where should I put my functions?
Can I change a variable from outside inside a function?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.