Python program that finds the factorial of a given number:
number = int(input("Enter a number: "))
factorial = 1
if number < 0:
print("Sorry, factorial does 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("The factorial of", number, "is", factorial)
The program prompts the user to enter a number using the input() function, and stores the value in the variable “number”. It then uses an if-elif-else statement to check if the number is less than 0, equal to 0 or greater than 0. If the number is less than 0, it prints a message saying factorial does not exist for negative numbers, if the number is equal to 0, it prints the factorial of 0 which is 1. If the number is greater than 0, it uses a for loop to find the factorial of the number by multiplying each number between 1 and the number itself.
Another way to find the factorial of a number is by using recursion:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
number = int(input("Enter a number: "))
if number < 0:
print("Sorry, factorial does not exist for negative numbers")
else:
print("The factorial of", number, "is", factorial(number))
Here, a function factorial
is defined which calls itself recursively until the base case (n == 0) is reached and then it returns the fact