Part of the series

Several example codes

~1 min read • Updated Oct 12, 2025

Program Overview

This Python program reads a number n from the user and calculates the sum of factorials from 1 to n.
The expression being evaluated is:
1! + 2! + 3! + ... + n!
The program uses one method to compute individual factorials and another to accumulate the total sum.


Python Code:


def factorial(num: int) -> int:
    result = 1
    for i in range(2, num + 1):
        result *= i
    return result

def sum_of_factorials(n: int) -> int:
    total = 0
    for i in range(1, n + 1):
        total += factorial(i)
    return total

# Read input from user
n = int(input("Enter a number n: "))
total = sum_of_factorials(n)
print(f"The sum of factorials from 1 to {n} is: {total}")

Sample Output (input: n = 4):


The sum of factorials from 1 to 4 is: 33

Step-by-Step Explanation:

- The user enters a number n
- The factorial method calculates each factorial from 1 to n
- The sum_of_factorials method adds up all the factorials
- The final result is printed


Written & researched by Dr. Shahin Siami