Exam-style question
Try this first
Explain the difference between local and global variables. Use the following Python code in your answer and state what happens when the final line is reached. def calculate(): result = 42 print(result) calculate() print(result).
Model answer
What a good answer should say
- result is a local variable because it is defined inside calculate.
- It can be used by the print statement inside calculate, so 42 is printed when the function runs.
- It is not available to the final print statement outside the function.
- When that final line is reached, the program cannot access result there and produces an error.
Explanation
Why this works
This example demonstrates the restricted scope of a local variable. Defining result inside calculate does not make it available to statements outside calculate.
A global variable has a wider scope because it is defined outside the local function area.
Common mistake
No common mistake is linked to this question yet.
