Beginner Python Exercises

Factorial in Python

The factorial of a non-negative integer n is the product of every integer from 1 through n.

What is Factorial?

The factorial of a non-negative integer n is the product of every integer from 1 through n.

Calculate a factorial in Python with an iterative function.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
def factorial(number):
    if number < 0:
        raise ValueError("Factorial is undefined for negative numbers")

    result = 1
    for value in range(2, number + 1):
        result *= value
    return result

print(factorial(6))

Expected output

720

How it works

Starting with 1 preserves the correct value for 0 factorial. The loop multiplies the result by each integer through n.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →