How to Find the Factorial of a Number in Python (Using If-Else & Loops)

Calculating the factorial of a number is one of the best ways to practice conditional statements and loops in Python. In the video below, I walk through a clean Python script that handles negative numbers, zero, and positive integers step by step.

Python Code: Factorial Calculator

You can test this script right away by changing the value assigned to number:

# This script calculates the factorial of a hard-coded number
# Tweak the input value below to test different results
number = 5
factorial = 1

# Check whether the number is negative, zero, or positive
if number < 0:
    print("Factorials do not exist for negative numbers.")
elif number == 0:
    print("The factorial of 0 is 1.")
else:
    for i in range(1, number + 1):
        factorial = factorial * i
    print(f"The factorial of {number} is {factorial}")

Sample Output

The factorial of 5 is 120

How This Script Works

  • Initialize Variables: We set number = 5 as our test input and create an accumulator variable factorial = 1 to store the running product.
  • Handle Negative Numbers (if): Factorials are undefined for negative numbers, so the script catches number < 0 first.
  • Handle Zero (elif): By mathematical definition, 0! = 1, which the elif number == 0 branch prints immediately.
  • Multiply Using a for Loop (else): For any positive integer, range(1, number + 1) loops from 1 up to 5, multiplying factorial by each integer i.

Have a Python concept or animation you would like to see broken down next? Drop a comment below or subscribe on YouTube (@programmer_script99) for more quick coding tutorials!

Comments

Popular posts from this blog

🌐🤖 Modi Calls for Inclusive AI, Unveils MANAV Framework

Amazon CodeGuru

☁️ Cloud Services: The Hidden Playground of Cybercriminals