A factorial is the product of an integer and all the integers below it; for example, the factorial of 4 (written as “4!”) is 4 * 3 * 2 * 1 = 24. Here is a simple Python program that calculates the factorial of a given number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
number = int(input("Enter a number: "))
print(factorial(number))
Here is how the program works:
- We define a function
factorial()
that takes an integern
as an argument. - The function contains a base case, which is
if n == 0: return 1
. This is important because the factorial of 0 is 1, and we want to make sure our program terminates. - If
n
is not 0, the function returnsn * factorial(n-1)
. This is known as recursion, and it means that the function will call itself with a smaller valuen
until the base case is reached. - Outside the function, we ask the user to enter a number, which is stored in the variable
number
. - We call the
factorial()
function and passnumber
it as an argument. The result of the function is printed on the screen.
Here is a more detailed explanation of the Python program for calculating the factorial of a number:
1) First, we define a function called factorial()
that takes an integer n
as an argument. The function definition is as follows:
def factorial(n):
2) Next, we add a conditional statement to check if n
is equal to 0. If it is, the function returns 1. This is the base case for our function, which means that it will stop calling itself once the value of n
reaches 0. The base case is important because it allows our program to terminate and avoid an infinite loop.
if n == 0:
return 1
3) If n
is not 0, the function returns n * factorial(n-1)
. This line of code uses recursion, which means that the function calls itself with a smaller value of n
until the base case is reached. In this case, the function will multiply n
by the result of factorial(n-1)
, which is the factorial of n-1
.
else:
return n * factorial(n-1)
4) Outside the function, we ask the user to enter a number, which is stored in the variable number
. We use the int()
function to convert the user input from a string to an integer.
number = int(input("Enter a number: "))
5) Finally, we call the factorial()
function and pass number
as an argument. The result of the function is printed to the screen using the print()
function.
print(factorial(number))
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023