0% found this document useful (0 votes)
11 views3 pages

Unit III Lecture Hour 6

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

Unit III Lecture Hour 6

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

UNIT III CONTROL FLOW, FUNCTIONS

Lecture Hour 6 – Function composition, Recursion

Function composition

Function composition is the way of combining two or more functions in such a way that the output of
one function becomes the input of the second function and so on. For example, let there be two functions
“F” and “G” and their composition can be represented as F(G(x)) where “x” is the argument and output
of G(x) function will become the input of F() function.

# Function to add 2
# to a number
def add(x):
return x + 2

# Function to multiply
# 2 to a number
def multiply(x):
return x * 2

# Printing the result of


# composition of add and
# multiply to add 2 to a number
# and then multiply by 2
print("Adding 2 to 5 and multiplying the result with 2: ",
multiply(add(5)))

>>> Adding 2 to 5 and multiplying the result with 2: 14

Recursion

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively
In Python, we know that a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.

The following image shows the working of a recursive function called recurse

Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

>>> The factorial of 3 is 6

Let's look at an image that shows a step-by-step process of what is going on:
# Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:", end =’ ‘)
for i in range(nterms):
print(recur_fibo(i), end =’ ‘)

>>> Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34

You might also like