Beginner level · Module 4: Writing Reusable Functions · Lesson 2 of 3
Scope and Default Arguments
Understand where variables exist and make functions flexible with default values.
In this lesson you will
- Explain local versus global variables
- Use default and keyword arguments
Key concepts
local scopeglobal scopedefault argumentkeyword argument
The lesson
Variables created inside a function are local: they exist only while the function runs and cannot be seen outside it. This keeps functions independent, so a total inside one function cannot accidentally change a total somewhere else.
Default arguments make parameters optional: def calculate_total(prices, discount_rate=0): works with or without a discount. Put parameters with defaults after the required ones.
Avoid relying on global variables inside functions. Pass what the function needs as arguments and return what it produces; the function then behaves the same wherever you use it, which makes it easy to test.
Step by step
- Add discount_rate=0 to calculate_total.
- Apply the discount inside the function and return the discounted total.
- Call it once without a discount and once with discount_rate=0.1.
- Print a local variable outside the function to see the NameError, then remove that line.
Practice activity
Add an optional discount_rate=0 parameter to calculate_total and call it with and without a discount.
Expected result: calculate_total works with and without the discount argument and gives correct results.
Check your understanding
-
Can code outside a function use a variable created inside it?
Show answer
No, it is local to the function.
-
What is a keyword argument?
Show answer
An argument passed by name, such as rate=1500, so its meaning is clear regardless of position.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.