Assignment makes a name local — Aptitude Question
Assignment makes a name local: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this Python program print?
x = 10
def f():
x = 20
return x
print(f(), x)Options
- 10 10
- 20 10
- 20 20
- The program raises an UnboundLocalError
Show the answer and the worked solution
Correct answer: B. 20 10
Worked solution
- Because f assigns to x, x is a local name inside f, entirely separate from the module-level x.
- f sets its local x to 20 and returns it, so the first value printed is 20.
- The module-level x was never reassigned, so the second value printed is 10 and the line reads 20 10.
Answer: 20 10.
The idea
Python decides scope by looking for assignments, not by looking at what already exists. Changing a global from inside a function requires the global keyword; without it you simply create a local.
Shortcut. f never says global, so its x = 20 is private to f: f() gives 20 and the module-level x is still 10.
Common trap. "20 20" assumes x = 20 inside f overwrites the global; without a global statement it creates a separate local.
All Programming Fundamentals questions · placement mock tests