6.6.3 – Local and global variables
Trace local and global names, choose where values should live, and repair scope errors by passing inputs and returning results.
Names have a scope
Scope describes where a name can be used. A global variable is defined at main-program/module level, outside subprograms. A local variable belongs to a subprogram; its parameters are local too. Separate calls receive their own local values.
level = "Bronze"
def make_badge(level):
message = "Badge: " + level
return message
badge = make_badge("Gold")
print(level)
print(badge)
Bronze
Badge: Gold
The parameter receives Gold and shadows the global name while the function runs. It does not reassign global level. The local message is not available by that name to the caller. Its returned string survives because the caller stores it in badge.
| Moment | Main-program level | Local level | Local message |
|---|---|---|---|
| Before call | Bronze | no active call | no active call |
| During call | Bronze | Gold | Badge: Gold |
| After call | Bronze | call ended | call ended |
Two names with the same spelling are not automatically one variable. Similarly, two different functions can each use a local total without sharing that local name. For a simple call, a local counter initialised to zero starts again each time; it is not a hidden persistent counter.
Use shared values deliberately
A subprogram can read a global name when there is no local name hiding it. This can be appropriate for a clearly shared fixed setting:
TAX_RATE = 0.05
def add_tax(price):
return price * (1 + TAX_RATE)
print(add_tax(20))
The result is 21.0. The function reads the shared constant and receives the changing price as a parameter. Main-program state also naturally lives at module level. Global variables are not automatically wrong; choose them for a real shared purpose.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account