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 = 5as our test input and create an accumulator variablefactorial = 1to store the running product. - Handle Negative Numbers (
if): Factorials are undefined for negative numbers, so the script catchesnumber < 0first. - Handle Zero (
elif): By mathematical definition,0! = 1, which theelif number == 0branch prints immediately. - Multiply Using a
forLoop (else): For any positive integer,range(1, number + 1)loops from1up to5, multiplyingfactorialby each integeri.
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
Post a Comment