AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easypythonscope

~60s

Assignment makes a name local

What does this Python program print?

x = 10

def f():
    x = 20
    return x

print(f(), x)
Show the answer and the worked solution

Correct answer: B.

20 10

Worked solution

  1. Because f assigns to x, x is a local name inside f, entirely separate from the module-level x.
  2. f sets its local x to 20 and returns it, so the first value printed is 20.
  3. 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.

Assignment makes a name local — Aptitude Question

Assignment makes a name local: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

x = 10

def f():
    x = 20
    return x

print(f(), x)

Options

  1. 10 10
  2. 20 10
  3. 20 20
  4. The program raises an UnboundLocalError
Show the answer and the worked solution

Correct answer: B. 20 10

Worked solution

  1. Because f assigns to x, x is a local name inside f, entirely separate from the module-level x.
  2. f sets its local x to 20 and returns it, so the first value printed is 20.
  3. 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