The factorial of a positive integer n is the product of all positive integers less than or equal to n. The factorial of a number is represented by the symbol "!" . For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.
Here is a Python function that calculates the factorial of a given number using a for loop:
def factorial(n):
if n < 0:
return None
if n == 0:
return 1
result = 1
for i in range(1, n+1):
result *= i
return result
This function takes a single argument, n, and returns the factorial of n. It first checks if n is less than 0, if so it returns None. If n is equal to 0, it returns 1 (since the factorial of 0 is defined to be 1). It then initializes a variable named result to 1, then uses a for loop to iterate over the range of integers from 1 to n inclusive and multiply each number to result variable. Finally, the function returns the value of result, which is the factorial of n.
You can call this function and pass in any positive integer to calculate its factorial:
>>> factorial(5)
120
>>> factorial(3)
6
>>> factorial(10)
3628800
Alternatively python has math.factorial function which you can use without writing your own function.
import math
math.factorial(5)
Do note that factorial of number can be very large, even for relatively small numbers and python integers may not be large enough to store those values.