A tiny, elegant Python script that turns a single number into its full factorial — instantly.
The factorial of a non-negative integer n, written n!, is the product of every positive integer from 1 up to n.
Factorials show up everywhere — combinatorics, probability, permutations, series expansions — which makes this humble little script surprisingly powerful.
The script does three things, in order:
- Reads an integer from the user via
input(). - Branches on the value of
n:- 🔴 Negative → prints an error message (factorials aren't defined here).
- 🟡 Zero → prints
1directly (0! = 1by mathematical convention). - 🟢 Positive → multiplies its way up from
1tonin aforloop.
- Prints the final result.
n = int(input("Enter a number: "))
if n < 0 :
print("Factorial is not defined for negative numbers.")
elif n == 0 :
print("Factorial is: 1")
else:
factorial = 1
for i in range(1, n + 1):
factorial = factorial * i
print("Factorial is:", factorial)Clean, readable, and dependency-free — pure Python standard library, no imports needed.
flowchart TD
A(["🚀 Start"]) --> B["Read integer n"]
B --> C{"n < 0 ?"}
C -- "Yes" --> D["❌ Print: not defined for negatives"]
C -- "No" --> E{"n == 0 ?"}
E -- "Yes" --> F["✅ Print: Factorial is 1"]
E -- "No" --> G["🔁 Loop i = 1 → n<br/>factorial *= i"]
G --> H["✅ Print: Factorial is factorial"]
D --> I(["🏁 End"])
F --> I
H --> I
style A fill:#2ECC71,stroke:#27AE60,color:#fff
style I fill:#E74C3C,stroke:#C0392B,color:#fff
style D fill:#FF6B6B,stroke:#C0392B,color:#fff
style F fill:#F7C948,stroke:#D4A017,color:#1a1a2e
style H fill:#4ECDC4,stroke:#1B9C92,color:#1a1a2e
style G fill:#6C5CE7,stroke:#4834D4,color:#fff
💡 GitHub renders Mermaid diagrams natively — this flowchart will animate into view when the README loads.
Click to expand factorial.py 📂
n = int(input("Enter a number: "))
if n < 0 :
print("Factorial is not defined for negative numbers.")
elif n == 0 :
print("Factorial is: 1")
else:
factorial = 1
for i in range(1, n + 1):
factorial = factorial * i
print("Factorial is:", factorial)# 1️⃣ Clone or download this repo
git clone https://github.com/your-username/factorial-calculator.git
cd factorial-calculator
# 2️⃣ Run the script
python3 factorial.py
# 3️⃣ Enter any integer when prompted
Enter a number: 7
Factorial is: 5040| Input | Behavior |
|---|---|
n < 0 |
Prints a friendly error — factorial isn't defined for negatives |
n == 0 |
Correctly returns 1 (mathematical convention: 0! = 1) |
n > 0 |
Computes the product iteratively via a for loop |
| Non-integer input | ValueError — not currently caught |
Released under the MIT License — free to use, modify, and share.

