CS Till Recursion
CS Till Recursion
TYPES OF FUNCTIONS:
1. BUILT IN FUNCTION
2. USER-DEFINED FUNCTIONS
3. BUILT-IN FUNCTION:
print(),input(),sqrt(),abs(),
A. USER-DEFINED FUNCTION:
'''docstring
'''
statement(s)
In [8]:
name=str(input("Enter the name:"))
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
return()
greet(name)
print(greet.__doc__)
def function_name():
.........
.........
.........
.......
.......
function_name()
.......
.......
.......
RETURN STATEMENT
In [13]:
def greet():
print("Hello")
print(greet())
Hello
None
In [19]:
def greet():
return "Hello"
greet()
'xyz'
Out[19]:
In [28]:
num=int(input("Enter the number: "))
def squ(num):
''' This functions returns
the square of a given number
'''
return num**2
print(squ(num))
print(squ.__doc__)
In [1]:
#define a function to calculate Simple Interest:
def sim_int(p,r,t):
si=p*r*t/100
return si
s=sim_int(1000,10,3)
print("Simple Interest is=",s)
print("Simple Interest is=",sim_int(500,12,6))
pi=int(input("Enter the Principle: "))
ri=int(input("Enter the Rate: "))
td=int(input("Enter the Time: "))
sim=sim_int(pi,ri,td)
print("Simple Interest is=",sim)
In [6]:
#define a function to check whether a number is divisble by another number
def div(x,y):
if x%y==0:
print(x,"is divisble by",y)
else:
print(x,"is not divisble by",y)
div(12,4)
div(8,3)
div(9999,3)
12 is divisble by 4
8 is not divisble by 3
9999 is divisble by 3
In [7]:
#define a function to check whether a number is divisble by another number
def div(x,y):
if x%y==0:
return True
else:
return False
x=13
y=4
t=div(x,y)
print(x,"is divisble",y,":",t)
13 is divisble 4 : False
In [8]:
#define a function to count the number of digit for a given integer number
def count_digit(n):
count=0
while n>0:
n=n//10
count=count+1
return count
print("Number of digit: ",count_digit(12431241489612489))
print("Number of digit: ",count_digit(124))
In [9]:
#Write a program to calculate value of nCr
#step-1
#define a function to compute factorial
def fact(x):
f=1
for i in range(1,x+1):
f=f*i
print("Factorial of",x,"is=",f)
#step-2
#receive input from the user n and r
#step-3
#calculating nCr with the help of fact function
#step-4
#printing the final output
print("value of",n,"C",r,"is",c)
In [10]:
#Write a program to calculate value of nCr
#step-1
#define a function to compute factorial
def fact(x):
f=1
for i in range(1,x+1):
f=f*i
return f
#step-2
#receive input from the user n and r
#step-3
#calculating nCr with the help of fact function
#step-4
#printing the final output
print("value of",n,"C",r,"is",c)
In [11]:
print(sim_int(1000,10))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9980/922703614.py in <module>
----> 1 print(sim_int(1000,10))
In [12]:
print(sim_int(1000,10,5,78))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9980/2376813292.py in <module>
----> 1 print(sim_int(1000,10,5,78))
In [19]:
#Function to understand the concept of pass by reference in mutable data type
y=[10,20,30] #y is a list
print("Before changing values are:",y)
change(y) #y is an actual paramter
print("After changing the values are:",y)
In [1]:
#Function to understand the concept of pass by reference in immutable data types
y='NIET' #y is a string
print("Before changing string is:",y)
change(y) #y is an actual paramter
print("After changing string is:",y)
In [3]:
#Function to understand the concept of pass by reference in immutable data types
y=(1,'regional',333,'lion') #y is tuple
print("Before changing string is:",y)
change(y) #y is an actual paramter
print("After changing string is:",y)
~\AppData\Local\Temp/ipykernel_4932/48792912.py in change(x)
2
3 def change(x): #x is formal parameter
----> 4 x[1]='mohit'
5 print("String inside the function: ",x)
6 return
In [4]:
#Function to understand the concept of pass by reference in immutable data types
y=10 #y is a number
print("Before changing number is:",y)
change(y) #y is an actual paramter
print("After changing number is:",y)
In [5]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
5 10 15
In [7]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4932/2920327708.py in <module>
6 return
7
----> 8 pos_arg(5,10) #Less parameters are passed as per the mentioned in definition
In [8]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4932/1748090421.py in <module>
6 return
7
----> 8 pos_arg(5,10,15,20) #More parameters are passed as per the mentioned in defin
ition
KEYWORD ARGUMENTS:
1.Keyword arguments are passed at the time of function call! 2.The caller identifies the arguments
by the parameter name which are mentioned as keyword at time of function call. 3.This allows to
place arguments out of order because the Python interpreter can use the keywords provided to
match the values with parameters.
Note: A non keyword/positional argument can be followed by keyword argument, but keyword
argument can not be followed by non keyword/positional argument.
In [20]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
a= 1
b= 2
c= 3
a= 10
b= 20
c= 30
a= 100
b= 400
c= 300
In [4]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10796/2184526207.py in <module>
6 return
7
----> 8 keyword(100,b=300,a=400) #order must be maintained in the mixture of reqpos a
nd keyword
In [11]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
In [14]:
#Usage of keyword arguments
def person(name,age):
print(name)
print(age-5)
person(age=28,name='aakash')
aakash
23
In [7]:
#Usage of keyword arguments
print(5,6,7,end="++",sep='**')
print()
print(5,6,7,sep="##",end='@@')
5**6**7++
5##6##7@@
In [ ]:
print(obj,sep,end,file,flush) #all the parameters have some default value associated
DEFAULT ARGUMENT:
1.When an argument is given a default value while defining a function, it will be called a default
argument. 2.The default value will be considered if a value is not passed in the function call for
that argument.
In [18]:
#Demo of default argument
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 9/22
1/25/22, 8:15 PM CS Lecture-1
def project(name,language='python'):
print("project",name,"is developed using",language)
return
Python provides a facility to define a function even when number of arguments are not fixed. A
function having variable number of arguments can be defined by using variable-length-
argument.
This argument is prefixed with a special character asterisk (* or **) in function definition !
An asterisk (*) is placed before the variable name that holds the values of all non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call.
This argument will hold all the unspecified non-keyword arguments in the function definition by
packing them in a tuple. Non-keyword arguments will be prefixed with single asterisk in the
function definition.
Ex: *var_args
In [1]:
#demo of non-keyword variable length argument:
def var_len(*var): #variable length arguments can recieve zero or more than zero para
print("All the parameters are packed in tuple:",var) # Tuple will be created for
print("Accessing tuple elements one by one: ")
for v in var: #Loop can be used to access elements of tuple one by one
print (v)
return
var_len(10)
var_len(10,20,30,40,50)
In [2]:
var_len()
In [5]:
#fixing the number of arguments to at least one with variable length argument
def var_len1(pos,*var): #here one positional argument is required so function can rec
print("One position arguments: ",pos) #we have to manage positional argument sepe
print("Remaining parameters are packed in tuple: ",var) #a tuple will created for
print("Acessing tuple element one by one: ")
for v in var: #Loop can be used to access elements of tuple one by one
print(v)
return
var_len1()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4456/3094496204.py in <module>
9 return
10
---> 11 var_len1()
In [4]:
var_len1(100,200,300,400,500)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 11/22
1/25/22, 8:15 PM CS Lecture-1
In [1]:
# A function to add all the numbers provided by user at the time of
# function calling.
# function must receive at least one parameter
def add_param(first,*num):
add=first #first value which is passed through req positional arg. is added
for i in num:
add=add+i
return add
x=add_param(10,20,40,50)
print("Addition of the numbers is: ",x)
print("Addition of the numbers is: ",add_param(5))
print("Addition of the numbers is: ",add_param())
In [2]:
add_param(10,20,30,40,first=100)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9816/3236942631.py in <module>
----> 1 add_param(10,20,30,40,first=100)
In [3]:
add_param(first=100,10,20,30,40)
In [6]:
#Create a function to compute hcf of the given natural numbers:
def hcf_var(*num):
if len(num)==0: #when there is no parameter is passed in function calling
print("HCF is not possible")
HCF= 10
HCF= 4
HCF= 4
HCF is not possible
HCF= None
In [8]:
#Create a function to compute hcf of the given natural numbers without else:
def hcf_var(*num):
if len(num)==0: #when there is no parameter is passed in function calling
print("HCF is not possible")
return
print("HCF= ",hcf_var(10))
print("HCF= ",hcf_var(12,20,))
print("HCF= ",hcf_var(20,12,8))
print("HCF= ",hcf_var())
HCF= 10
HCF= 4
HCF= 4
HCF is not possible
HCF= None
1.This argument will hold all the unspecified keyword arguments in the function definition by
packing them in a dictionary. Keyword-arguments will be prefixed with double asterisk in the
function definition. Ex: **var_kwargs
In [9]:
#Demo of variable length keyword arguments
def var_key(**vark): #It accept all the zero or more keyword arguments
#all the keyword arguments will be packed in a dictionary as key
#and value pair under the name vark
print("All the keyword arguments are: ",vark)
return
var_key(a=10,b=20,c=30)
var_key() #It will create a blank dictionary
var_key(10)
All the keyword arguments are: {'a': 10, 'b': 20, 'c': 30}
All the keyword arguments are: {}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9816/418519626.py in <module>
9 var_key(a=10,b=20,c=30)
10 var_key() #It will create a blank dictionary
---> 11 var_key(10)
In [15]:
#Accessing individual keyword arg in a function def having var. len. keywords
def var_key1(**vark1):
for v in vark1: #for loop will iterate through only keys of the dictionary
print(v,vark1[v]) #values can be accessed by indexing on keys
return
var_key1(a=10,b=20,c=30)
a 10
b 20
c 30
STUDENT CHECK
1. Create a function to convert distance from feet to inches to cm.
2. Create a function to find the smallest number among three numbers.
3. Create a function to reverse a number and also check whether number is pallindrome or not.
4. Create a function to check whether a number is prime or not.
In [1]:
#Program to compute hcf/gcd of two numbers:
if a<b:
h=a
while True:
if a%h==0 and b%h==0:
print(h,"is HCF of",a,b)
break
h=h-1
In [2]:
def hcf(a,b):
if a<b:
h=a
else:
h=b
while True:
if(a%h==0 and b%h==0):
return h
h=h-1
In [5]:
def prime(n):
for i in range(2,n):
if n%i==0:
print(n,"is not a prime number")
break
else:
print(n,"is a prime number")
return
x=int(input("Enter a number: "))
prime(x)
Enter a number: 9
9 is not a prime number
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python:
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
In [6]:
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print("Outside the function global total : ", total)
In [10]:
#Scope of variable
a=10 #it is a global variable as it is not defined inside the body of function
def scope():
print("Value of global a is accessed inside the function scope:",a)
a=20 # once we define a variable inside the function body it becomes local
#so same name global can not be access from the function.
scope()
print("VAlue of outside the function: ",a)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11504/2267888031.py in <module>
9 return
10
---> 11 scope()
12 print("VAlue of outside the function: ",a)
~\AppData\Local\Temp/ipykernel_11504/2267888031.py in scope()
2 a=10 #it is a global variable as it is not defined inside the body of functio
n
3 def scope():
----> 4 print("Value of global a is accessed inside the function scope:",a)
5 a=20 # once we define a variable inside the function body it becomes loca
l
6 #so same name global can not be access from the function.
In [8]:
#Scope of variable
a=10 #it is a global variable as it is not defined inside the body of function
def scope():
a=20 # once we define a variable inside the function body it becomes local
#so same name global can not be access from the function.
print("Value of global a is accessed inside the function scope:",a)
scope()
print("VAlue of outside the function: ",a)
In [13]:
#How to modify a global variable inside the body of function it becomes
#We have to write global statement
def scope():
global a # it allow to access and modify the global variable inside the function
a=20
print("Value of a inside the function: ",a)
print(id(a))
return
scope()
print("Value of outside the function: ",a)
print(id(a))
In [1]:
def fun():
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 17/22
1/25/22, 8:15 PM CS Lecture-1
x=100
print("Inside function x= ",x)
return
fun()
print("Outside the function x= ",x) # A local variable can not be accessed from outs
# as it is no longer exist after the function exit.
In [2]:
# A local variablle can not be accessed outside even if it is being
#returned by function as only it's value is returned
def fun():
x=500
print("Inside the function x= ",x)
return x
fun()
print("Outside the function x=",x)
RECURSION IN PYTHON:
Recursion is the process of defining something in terms of itself.
In Python, it’s also possible for a function to call itself! A function that calls itself is said to be
recursive, and the technique of employing a recursive function is called recursion.
It may seem peculiar for a function to call itself, but many types of programming problems are
best expressed recursively. When you bump up against such a problem, recursion is an
indispensable tool for you to have in your toolkit.
What is Recursion?
The word recursion comes from the Latin word recurrere, meaning to run or hasten back, return,
revert, or recur.
A recursive definition is one in which the defined term appears in the definition itself. Self-
referential situations often crop up in real life, even if they aren’t immediately recognizable as
such. For example, suppose you wanted to describe the set of people that make up your
ancestors. You could describe them this way:
In [1]:
# Recursive function for countdown.
def countdown(n):
print(n)
if n==0: # Recursion termination
return
else:
countdown(n-1) #Recursive call
In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms
In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms
print(b,c,end=',')
for i in range(3,n+1):
if i%2==0:
d=a+b+c
else:
d=b+c
print(d,end=',')
a=b
b=c
c=d
In [ ]:
#Program to print the following Series:
#2, 15, 41, 80, 132, 197, 275, 366, 470, 587
In [4]:
a = 2
b = 13
n =int(input("Enter a no. - "))
for i in range(1, n+1, 1):
print(a,end=',')
a = a + b*i
Enter a no. - 9
2,15,41,80,132,197,275,366,470,
In [3]:
#Program to add n natural number using recursion
def rec_add(n):
if n==1: #base condition
return 1
else:
return rec_add(n-1)+n #recursive condition
In [8]:
#Program to compute factorial of a given number using recursion
def fact(n):
if n==1: #base case
return 1
else:
return n*fact(n-1) #Recursive Case(Self Refrential Case)
Enter a number: 5
Factorial: 120
In [11]:
# A recursive function to calculate exponential (power) of a given numbe (x**y)
def exp(x,y):
if y==0: #Base Case
return 1
else:
return x*exp(x,y-1) #Recursive Case
print (exp(2,1))
In [ ]:
# W.A.P. to calculate sum of digits of a given number using recursion.
# W.A.P. to reverse a given number using recursion.
# W.A.P. to display n terms of fibonacci series using recursion.
In [1]:
#Program to calculate sum of digits of a given number using recursion.
def rec_digit(n):
if n==0:
return 0
else:
return n%10 + rec_digit(n//10)
In [3]:
# W.A.P. to reverse a given number using recursion.
def rev(n,r=0):
if n==0:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 21/22
1/25/22, 8:15 PM CS Lecture-1
return r
else:
return rev(n//10,r*10+n%10)
In [7]:
# W.A.P. to display n terms of fibonacci series using recursion.
def fib(n):
if n==1: #base case
return 0
elif n==2: #base case
return 1
else:
return fib(n-1)+fib(n-2) #Recursive Case
def fib_series(n):
for i in range(1,n+1):
print(fib(i),end=',')
In [9]:
#Program to generate fibonacci Series using recursion.
def fibonacci(n):
if(n <= 2): #base case
return n
else:
return(fibonacci(n-1) + fibonacci(n-2)) #recursive case
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(1,n+1):
print(fibonacci(i),end=',')