4.5.1.
6 Creating functions:
factorials
Some simple functions: factorials
It's marked with an exclamation mark and is equal to the
product of all natural numbers from one up to its argument.
#function definition
def factorial_function(n):
0! = 1 (yes! it's true) if n < 0:
1! = 1 return None
if n < 2:
2! = 1 *2 return 1
OUTPUT
3! = 1 *2*3
4! = 1 *2*3*4 product = 1
: for i in range(2, n +
: 1):
product *= i
n! = 1 * 2 * 3 * 4 * ... * n-1 * n return product
# calling the function
for n in range(1, 6): #
testing
print(n,
4.5.1.8 Creating functions | recursion
Recursion is a technique where a function invokes (calls)
itself
n! = n x (n-
1)!
#function definition
def factorial(n):
if n < 0:
return None
if n < 2:
return 1
return n * factorial(n - 1) # calling
itself, recursive call
Note: There is a little risk indeed. If you
#calling forget to consider the conditions which
x=int(input('Pls enter an integer:')) can stop the chain of recursive
print('The factorial of’, x, 'is’, invocations, the program may enter an
factorial(x)) infinite loop. You have to be careful.
print('bye')