The factorial of a number means multiplying all positive integers from 1 to n.
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Let’s explore different ways to calculate factorial in Python ๐
๐น Method 1 – Using for Loop
n = 5 fact = 1 for i in range(1, n + 1): fact *= i print("Factorial:", fact)
✅ Best and most common approach.
๐น Method 2 – Taking User Input
n = int(input("Enter a number: ")) fact = 1 for i in range(1, n + 1): fact *= i print("Factorial:", fact)
✅ Useful for dynamic programs.
๐น Method 3 – Using while Loop
n = 5
fact = 1
i = 1
while i <= n:
fact *= i
i += 1
print("Factorial:", fact)✅ Good for loop practice.
๐น Method 4 – Using Recursion
def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) print(factorial(5))
✅ Great for understanding recursive functions.
๐ Example Output
For n = 5
120๐ฏ Best Method?
✔ for loop → easiest and efficient
✔ while loop → beginner practice
✔ recursion → advanced concept learning
๐ฅ Follow for more Python basics in this 150 Days Python Challenge
.png)

0 Comments:
Post a Comment