ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def f(n):
    return sum(d if n % 2 else -d for d in range(1, n + 1))
print(f(1), f(2), f(3), f(4))
  1. A. 1 -3 5 -10
  2. B. 1 -3 6 -10
  3. C. 1 -2 6 -10
  4. D. 0 -3 6 -10

Correct answer: B. 1 -3 6 -10

Odd n adds every term, and even n subtracts them all, so f(4) is -(1 + 2 + 3 + 4) = -10. The trap is thinking the sign alternates per term.

More Python Programming questions

Exams that ask this topic