Scope & variable lifetime
Computer Science · Programming fundamentals
Question 1 of 10
0Does an if statement create a new scope in Python?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Scope & variable lifetime explained
The scope of a variable is the part of a program where its name can be used. Its lifetime is the period during which it exists in memory. A local variable is created inside a function and is discarded when that function finishes. A global variable is defined outside every function and can be used throughout the program.
When the program uses a name, it looks in the nearest scope first, which is usually the current function, then any enclosing scope, and finally the global scope. A local variable with the same name as a global one hides the global inside that function. Assigning a value to the local name leaves the global unchanged.
Global variables can be changed from many places, which makes programs hard to follow and debug. Programmers usually pass values into functions as parameters and return the results, keeping each function's data under its own control. In Python, a function that must change a global needs the global keyword.
total = 10
def add_bonus():
total = 5
return total + 1
result = add_bonus()
print(total, result)
Worked example
Trace the program above.
- The call add_bonus() starts. Inside it, total = 5 creates a new local variable that hides the global total.
- return total + 1 uses the local value: 5 + 1 = 6.
- The function ends, and its local total is discarded.
- The global total is still 10, so print(total, result) displays 10 6.
Had the function left out the local assignment, total + 1 would have used the global 10 and returned 11.
What you will practise
100 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Global variables are accessible:
- A local variable exists:
- Shadowing means:
- A variable’s lifetime is:
- Lexical scope means:
- Where is a variable declared inside a function body normally visible?
- Why is it good practice to keep variables in the smallest scope possible?
- A global variable is best described as one that:
…and 92 more.