Factorial of a Number in Python Using for Loop

Python incorporates an endless collection of libraries and systems that make it simple to create complex applications with negligible code. In this Python exercise, we are going to learn how to calculate the factorial of a number in Python using for loop.

The factorial of a number is the item of all positive integrability up to and including that number. For Example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120. Calculating the factorial of a number may be a common issue in arithmetic and computer science. In this exercise, we’ll learn how to calculate the factorial of a number in Python using for loop.

Factorial of a Number in Python- Code

Below, you’ll see the code of the factorial of a number in Python using for loop which will help you to understand the concept in a better way:

#Factorial of a Number in Python Using for Loop
# accept input from user
n = int(input("Enter any number: "))

f = 1

# for loop to calculate factorial of a number
for i in range(n, 0, -1):
    f *= i

# print output
print("Factorial is", f)

To calculate the factorial of a number in Python using for loop, follow these steps:

1. Accept input from the user.

n = int(input("Enter any number: "))

The first step of the code is to accept input from the user. The program uses the input() function to prompt the user to enter a value and then converts it to an integer using the int() function. It stores this value in a variable named “n”.

2. Initialise a variable to store the factorial value.

f = 1

The next step is to initialize a variable named “f” to 1. This variable stores the factorial value.

3. Use a for loop to calculate the factorial of the input number.

for i in range(n, 0, -1):
    f *= i

We use the for loop to calculate the factorial of the input number. We use the range() function to create a sequence of numbers from the input number down to 1. The loop iterates over this sequence, multiplying each number by the previous product, starting with 1. The *= operator is a shorthand for multiplying the current value of “f” by the current value of “i”.

4. Print the output.

print("Factorial is", f)

The final step is to print the output, which is the factorial value. The print() function displays the message “Factorial is” and then the value of “f”.

In summary, the code accepts input from the user, initialises a variable to store the factorial value, uses a for loop to calculate the factorial of the input number, and prints the output.

The code above prompts the user to enter a number initialises a variable named “f” to 1, and uses a for loop to calculate the factorial of a number. It then prints the output, which is the factorial value.

Output:

Enter any number: 5
Factorial is 120

The above code uses a for loop to calculate the factorial of a number. It first prompts the user to input a number and then converts it to an integer using the int() function, storing it in the variable n.

Next, we initialize a variable f with a value of 1, which we will use to store the factorial of the number n.

When we initiate the for loop, it starts with i being equal to n and counts down to 1 in increments of -1 using the range() function with a step of -1.

In each iteration of the loop, we multiply the value of the variable f by i using the *= operator. This calculates the product of all numbers from n down to 1, resulting in the value of n!.

Why do we use For Loop to print factorial program in python

We generally use ‘for loop’ for finding the factorial of a number because it allows us to iterate through the numbers from n to 1 quickly and multiplies them together to find its factorial. 

Although there are other functions capable of calculating the factorial, such as recursion and reduce function, they could be more complex and efficient. 

For example, making multiple function calls with recursion can lead to stack overflow errors for large input values. Similarly, using the reduce function available in the functools module requires defining an additional function, which makes the code more complex and less readable than a simple for loop.

Thus, for loop is the most efficient method to calculate the factorial of a number. 

Handling Edge Cases

Handling edge cases is crucial when calculating the factorial of a number in Python using a for loop. Here’s how to address some common edge cases:

1. Zero Input: The factorial of 0 is defined as 1. This is a special case that needs to be handled explicitly.

   n = int(input("Enter any number: "))

   if n == 0:

       print("Factorial is 1")

   else:

       f = 1

       for i in range(n, 0, -1):

           f *= i

       print("Factorial is", f)

2. Negative Input: Factorials are not defined for negative numbers. The program should check for this and inform the user appropriately.

   if n < 0:

       print("Factorial is not defined for negative numbers")

3. Non-integer Input: Factorials are defined only for integers. Ensure the input is an integer. If using int(input()), any non-integer input will raise a ValueError, which can be caught using a try-except block.

   try:

       n = int(input("Enter any number: "))

       if n < 0:

           print("Factorial is not defined for negative numbers")

       elif n == 0:

           print("Factorial is 1")

       else:

           f = 1

           for i in range(n, 0, -1):

               f *= i

           print("Factorial is", f)

   except ValueError:

       print("Please enter a valid integer")

By including these checks, the program of Factorial of a Number in Python Using for Loop becomes robust and user-friendly, handling special cases effectively.

In this Python exercise, we learned how to calculate the factorial of a number in Python using for loop. We clarified each step of the code in detail, making it simple for tenderfoots to get it. Calculating the factorial of a number may be a common issue in arithmetic and computer science, and Python gives a basic and natural way to solve it. We trust this instructional exercise was accommodating and instructive, in which you’re presently able to calculate the factorial of any number using Python and a for loop.

FAQ‘s – Factorial of a Number in Python Using for Loop

Does Python have an inbuilt function for calculating factorial?

Yes, the math module in Python provides an inbuilt function called factorial().

How to calculate the factorial of multiple numbers?

You can use a loop that takes a new number after each calculation. Alternatively, you can create a list of numbers and use the loop function to calculate the factorial of each number in the list.

Can I input a decimal or negative number in this program?

No, the input must be a positive integer. If you try to enter a decimal or negative number, the program will result in an error as factorials are only calculated for positive integers. 

Is there a limit to the number size that I can enter?

Yes, there is a limit due to the limitations of the computer’s memory. However, this limit is very large and should not be an issue for most practical purposes.

About The Author

Leave a Reply