Scope determines where a variable can be accessed. Understanding scope helps you reason about variables inside and outside functions.
Local variables
Variables defined inside a function are local variables. They can only be accessed inside that function.
def swap(a, b):
a, b = b, a
print("inside swap():", a, b)
def main():
a, b = 1, 2
print("Before:", a, b)
swap(a, b)
print("After:", a, b)
if __name__ == "__main__":
main()Output:
Before: 1 2
inside swap(): 2 1
After: 1 2INTERACTIVE LAB
Two rooms, two pairs of boxes
ACCESSPRO
PRO EXCLUSIVEGo further with Pro
Unlock Pro accessUnlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
QUESTION
When swap(a, b) is called, how are a inside swap() and a inside main() related?
Global variables
Variables defined outside functions are global variables. To modify a global variable inside a function, use global.
a, b = 1, 2
def swap():
global a, b
a, b = b, a
print("inside swap():", a, b)
def main():
print("Before:", a, b)
swap()
print("After:", a, b)
if __name__ == "__main__":
main()Global variables are sometimes useful, but overusing them makes programs harder to debug.
KNOWLEDGE QUIZ
QUESTION
Which keyword is commonly needed to modify a global variable inside a function?
HANDS-ON PRACTICE
Maintain a global scoreboard
Use global score in add_points and compare it with a shadowing local parameter.
- Create score = 0 globally.
- Use global in add_points.
- Show that preview_message(score) does not change the global.