ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
x = 1
def f(flag):
    if flag:
        x = 2
    return x

print(f(True), end=" ")
try:
    print(f(False))
except UnboundLocalError:
    print("UBL")
  1. A. 2 1
  2. B. 2 UBL
  3. C. 1 1
  4. D. 2 None

Correct answer: B. 2 UBL

Python decides scope at compile time: because x is assigned somewhere inside f, x is local throughout f, even on paths where the assignment never runs. f(True) binds it and returns 2. f(False) reaches return x with the local still unbound and raises UnboundLocalError instead of reading the global 1.

More Python Programming questions

Exams that ask this topic