Exam-style question
Try this first
Study the Python code below. Identify the global and local variables, then explain where each can be accessed. score = 5 def show_score(): message = "Current score" print(message) print(score) show_score() print(score).
Model answer
What a good answer should say
- score is a global variable because it is defined outside show_score.
- It can be accessed inside show_score and by the final print statement outside the function.
- message is a local variable because it is defined inside show_score.
- It can be accessed inside that function but not from the final statement outside it.
Explanation
Why this works
The position where each variable is defined determines its scope in this example. score is defined outside the function, so it has wider access.
message is defined inside the function, so its access is limited to that function.
Common mistake
No common mistake is linked to this question yet.
