ΣνΜDr. Sharon's Math PlatformSyvara Learning
Question Bank › 📘 Undergraduate › Programming for Engineers › Q13

Q13 · The function below should compute n! (n factorial) but always returns 0. This is a logic…

Error Handling and Debugging 🟡 Intermediate Coding
Question

The function below should compute n! (n factorial) but always returns 0. This is a logic error — no exception is raised, but the output is wrong.

  def my_bad_factorial(n):
      out = 0
      for i in range(1, n+1):
          out = out * i
      return out

(a) Add a print statement inside the loop to trace i and out for n=4.
(b) Identify the logic error and explain why it always produces 0.
(c) Fix it and verify: 4! = 24, 5! = 120, 0! = 1.

🔒

Log in to see the worked solution

Enter your email to get started. Your first free solutions in every course unlock as soon as you verify.

Log in or sign up with email
← Previous Next →
Working…