0% found this document useful (0 votes)
5 views22 pages

CS Till Recursion

The document provides an overview of types of functions in Python, including built-in and user-defined functions, along with their syntax and examples. It covers essential concepts such as return statements, argument types (required, keyword, default, and variable-length), and demonstrates various function implementations like greeting, calculating simple interest, and checking divisibility. Additionally, it highlights common errors encountered when defining and calling functions.
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)
5 views22 pages

CS Till Recursion

The document provides an overview of types of functions in Python, including built-in and user-defined functions, along with their syntax and examples. It covers essential concepts such as return statements, argument types (required, keyword, default, and variable-length), and demonstrates various function implementations like greeting, calculating simple interest, and checking divisibility. Additionally, it highlights common errors encountered when defining and calling functions.
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/ 22

1/25/22, 8:15 PM CS Lecture-1

TYPES OF FUNCTIONS:
1. BUILT IN FUNCTION
2. USER-DEFINED FUNCTIONS

3. BUILT-IN FUNCTION:

print(),input(),sqrt(),abs(),

A. USER-DEFINED FUNCTION:

SYNTAX: def function_name(parameters/arguments):

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

Enter the name:HAKFHA


Hello, HAKFHA. Good morning!

This function greets to


the person passed in as
a parameter

def function_name():
.........
.........
.........
.......
.......

function_name()
.......
.......
.......

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 1/22


1/25/22, 8:15 PM CS Lecture-1

In [10]: for i in range(1,6):


for j in range(1,6-i):
print(" ",end="")
k=i
for j in range(1,i+1):
print(k,end="")
k=k+1
k=k-2
for j in range(1,i):
print(k,end="")
k=k-1
print()

1 232 34543 4567654567898765

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

Enter the number: 9


81
This functions returns
the square of a given number

In [1]:
#define a function to calculate Simple Interest:

def sim_int(p,r,t):
si=p*r*t/100
return si

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 2/22


1/25/22, 8:15 PM CS Lecture-1

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)

Simple Interest is= 300.0


Simple Interest is= 360.0
Enter the Principle: 5000
Enter the Rate: 10
Enter the Time: 5
Simple Interest is= 2500.0

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

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 3/22


1/25/22, 8:15 PM CS Lecture-1
Number of digit: 17
Number of digit: 3

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

n=int(input("Enter the value of n in nCr: "))


r=int(input("Enter the value of r in nCr: "))

#step-3
#calculating nCr with the help of fact function

c=fact(n)/(fact (r) * fact(n-r))

#step-4
#printing the final output

print("value of",n,"C",r,"is",c)

Enter the value of n in nCr: 5


Enter the value of r in nCr: 2
Factorial of 5 is= 120
Factorial of 2 is= 2
Factorial of 3 is= 6
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9980/2248361591.py in <module>
18 #calculating nCr with the help of fact function
19
---> 20 c=fact(n)/(fact (r) * fact(n-r))
21
22 #step-4

TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

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

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 4/22


1/25/22, 8:15 PM CS Lecture-1
n=int(input("Enter the value of n in nCr: "))
r=int(input("Enter the value of r in nCr: "))

#step-3
#calculating nCr with the help of fact function

c=fact(n)/(fact (r) * fact(n-r))

#step-4
#printing the final output

print("value of",n,"C",r,"is",c)

Enter the value of n in nCr: 10


Enter the value of r in nCr: 5
value of 10 C 5 is 252.0

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

TypeError: sim_int() missing 1 required positional argument: 't'

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

TypeError: sim_int() takes 3 positional arguments but 4 were given

In [19]:
#Function to understand the concept of pass by reference in mutable data type

def change(x): #x is formal parameter


x[1]='123'
print("Value inside the function",x)
return

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)

Before changing values are: [10, 20, 30]


Value inside the function [10, '123', 30]
After changing the values are: [10, '123', 30]

In [1]:
#Function to understand the concept of pass by reference in immutable data types

def change(x): #x is formal parameter


x='mohit'
print("String inside the function: ",x)
return
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 5/22
1/25/22, 8:15 PM CS Lecture-1

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)

Before changing string is: NIET


String inside the function: mohit
After changing string is: NIET

In [3]:
#Function to understand the concept of pass by reference in immutable data types

def change(x): #x is formal parameter


x[1]='mohit'
print("String inside the function: ",x)
return

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)

Before changing string is: (1, 'regional', 333, 'lion')


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4932/48792912.py in <module>
8 y=(1,'regional',333,'lion') #y is tuple
9 print("Before changing string is:",y)
---> 10 change(y) #y is an actual paramter
11 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

TypeError: 'tuple' object does not support item assignment

In [4]:
#Function to understand the concept of pass by reference in immutable data types

def change(x): #x is formal parameter


x=777
print("Number inside the function: ",x)
return

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)

Before changing number is: 10


Number inside the function: 777
After changing number is: 10

TYPES OF ACTUAL ARGUMENTS:


localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 6/22
1/25/22, 8:15 PM CS Lecture-1

1. Required /Positional arguments


2. Keyword arguments
3. Default arguments
4. Variable-length arguments

REQUIRED POSITIONAL ARGUMENTS: Required arguments are the arguments passed to a


function in correct positional order.The number of arguments in the function call should match
exactly with the function definition.

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

pos_arg(5,10,15) #All the parameters are passed

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

pos_arg(5,10) #Less parameters are passed as per the mentioned in definition

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

TypeError: pos_arg() missing 1 required positional argument: 'c'

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

pos_arg(5,10,15,20) #More parameters are passed as per the mentioned in definition

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 7/22


1/25/22, 8:15 PM CS Lecture-1

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

TypeError: pos_arg() takes 3 positional arguments but 4 were given

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

keyword(1,2,3) #passed as a required positional arguments


keyword(a=10,b=20,c=30) #all parameters are passed as keywords arguments
keyword(100,c=300,b=400) #keyword argumnets following required positional arguments t

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

keyword(100,b=300,a=400) #order must be maintained in the mixture of reqpos and keywo

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 8/22


1/25/22, 8:15 PM CS Lecture-1

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

TypeError: keyword() got multiple values for argument 'a'

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

keyword(a=100,b=200,300) #positional arguments can not follow keywords arguments

File "C:\Users\callage\AppData\Local\Temp/ipykernel_9816/1405506763.py", line 8


keyword(a=100,b=200,300) #positional arguments can not follow keywords arguments
^
SyntaxError: positional argument follows keyword argument

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

project("Online exam system","java") # Required Positional Argument


project(language='C++',name="Reservation System") # Keyword Argument
project("Election Data Analysis") #Required Positional Argument
project(language="Java") #One positional arguments is missing

project Online exam system is developed using java


project Reservation System is developed using C++
project Election Data Analysis is developed using python
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10796/1889896714.py in <module>
8 project(language='C++',name="Reservation System") # Keyword Argument
9 project("Election Data Analysis") #Required Positional Argument
---> 10 project(language="Java") #One positional arguments is missing

TypeError: project() missing 1 required positional argument: 'name'

VARIABLE LENGTH ARGUMENTS:


1.NON-KEYWORDS ARGUMENTS 2.KEYWORDS ARGUMENTS

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 !

VARIABLE LENGTH ARGUMENTS


You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.

Syntax: Syntax for a function with non-keyword variable arguments is this −

def function_name(*var_args_tuple ): "function_docstring" function_body return (expression)

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.

NON-KEYWORDS VAR. LENGTH


ARGUMENTS:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 10/22
1/25/22, 8:15 PM CS Lecture-1

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)

All the parameters are packed in tuple: (10,)


Accessing tuple elements one by one:
10
All the parameters are packed in tuple: (10, 20, 30, 40, 50)
Accessing tuple elements one by one:
10
20
30
40
50

In [2]:
var_len()

All the parameters are packed in tuple: ()


Accessing tuple elements one by one:

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

TypeError: var_len1() missing 1 required positional argument: 'pos'

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

One position arguments: 100


Remaining parameters are packed in tuple: (200, 300, 400, 500)
Acessing tuple element one by one:
200
300
400
500

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

Addition of the numbers is: 120


Addition of the numbers is: 5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9816/3241582378.py in <module>
12 print("Addition of the numbers is: ",x)
13 print("Addition of the numbers is: ",add_param(5))
---> 14 print("Addition of the numbers is: ",add_param())

TypeError: add_param() missing 1 required positional argument: 'first'

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)

TypeError: add_param() got multiple values for argument 'first'

In [3]:
add_param(first=100,10,20,30,40)

File "C:\Users\callage\AppData\Local\Temp/ipykernel_9816/14697281.py", line 1


add_param(first=100,10,20,30,40)
^
SyntaxError: positional argument follows keyword argument

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

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 12/22


1/25/22, 8:15 PM CS Lecture-1
return
else:
low=num[0] #initialize min value of the tuple
for i in num: #finding actual minimum in the tuple
if low>i:
low=i
for i in range(low,0,-1):
for v in num:
if v%i!=0:
break
else:
return i
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

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

low=num[0] #initialize min value of the tuple


for i in num: #finding actual minimum in the tuple
if low>i:
low=i
for i in range(low,0,-1):
for v in num:
if v%i!=0:
break
else:
return i

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

KEYWORD VARIABLE LENGTH ARGUMENT:

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 13/22


1/25/22, 8:15 PM CS Lecture-1

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)

TypeError: var_key() takes 0 positional arguments but 1 was given

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:

a=int(input("Enter the first number: "))


b=int(input("Enter the second number: "))

if a<b:
h=a

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 14/22


1/25/22, 8:15 PM CS Lecture-1
else:
h=b

while True:
if a%h==0 and b%h==0:
print(h,"is HCF of",a,b)
break
h=h-1

Enter the first number: 6


Enter the second number: 9
3 is HCF of 6 9

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

a=int(input("Enter the first number: "))


b=int(input("Enter the second number: "))
z=hcf(a,b)
print(z,"is HCF of",a,b)

Enter the first number: 8


Enter the second number: 12
4 is HCF of 8 12

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

SCOPE OF VARIABLE IN PYTHON:


In programming languages, variables need to be defined before using them. These variables can
only be accessed in the area where they are defined, this is called scope. You can think of this as a
block where you can access variables.

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 15/22


1/25/22, 8:15 PM CS Lecture-1

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:

1.Local Variable 2.Global Variable

GLOBAL VS LOCAL VARIABLES


Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.

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)

Inside the function local total : 30


Outside the function global total : 0

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.

print("Modified value of inside the function: ",a)


return

scope()
print("VAlue of outside the function: ",a)

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 16/22


1/25/22, 8:15 PM CS Lecture-1

---------------------------------------------------------------------------
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.

UnboundLocalError: local variable 'a' referenced before assignment

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)

print("Modified value of inside the function: ",a)


return

scope()
print("VAlue of outside the function: ",a)

Value of global a is accessed inside the function scope: 20


Modified value of inside the function: 20
VAlue of outside the function: 10

In [13]:
#How to modify a global variable inside the body of function it becomes
#We have to write global statement

a=50 #global variable

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

Value of a inside the function: 20


1591599170384
Value of outside the function: 20
1591599170384

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.

Inside function x= 100


---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12152/1923083856.py in <module>
5
6 fun()
----> 7 print("Outside the function x= ",x)

NameError: name 'x' is not defined

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)

Inside the function x= 500


---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3272/1005135858.py in <module>
8
9 fun()
---> 10 print("Outside the function x=",x)

NameError: name 'x' is not defined

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?

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 18/22


1/25/22, 8:15 PM CS Lecture-1

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:

Eg.: Your ancestors = (your parents) + (your parent's ancestors)

Recursion techniques in Python:


When you call a function in Python, the interpreter creates a new local namespace so that names
defined within that function don’t collide with identical names defined elsewhere. One function
can call another, and even if they both define objects with the same name, it all works out fine
because those objects exist in separate namespaces.

In [1]:
# Recursive function for countdown.

def countdown(n):
print(n)
if n==0: # Recursion termination
return
else:
countdown(n-1) #Recursive call

n=int(input("Enter your countdown number: "))


countdown(n)

Enter your countdown number: 7


7
6
5
4
3
2
1
0
print(obj,sep,end,file,flush) #all the parameters have some default value associated with them 1.obj="ANything
you wanted to show as your results" 2.sep="Space" 3.end="Null character or New Line" 4.file="File where you
wanted to show your result" 5.flush="Flush by default is set to 0 i.e, it will store your result in memory but if you
set flush=1 then your result will be flusded out from the memory".

In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms

n=int(input("Enter the number:"))


a=1
b=2
for i in range(1,n+1):
if(i%2==1):
print(a,end=',')
a=a*3
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 19/22
1/25/22, 8:15 PM CS Lecture-1
else:
print(b,end =',')
b=b*3

In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms

n=int(input("Enter the number:"))


a=0
b=1
c=2

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

n=int(input("Enter the range of number(Limit):"))


i=1
value=2
while(i<=n):
print(value,end=",")
value+=i*13
i+=1

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

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 20/22


1/25/22, 8:15 PM CS Lecture-1

n=int(input("Enter the term: "))


print(rec_add(n))

Enter the term: 5


15

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)

x=int(input("Enter a number: "))


print("Factorial: ",fact(x))

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)

n=int(input("Enter the digit: "))


print("Sum of digit: ",rec_digit(n))

Enter the digit: 5678


Sum of digit: 26

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)

n=int(input("Enter the number: "))


print("Reverse of the number is: ",rev(n))

Enter the number: 654


Reverse of the number is: 456

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

n=int(input("Enter the number of term: "))


(fib_series(n))

Enter the number of term: 10


0,1,1,2,3,5,8,13,21,34,

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

Enter number of terms:10


Fibonacci sequence:
1,2,3,5,8,13,21,34,55,89,

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 22/22

You might also like