Editor

Factorial, With a Proper Error

Beginner · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write factorial(n) that returns n! using a loop (no math.factorial). factorial(0) is 1. For a negative n, raise a `ValueError`.

factorial(5)   ->  120
factorial(-1)  ->  ValueError
def factorial(n):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
factorial(5)120
factorial(0)1
try: factorial(-1) print("no error") except ValueError: print("ValueError")ValueError

More practice problems

All Python exercises · 50 practice problems