Read the question, write Python on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Write a function factorial(n) that returns n! (the product 1 × 2 × … × n). By definition 0! is 1.
The main part already reads n and prints factorial(n) — you only need to fill in the function.
Input. One line: an integer n ≥ 0.
Output. One integer: n!
Constraints
- 0 ≤ n ≤ 20 (fits in a normal int).
Examples
Input
5
Output
120
Input
0
Output
1
Hint
- Start a result at 1 and multiply it by every number from 2 up to n.
- range(2, n + 1) is empty when n is 0 or 1, so the result stays 1 — exactly what you want.
Show correct code
Peek only after you have tried. You can still Check your own version.
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
n = int(input())
print(factorial(n))
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.