script_4.py - Factorial Calculator
Code
#!/usr/bin/env python3
"""Factorial calculator"""
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"{n}! = {factorial}")
Explanation
Line 4: n = int(input("Enter a number: "))
- n stores the integer to calculate factorial for
Line 5: factorial = 1
- Accumulator initialized to 1 (not 0!)
- Must be 1 because we're multiplying (0 would make result always 0)
- Integer type
Line 7: for i in range(1, n + 1):
- Iterates from 1 to n (inclusive)
- Loop variable i takes each value in sequence
Line 8: factorial *= i
- *= is augmented assignment for multiplication
- Equivalent to factorial = factorial * i
- Multiplies accumulator by current loop value
- Example for n=5: 1×1=1, then 1×2=2, then 2×3=6, then 6×4=24, then 24×5=120
- Builds up factorial through repeated multiplication
Line 10: print(f"{n}! = {factorial}")
- ! is factorial symbol in mathematics
- Shows final result after all iterations complete