Factorial

Computes factorials with a function that calls itself. Teaches functions and recursion.

Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Factorial example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""Prints the factorials of 0, 5, 10, 15 and 20. Teaches a function that returns a value."""

def factorial(n: int) -> int:
    """Recursion: n! = n · (n − 1)!, and 0! = 1! = 1."""
    if n <= 1:
        return 1
    else:
        # The function calls itself with a smaller n until it reaches 1.
        return n * factorial(n - 1)

for k in range(0, 21, 5):
    print(str(k) + "! =", factorial(k))

Follow-up tasks

Tasks in which you change the example (with a model solution):

All examples