In this python program, we will find the factorial of a number. We are going to use the **for loop**. We have also used the **range()** function to traverse through every number between 1 and num+1.

Write a program to Find the Factorial of a Number in Python

Code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Python program to find the factorial of a number provided by the user. num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) |

This Python program takes an input number from the user and finds the factorial of the input number. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 (written as 5!) is 5x4x3x2x1 = 120.

The program starts by asking the user to input a number, which is stored as an integer in the variable “num”.

Then, the program checks if the input number is negative, positive or zero. If the input number is negative, it prints “Sorry, factorial does not exist for negative numbers” to the output. If the input number is zero, it prints “The factorial of 0 is 1” to the output. If the input number is positive, it uses a for loop to iterate through all the numbers between 1 and the input number (inclusive) and calculates the factorial of the input number by multiplying each number by the previous one.

Finally, it prints “The factorial of num is factorial” to the output, where num is the input number and factorial is the factorial of the input number.

The output will be a string indicating the factorial of the input number or a message indicating that factorial does not exist for negative numbers.