Factorial Using a Loop

Easy ⏱ 8 min 77% acceptance ★★★★★ 4.7
Write a function factorial(n) that returns n! (n factorial) computed with a for loop, not recursion. By definition 0! = 1.

Examples

Example 1
Input
factorial(5)
Output
120
Explanation

5*4*3*2*1 = 120.

Example 2
Input
factorial(0)
Output
1
Explanation

0! is defined as 1.

Constraints

  • n is a non-negative integer.
  • Must use iteration, not recursion.

Topics

Loopsfor loopaccumulator

Companies

WiproAccenture

Hints

Hint 1

Start a `result = 1` accumulator.

Hint 2

Multiply result by each value from 1 to n inclusive.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.