Numbers and their factorial from 1 to 10


The code defines a Python function factorial(n) to calculate the factorial of a number n using recursion and then uses this function to create a dictionary called factorials. This dictionary maps numbers from 1 to 10 to their respective factorial values. Here's a step-by-step explanation of the code:

  • def factorial(n): This line defines a function named factorial that takes an integer n as input and calculates the factorial of n using recursion.
    • The base case is defined as if n == 0:. When n is 0, the function returns 1 because 0! (read as "zero factorial") is defined as 1.
    • In the recursive case, the function calculates the factorial of n as n * factorial(n - 1). It recursively calls itself with a smaller value until it reaches the base case.
  • factorials = {x: factorial(x) for x in range(1, 11)}: This line creates the factorials dictionary using a dictionary comprehension. Here's how it works:
    • {x: factorial(x) for x in range(1, 11)} is the dictionary comprehension. It iterates over the range of numbers from 1 to 10 (inclusive).
    • For each number x, it creates a key-value pair in the dictionary. The key (x) is the number itself, and the value (factorial(x)) is calculated by calling the factorial function with that number as input.
  • print(factorials): This line prints the factorials dictionary to the console.

Source Code

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)
 
factorials = {x: factorial(x) for x in range(1, 11)}
print(factorials)

Output

{1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880, 10: 3628800}

Example Programs