Home Tutorials Python Programs Factorial
Factorial

Factorial


Topic: Factorial Calculator

Description: This program prompts the user to enter a positive integer and calculates its factorial value. It provides two clean approach options for students: an iterative approach using a while loop, and a modular approach utilizing a recursive function structure.

Why: The factorial problem is a classic milestone in computer science logic building. It helps students understand mathematical accumulators (iterative multiplication) and introduces the advanced architectural concept of recursion—where a function solves a problem by calling itself with scaled-down inputs.


Program Code

Copy and run the following Python code to see the factorial engine in action:

# Approach 1: Iterative Logic (Using a While Loop)
def factorial_iterative(n):
    if n < 0:
        return "Undefined (Factorials do not exist for negative numbers)"
        
    result = 1
    counter = n
    
    while counter > 1:
        result *= counter
        counter -= 1
        
    return result


# Approach 2: Recursive Logic (Function calling itself)
def factorial_recursive(n):
    # Base Case scenario constraints
    if n == 0 or n == 1:
        return 1
    # Recursive Step execution
    return n * factorial_recursive(n - 1)


# Main Execution Driver Block
def run_factorial_system():
    print("=============================")
    print("  FACTORIAL CALCULATOR ENGINE ")
    print("=============================")
    
    try:
        user_num = int(input("Enter a non-negative integer: ").strip())
    except ValueError:
        print("\nError: Invalid input. Please enter a valid whole number.")
        return

    if user_num < 0:
        print("\nError: Factorial is not defined for negative numbers.")
    else:
        iterative_output = factorial_iterative(user_num)
        recursive_output = factorial_recursive(user_num)
        
        print("\n-----------------------------")
        print("      COMPUTATION SUMMARY     ")
        print("-----------------------------")
        print(f"Mathematical Expression : {user_num}!")
        print(f"Iterative Loop Result   : {iterative_output}")
        print(f"Recursive Stack Result  : {recursive_output}")
        print("-----------------------------")

# Start the application
run_factorial_system()

Expected Console Output Examples

Example 1 (Standard Calculation - 5!):

=============================
  FACTORIAL CALCULATOR ENGINE 
=============================
Enter a non-negative integer: 5

-----------------------------
      COMPUTATION SUMMARY     
-----------------------------
Mathematical Expression : 5!
Iterative Loop Result   : 120
Recursive Stack Result  : 120
-----------------------------

Example 2 (Edge Case Check - 0!):

=============================
  FACTORIAL CALCULATOR ENGINE 
=============================
Enter a non-negative integer: 0

-----------------------------
      COMPUTATION SUMMARY     
-----------------------------
Mathematical Expression : 0!
Iterative Loop Result   : 1
Recursive Stack Result  : 1
-----------------------------

Core Syntax & Concept Breakdown

  • Multiplication Assignment Operator (*=): The expression result *= counter is shorthand notation for writing result = result * counter. This updates the running calculation product cleanly inside the loop step.
  • Recursive Base Case Requirement: Every recursive function must contain an explicit termination clause known as a **Base Case** (e.g., if n == 0 or n == 1: return 1). Without this threshold exit gate, the function would create an infinite loop call stack, causing a fatal RecursionError crash.
  • Mathematical Boundary Check (Edge Cases): By definition, the factorial of 0 ($0!$) evaluates to $1$. The code handles this input gracefully across both structural formats without producing arithmetic processing failures.

🏋️ Test Yourself With Exercises

Take our quiz on Factorial to test your knowledge.

Browse Quizzes »