[go: up one dir, main page]

0% found this document useful (0 votes)
6 views2 pages

Factorial Function and Recursion (F3)

The document explains how to create a factorial function in Python using both iterative and recursive methods. It provides code examples for defining the function and handling edge cases, such as negative inputs. Additionally, it warns about the risks of infinite loops in recursion if base conditions are not properly implemented.

Uploaded by

nuramalinanor288
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Factorial Function and Recursion (F3)

The document explains how to create a factorial function in Python using both iterative and recursive methods. It provides code examples for defining the function and handling edge cases, such as negative inputs. Additionally, it warns about the risks of infinite loops in recursion if base conditions are not properly implemented.

Uploaded by

nuramalinanor288
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like