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")- A. 2 1
- B. 2 UBL
- C. 1 1
- 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
- What is printed? python class A: pass class B(A): pass try: class C(A, B): pass print("ok", end=" ") except TypeError: print("TypeError"…
- What is printed? python class R: def iter(self): print("it", end=" ") return iter([1, 2, 3]) r = R() print(2 in r, 5 in r)
- What is printed? python d = {1: "a", 2: "b"} for k in d: d[k] = d[k] 2 try: for k in d: d[k 10] = "x" except RuntimeError: print("RE"…
- What is printed? python s = "abcbaXabcba" print(s.strip("ab"), s.removeprefix("ab"), s.lstrip("cba"))
- What is printed? python print(-7.5 // 2, -7.5 % 2, 7 // -2.0, 7 % -2.0)
- What is printed? python n = [1] print(1 in n == True, (1 in n) == True, 0 < 1 in n)