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

~90s

Short-circuiting past a function call

What does this Python program print?

def g():
    print("g", end=" ")
    return True

x = False and g()
y = True or g()
print(x, y)
Show the answer and the worked solution

Correct answer: A.

False True

Worked solution

  1. In False and g() the left operand is already false, so the result is settled and g is never called.
  2. In True or g() the left operand is already true, so again g is never called.
  3. No g is printed, and the final line prints the two stored values as False True.

Answer: False True.

The idea

Both boolean operators return the operand that decided the result and skip the rest, so any side effect on the right may never occur. Here that means the function body never runs at all.

Shortcut. and stops at a false left side and or at a true one; both left operands decide here, so g never runs and nothing extra prints.

Common trap. "g g False True" assumes both g() calls execute; each is skipped because its operator already knows the result.

Short-circuiting past a function call — Aptitude Question

Short-circuiting past a function call: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

def g():
    print("g", end=" ")
    return True

x = False and g()
y = True or g()
print(x, y)

Options

  1. False True
  2. g False True
  3. g g False True
  4. True True
Show the answer and the worked solution

Correct answer: A. False True

Worked solution

  1. In False and g() the left operand is already false, so the result is settled and g is never called.
  2. In True or g() the left operand is already true, so again g is never called.
  3. No g is printed, and the final line prints the two stored values as False True.

Answer: False True.

The idea

Both boolean operators return the operand that decided the result and skip the rest, so any side effect on the right may never occur. Here that means the function body never runs at all.

Shortcut. and stops at a false left side and or at a true one; both left operands decide here, so g never runs and nothing extra prints.

Common trap. "g g False True" assumes both g() calls execute; each is skipped because its operator already knows the result.

All Programming Fundamentals questions · placement mock tests