0

8.8kviews

Write a Python Program to Find the Factorial of a Number

**1 Answer**

0

8.8kviews

Write a Python Program to Find the Factorial of a Number

0

690views

written 17 months ago by | • modified 17 months ago |

**Explanation**

The factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative
numbers and the factorial of zero is one, 0! = 1.

if the no entered by the user is greater then 0 then for loop will iterate n times, for loop along with the range() function is used.

The arguments inside range function is (1, n+1) meaning, greater than or equal to 1 and less than n+1 (meaning n+1).n+1 is used as python excludes last element.

**Code:-**

```
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)
```

**Output:-**

**Using Recursion**

```
#Function to return the factorial of a number using recursion
def factorial(num):
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)
num = int(input("Enter a number: "))
factorial(num)
```

ADD COMMENT
EDIT

Please log in to add an answer.