ProgrammingModerateInfosys · Accenture · Capgemini pattern
What is printed?
What is printed?
x = 10
def f():
x += 1
return x
try:
f()
except Exception as e:
print(type(e).__name__)- A. 10
- B. NameError
- C. UnboundLocalError
- D. 11
Correct answer: C. UnboundLocalError
Because x is assigned inside f, the compiler treats x as local for the WHOLE function. x += 1 then reads the local x before it has a value, which raises UnboundLocalError. A 'global x' line would fix it.
More Python Programming questions
- What is printed? python g = (i i for i in range(4)) print(sum(g), sum(g))
- What is printed? python print({1, 2, 3} ^ {2, 3, 4}, {1, 2} <= {1, 2, 3})
- What is printed? python a = "abc" b = a a += "d" print(a, b)
- What is printed? python t = (1, [2, 3]) t[1].append(4) print(t)
- What is printed? python print(0.1 + 0.2 == 0.3, abs(0.1 + 0.2 - 0.3) < 1e-9)
- What is printed? python def outer(): n = 0 def inc(): nonlocal n n += 1 return n return inc c = outer() c(); c() print(c())