You are on page 1of 95

CHAPTER 3

WOR K IING
WO RK NG
WI
WITTH
H
FUNC
FUN CTTI IOO NNSS
SELF-STUDY PRESENTATION
THROUGH ANIMATIONS.

Not for commercial use.


Dictionary meaning
of Function ?
What is FUNCTIONS
FUNCTION ?
In dictionary,
FUNCTION means DEED
( പ്രവർത്തനം )

FUNCTION = പ്രവൃത്തി
കൃത്യം
ആചരണം
ചുമതല
ആഘോഷം
തൊഴില്‍
ധര്‍മ്മം
പരിപാടി

In programming Language, A function is a block of


statements to perform an action.
Why Function is needed ?
 It is difficult to write much more
Big matter on a tiny page. statements as a single program
or unit.
Horrible !  And also difficult to find the
What are my Duties ? content.
Indian constitution
National Pledge India is my country and all Indians are my brothers
and sisters. I love my country and I am proud of its rich and varied
heritage. I shall always strive to be worthy of it. I shall give
respect to my parents, teachers and all elders and treat everyone
with courtesy. To my country and my people, I pledge my
devotion. In their well-being and prosperity alone lies my
happiness. Fundamental Duties : It shall be the duty of every
citizen of India- (a) to abide by the Constitution and respect its
ideals and institutions, the National Flag and the National
Anthem; Fundamental Rights : are defined as the basic human
rights of all citizens. These rights, defined in Part III of the
Constitution, applied irrespective of race, place of birth, religion,
caste, creed, or gender. They are enforceable by the courts,
subject to specific restrictions. The Directive Principles of State
Policy are guidelines for the framing of laws by the government. )
Writing paragraph separately is
much easier for read and write.

National Pledge : India is my country and all Indians are my brothers


and sisters. I love my country and I am proud of its rich and varied
heritage. I shall always strive to be worthy of it. I shall give respect
to my parents, teachers and all elders and treat everyone with
Easy to read. courtesy. To my country and my people, I pledge my devotion. In
their well-being and prosperity alone lies my happiness.

Fundamental Duties : It shall be the duty of every citizen of India- (a) to


abide by the Constitution and respect its ideals and institutions,
the National Flag and the National Anthem; (b) to cherish and
follow the noble ideals which inspired our national strugg …..

Fundamental Rights : are defined as the basic human rights of all


citizens. These rights, defined in Part III of the Constitution, applied
irrespective of race, place of birth, religion, caste, creed, or gender.
They are enforceable by the courts, subject to specific restrictions.
The Directive Principles of State Policy are guidelines for the
framing of laws by the government.
How I wrote a Paragraph ?.
REMEMBER 3 THINGS.
TITLE OF PARAGRAPH
1
FULL COLON
2
HANGING
3 ( INDENT ) LINES
National Pledge : India is my country and all Indians are my
n brothers and sisters. I love my country and I am proud
Indenta tio
re of its rich and varied heritage. I shall always strive to
Space b efo
ts be worthy of it. I shall give respect to my parents,
statem e n
teachers and all elders and treat everyone with

----- courtesy. To my country and my people, I pledge my


devotion. In their happiness and prosperity alone lies
my happiness.

INDENT = മാര്‍ജിനില്‍ നിന്ന്‌അക ലം വിട്ട്‌ടൈപ്പ്‌ചെയ്യുക


What is the link between
def greatest ( List ) :
max = List[0] PARAGRAPH and PYTHON PROGRAM.
for val in List[1:] :
if val > max : max = val
return max
eval(input("Ent
greatest(a)

Programs are like a big article. It contains hundreds of


statements. So we will break it into small pieces called
functions ( Paragraph of Statements ).We can learn more
about it in the 4th chapter PYTHON LIBRARIES.
e s t h e
a t d o
W h
n d o ?
t i o
f unc
FUNCTION TAKES
DATA, AND WILL
PRODUCE DESIRED
OUTPUT
o n

DATA
fu nc t i
e s the
h a t do
W
do?
OUTPUT
Assume any value in x and
calculate polynomial 2x2  

= 2x 2

For x = 1, the result is 2 * 12 = 2


For x = 2 , the result is 2 * 22 = 8
For x = 3, the result is 2 * 32 = 18
  Passing
  the value 1 to x
and Returns 22 * Click
1 ** 1here
= 2 to watch 

FUNCTION TAKES DATA
Passing
  the value 2 to x
and Returns 82 * Click
2 ** 2here
= 8 to watch 
PRODUCE OUTPUT  Passing
  the value 3 to x
and Returns 18 Click
2 * 3 ** 3 =here
18 to watch 
Different type of functions.

1) Built in Functions.

2) Modules.

3) User - defined functions.


Built in Functions.
The predefined functions are called
built-in functions. It can be execute
by a simplefunction call statement.

 min() Return smallest.


 max() Return largest.
 pow() Returns xy.
 len() Returns length.
 int() Returns integer.
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916
32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()"
for more information.
>>> min(10,-20) min() Return smallest value.
-20
>>> max(-25,80) max() Return largest.
80
>>> pow(2,3) pow() Returns xy.
8
>>> len("ANIL") len() Returns length.
4
>>> int(3.14) int() Returns integer.
3

The predefined functions are called built-in functions.


It can be execute by a simple function call statement.
Modular Functions.
A module is a file that contains functions,
classes, variables, and constants. To use the
functions of a module, you need to import
the module using the import statement. The
math module is an example. It contains the most
popular mathematical functions.
>>> import math
>>> math.pi
3.141592653589793 After importing the modules,
>>> math.sqrt(25) use the function.
5.0
>>> math.floor(3.14)
3 math.floor() - Drop down to the
>>> math.ceil(3.14)
nearest integer.
4
>>> import random math.ceil() - Grow up to the nearest
integer.
>>> random.randomint(10,20)
17

A module contains many functions and other objects.


After importing the modules, use the function.
in e
t o def
How
t i o n?
f un c
a
Anatomy of a functi on.
def 𝒇 unction name ( arguments ) :

statement 1 Keyword “def” is used to define


a function. The very first line is
statement 2
-------- called Function header. It
begins with the keyword “def”
…………… and end with a colon (“:”).

The body consisting of 1 or more


statements is called Function Body
or function suit. Put some space
(Indentation) before statements.
Functi on header Has these 4 elements.
def function Name ( )) : 4 End with a colon (“:”)
1 2 A pair of Brackets “()”

3
Function Name.
It begins with the keyword “def”

Statement
-------- 1
Function Body
Statement 2 or function suit.
……………

Space before statements (Indentation)


Some examples
def pie ( ) :
return 22 / 7
Pledge ( ) will print
def root2 ( ) :
few lines of National
return 1.4142 Pie ( ) will return
Pledge.
result of 22 / 7 =
def pledge ( ) :
3.14.
print ( “India is my country…”)

 
Click Me 
 
Click Me 
l i n g
Cal
t i on ?
fun c
I wrote a
wonderfull
function.
What Next ?

Call the function


where you want !

Function call is a request to perform the


action defined by the function.
FUNCTION CALLING
Function call is a request to perform the action
defined by the function.
I want to read “Cat on Mat”

Get page no and go to that page.

Here we request to do the action


defined by the function name.
Function call is a request to perform the
action defined by the function.

def :
 

return 22/7
Goto the function
definition and return
Start execution from below.
back with the result.

= Pie( ) Function call statement

print (“Value of Pie is “, p)


Functi on call is a request to perform the acti on
defi ned by the functi on.
>>> def pie ( ) :
return 22 / 7

Definitions Calling
>>> def root2 ( ) :
return 1.4142

Function
Function Call

>>> def pledge ( ) :


print ( "India is my country…")
>>> pledge() Calling F u n c ti o n s .
>>> India is my country…

>>> b = root2()
Function Call
>>> print ( b )
>>> 1.4142

>>> a = pie()
Function Call
>>> print ( a )
>>> 3.142857142857143
def A ( ) :
print( “Up above the world so high,” )

def B ( ):
print (“TWINKLE, twinkle, little star,”)  

def C ( ) : Click Me 
print ( ”Like a diamond in the sky.” )

def D ( ) :
print ( ”How I wonder what you are! “ )
INVOKE THE FUNCTIONS IN THE
FOLLOWING ORDER
B()
I wrote the lyrics of a song into 4
functions. In what 
D()
A() order I should
call (invoke) these
C() functions.
>>> def A ( ) :
print("Up above the world so high,")
C() # Calling the Function C()
>>> def B ( ):
print ("TWINKLE, twinkle, little star,")
D() # Calling the Function D()
>>> def C ( ) : OUTPUT
print ( "Like a diamond in the sky." ) >>>
TWINKLE, twinkle, little star,
>>> def D ( ) : How I wonder what you are!
print ( "How I wonder what you are! " ) Up above the world so high,
A() # Calling the Function A() Like a diamond in the sky.
>>>
>>> B()
OUT OF SYLLABUS.

Who made this parody and


what it means ?
u m e n t s
Arg
&
a m e t e r s
Pa r
Imagines that functions are
processing machines.
Input data
WHAT DOES THE
FUNCTION DO?

1. Accepts Data
Ou

2. Carried out desired process.


tp

3. Produce Output
ut

Arguments act as an input to the function, to


carries out the specified task.
ARGUMENTS OR PARAMETERS
The values passed to a function are called
arguments or Parameters.
arguments
Arguments act as an input to
the function, to carry out
the specified task.

Function Definition Returns output


Assume any value in x and calculate 2x2
 

= 2x 2 X’ ‘ receives a value,
and f() returns 2 * x2
For x = 1, the result is 2 * 12 = 2
𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 𝒄𝒂𝒏 𝒖𝒔𝒆
For x = 2 , the result is 2 * 22 = 8 𝒎𝒂𝒏𝒚 𝒕𝒊𝒎𝒆𝒔 𝒘𝒊𝒕𝒉
𝒅𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒕 𝒗𝒂𝒍𝒖𝒆𝒔
For x = 3, the result is 2 * 32 = 18
  Passing
  the value 1 to x
and Returns 22 * Click
1 ** 1here
= 2 to watch 
 Passing
  the value 2 to x
and Returns 82 * Click
2 ** 2here
= 8 to watch 
 Passing
  the value 3 to x
and Returns 18 Click
2 * 3 ** 3 =here
18 to watch 
Assume any value in x and calculate 2x2

def :
 

returnAnd2𝑥return
*becomes
* 2 * 𝑥5 = 50 2

What is the answer if x = 5 ?


Start execution from below.

= int ( input ( “Enter No ” ) )


a= 5  Click Me

print (“Answer is ”, a )
def 𝑓(𝑥) :
return 2 * 𝑥 * 𝑥
# Input the Value 5.

𝑥 = int ( input ( “Enter No ” ) )


# Calling the Function F(5) by OUTPUT
a = 𝑓(𝑥) passing the value 5. >>>
Answer is 50
print (“Answer is ”, a ) >>>
Difference between Arguments and
Parameters
a=10 b=20 c=30 d=40
def add ( a , b , c , d ) :
Parameter are variables,
which receives the values
print ( “Sum is “, a+b+c+d ) of passing arguments.

Arguments are the actual


values passed to the function
30
40
10

20

add ( 10 , 20, 30, 40 ) when it is called

Arguments act as an input to the function, to


carry out the specified task.
ARGUMENTS OR PARAMETERS
What
This is this 
parameter
def area ( r ) : Parameter are variables, receiving passing
return 3.14 * r ** r values within the function definition.

Arguments are the actual


a = area ( 10 ) values passed to the
function when it is called
g u me n t
Thi s is ar
What is this

print ( “Area of the circle is”, a)


A RG U M E N T S C A N B E E I T H E R L I T E R A L S ,
VA R I A B L ES O R E X P R ES S I O N S .
def add ( a,b,c) : Literal 10, value of
variable x and the end
return a+b+c result of expression
(3*10) i.e. 30 will be
X = 20 Start execution from here. passed as arguments.
add (10, X, (3*10) )

E x p re s s i o n
Va r i a b l e
L i te ra l
o t h i n g .
r n n
Re t u
VOID
T I O N S .
FUN C
NO RETURN – VOID FUNCTIONS functions which will not
return values are called void functions.

Example of
def add ( a, b , c , d ) : No Return Void Functions.
print ( “Sum is ”, a + b + c + d )
Missing Return statement here

Start execution from below.


10

20

30

40
s = add(10, 20, 30, 40)
avg = s/4 How can calculate
average if add () will
not return any value.
def add ( a, b , c , d ) : Print the sum 100.
No return or return
print ( “Sum is ”, a + b + c + d )
None.
s = add(10, 20, 30, 40) 
DON ’ T Do

Causing the error TypeError:


avg = s/4
 unsupported operand type(s) for /:
'NoneType' and 'int'
What is Return Statement ?

Give me some
numbers. I'll return
their sum.

The return statement


stops the execution of
a function and returns
to the caller function.
What is Return Statement ?

 Return statement is used to stop the execution of a

function and come back to called statement.

 Return statement returns the result if we needed.

 By default return statement returns a None value.

 In Python multiple values can be returned.


RETURN ONE VALUE
def add ( a , b , c , d ) : Return statement, stop
function execution and
return a+b+c+d
Return 100 come back. It also returns
the result if we needed.
Return statement By default it will return a
returns the result. None value.
Start execution from below.
10

20

30

40
s = add(10,20,30,40)
avg = s/4
print (“Sum =”, s, “Avg = ”, avg)
Return statement, stop function execution and
come back. It also returns the result if we needed.
By default it will return a None value.
ALL IN ONE
Python is a dynamically-
def add ( a , b ) : typed language. It doesn't
return a + b know about the type of the
variable until the code runs.
ALL IN ONE

s = add(10,20 ) 10 + 20 = 30
s = add ( 1.5, 2.5 ) 1.5 + 2.5 = 4.0
anil + kumar = anilkumar
s = add(“anil”, “kumar” )

s = add( [10,20], [5,15] ) [10,20,5,15]


Passing 2 Integers
Passing 2 Float
Passing 2 Strings

Passing 2 List

Python is a dynamically-typed language.


It doesn't know about the type of the
variable until the code runs.
RETURN MULTIPLE VALUES
def Sum_Avg ( a , b , c , d ) :
t=a+b+c+d t=100 Python can return multiple
values from a function.
return100t, t/4
25

sum, avg = Sum_Avg (10, 20,10,20,30,40


Passing 30, 40)
print (“Sum = “, sum , ” Avg = “, avg)

go t s u m
Here I
er a ge .
an d av
In Python, multiple assignment is posible like this.

a m e =
N 10 20 30
z = 1n 0i l,”2 0 , 3 0
x , y , “A A = 0 20 an d 3 0
l = 1 5
lgets valu =” 0s 1
​ 0 ,
R o e
B I I II ”
d Z h a v e
s s = “ X , 1 5, “ X
X, Y an la
C lass = “AC = 0 n i l”
m e , r ll , c
o pe n e d ?
na w il l h a
What = c = 0
a=b ne d ? 
ill ha p e
Wh a t w
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> x , y , z = 10 , 20 , 30 Assignin
g multip
>>> name, roll, Class = “Anil”, 15, “XII”into mult le
iple vari values ​
a single ab
>>> a = b = c = 0 stateme les using
'multiple nt is ca
>>> print (x, y, z ) assignme lled
n t'
>>> 10 20 30
>>> print (name, roll, Class)
>>> Anil 15, XII
>>> print(a,b,c)
>>> 0 0 0
Different types of arguments.

There are 3 (4) types of arguments.


Required
1 arguments or
Positional arguments
2
Default arguments
3
Keyword arguments

and Varying arguments.


1 Required (Positional) arguments.
These are mandatory arguments and take orderly.

2 Default arguments
Provides default value to an argument. It will be
used when we omit value during function call.

3 Keyword arguments
Keyword arguments are same as default
arguments but it allows you to give
name-value pairs instead of just the value.
POSITIONAL ARGUMENTS
Positional arguments are mandatory and take values
orderly. That is why we called it Required arguments.
Both the Arguments and Parameters should be matched.

def add ( a , b , c , d ) :
return a + b + c + d
Values 10, 20, 30, 40 will assigned
in a,b,c and d respectively.
30

40
10

20

S = add ( 10 , 20 , 30 , 40 )
POSITIONAL ARGUMENTS
Positional arguments are
def add ( a , b , c , d ) : mandatory and take values
return a + b + c + d orderly. That is why we called
it as Required arguments.


add ( 10 , 20 , 30 , 40 )
Both the Arguments and
Parameters should be
matched.

DON ’ T Do
10

20

Missing c & d
add (10 , 20 )
TypeError: add() missing 2 required
Positional arguments: 'c' and 'd‘
POSITIONAL ARGUMENTS
def add ( a , b , c , d ) : Positional arguments are
mandatory and take values orderly.
return a + b + c + d That is why we called it as Required
arguments. Both the Arguments


and Parameters should be matched.

add ( 10 , 20 , 30 , 40 )
DON ’ T Do

add (10 , 20, 30, 40, 50 )


TypeError: add() takes 4
positional arguments but 5
were given…..
Example Program.
Interest= Principal Amount * Rate * Years.

def interest (prin, rate, years) :


prin = 1000, Rate = 0.1
return prin*rate*years Years = 3
1000*0.1*3 = 300.0
Parameter Values
prin = 1000, Rate = 0.1
Years = 3

i= interest(1000, 0.1,
3) What will be the result ?

def interest (prin, rate, years) :
return prin*rate*years
S t a r t e x e c u ti o n f r o m b e l o w.

p = int(input("Enter Principal amoumt "))


r = float(input("Enter rate of interest "))
y = int(input("Enter No of years "))
i = interest(p,r,y)
print("Interest = ", i)

Output
Enter Principal amoumt 1000
Enter rate of interest 0.1
Enter No of years 3
Interest = 300.0
 
Consider a situation, One asks for the sum of
2 Nos and the other asks sum of 3 numbers.
def a:
return a+b
I want sum of
3 Nos(10,20
I want sum of 2
and 30)
Nos(10 and 20)
What a dilemma !
add () has only 2
arguments.
How I satisfies
both of them
default (Optional ) arguments.
 
def a:
return a+b I allows 2
entry only.
What a dilemma !
add
  () has only 2
My statement
arguments. is correct.
‘a’How
becomes 10 and ‘b’ becomes 20.
I satisfies
both of them
= add(10,20)
10 20
= add(10,20) 10 20 30 
s2 = add(10,20,30)
 

Click Me Click Me
def a: 𝐜=𝟎
   
o f
u m I want
s sum o
ant d 20
I w 0 an
1
return a+b+c 10,20
and 30
f

When we omit some


arguments, it uses the
default values.

30
10

20
10

20

= add(10,20)  s2 = add(10,20,30) 
 

Click Me Click Me

Arguments which has default values are


called default arguments.
def add (a, b, c=0) :
return a + b + c

v1 = int(input("Enter 1st No ")) Start from here.

v2 = int(input("Enter 2nd No "))


v3 = int(input("Enter 3rd No "))

Since we omit 3rd argument, c becomes 0


s1 = add(v1, v2)
s2 = add(v1, v2, v3)

print("Sum of 2 Nos = ", s1)


print("Sum of 3 Nos = ", s2)

Output
Enter 1st No 10
Enter 2nd No 20
Enter 3rd No 30
Sum of 2 Nos = 30
Sum of 3 Nos = 60
If the function is called without arguments,
that argument gets its default value.
def add(a=0, b=0, c=0, d=0, e=0) :
return a+b+c+d+e
What are the
result ?
 
= add( ) Click Me 
Two
One
Three
Four
values
value
values
values
given,
given,
given,
given,
which
that
 
= add(1) Click Me  All
No arguments
arguments are given.
given.
will
which be are
assigned
assigned
in ‘a’.
‘a’
in
 
= add(1,2) Click Me  Which are assigned in
a,b
Remaining
andand
a,b,c,d,e b. c.
Remaining
Remaining
b,c,d,e
becomes 0
a,b,c,d,e respectively.
4 = add(1,2,3) Click Me 
  c,d,e
d,ebecomes
becomes
becomes 0 0.0
Answer is
Answer is 015
 
= add(1,2,3,4) Click Me  Answer
Answerisis10 16
3
 
= add(1,2,3,4,5) Click Me 
 
def p: c = 1
return a*b*c
If the function
What is called
do you without
argument, that argument gets its default
When you callthink ?. Is it
product(5,6,7), correct
(no missing
value.
arguments) Parameters
in all a,b and c catch
situations.
When you call product(5,6) 3rd
our values 5,6,7. (a=5, b=6, c=7)
  parameter ‘c’ gets 0.
=Answer
add( 5, 6is) 5*6*7
Answer is 5*6*0 = 0?
What is = 210
Result 
s2 = add(5,6,7) What is Result ? 
Can you correct it? 
Argument values get assigned in the parameters in the
order of they placed is the Drawback of positional
arguments.
 
def greet: Parameter Values.
name
print(“Hai = 16, “,
”, name, rollyou
= ‘Aswin’
are”, age, “years old”)
Output : Hai 16, you are ‘Aswin’ years old.

Aswi 18)
greet (‘Aswin’, 1
n 8
What happened when I call
greet(16, ‘Aswin’)
Click Me 
ld. Ia
s o m
ear e ? Aswin 16 Do As
6 y m es wi
1
n ea ns stand up. he n R
i
sw m
A he m oll
m ea N
I a oes nm o1
D e? 6.

Keyword Arguments
ue I am Aswin,
a l
- v Roll no 16.
e y ir
K pa

Aswin,
Roll no 16,
stand up.

Giving arguments in the form of key-value


pairs are called keyword arguments.
def greet (name, roll ):
print (“Hai”,name,“Your Roll No is”, roll)
f u n c t i o n.
o f c a l l i ng
greet r e(16,
n t w a ys
‘Aswin’) produce different
D i ffe
output because the function is called in the style of
s w i n ’ ) C l i ck M e 
positional argument.
o l l = 1166, na m e
Argument
nam e=‘‘A values takes orderly.
= A s w in ’
gre e t ( r ro ll =
Name = 16 & roll
l l=1 =
1
6 6 ‘Aswin’
) C l i ck M e 
wiinn’’, ro ro ll =
t ( n a m n e
a m= ‘
e=A ‘Assw
greeOutput : Hai 16, your Roll No is Aswin.
i n ’ , 1 6 ) C l i ck M e
greet (‘‘A Assw w in ’ 1 6

s ww iinn’ ’) Click Me 
greet (16, ‘
1 6 A‘ A s

Which makes
different output?
def greet (name, roll ):
print (“Hai“,name,“Your Roll No is”, roll)

Name and name are different.


greet (roll = 16, name = “Aswin”)
TypeError: greet() got an
unexpected keyword argument
greet (roll=16,
roll=16 name=‘Aswin’)
name=‘Aswin’'Name'Show Execution ? 

greet name=‘Aswin’
(name=‘Aswin’, roll=16
roll=16) Show Execution ? 
greet (Name=‘Aswin’, roll=16) What’s wrong ? 
SCOPE OF VARIABLE
OR LEGB RULE
Scope is the area,
where data is active
and accessible.

x = 10 y = 20 The repeating variable

û
(y=100) will hides the
previous (y=20).

Variable Values
ûVariableScope
Values
B
Scope a =A5 ûx = 10
a,b = 5, 8
p,q = 15,b =25
8 y = 20
What are the values
x = 10of x, y, p =y=100
15
p and q ?  What are the values of x, y,
y = 100 q = 25
a and b ? 
NameSpace
Scope is the area, where
objects is active
and accessible.
In Python, everything
like literals, variables,
functions, classes all are
objects. . Establishing
name-object relationship is
called namespace.
4 s in Built-In : It is top level scope.
Objects in this scope are visible
pe n
c o h o from everywhere.
s yt
P B Global : entire program can access
it, unless duplicated.

G Enclosing scope : It is
the scope of nested
Data of outer
scope can be E functions.
accessed B G E Local Scope : It is
from inner the scope exists inside
scope. L a function.

Internal elements
Nothing goes out
should not be accessed
like a black Hole.
from the outside.
Data from outer scope can be accessed from inner scope.
Data from inner scope can’t be accessed from outer scope.

A = 10
Clicking on each
B = 20 Scope to see the data
C =Objects
30 visible in that Scope
Global Scope :
Built-In Scope :

Only the
Only the Objects
Enclosing

definedDAll
defined =in
40the

objects
in Built
All objects
defined
Built-in in defined in the
-and the
inClick 'BGE'
scope scope‘LEGB'
Mescope
global are can bescope can be
are accessed
available.
Local scope accessed from Local
from
available.
A = 10 and B = 20Scope. A=10, B=20, C=30
Enclosing
A =Me
A=10,
Click 10 
B=20 and C=30 and D = 40

Click Me 
Click Me 
Variables, declared
outside of functions
are called Global
variable

Global and local scope

Variables that
declare within a
function are called
Local Variable
Global vs local Variables.
Local Variables Global Variables
It is declared inside a function. It is declared outside the function.
If it is not initialized, a garbage value is If it is not initialized zero is stored as
stored default.
It is created when the function starts It is created before the program's global
execution and lost when the functions execution starts and lost when the
terminate. program terminates.
Data sharing is not possible as data of Data sharing is possible as multiple
the local variable can be accessed by functions can access the same global
only one function. variable.
When the value of the local variable is When the value of the global variable is
modified in one function, the changes modified in one function changes are
are not visible in another function. visible in the rest of the program.
Local variables can be accessed inside a You can access global variables by any
function in which they are declared. statement in the program.
variables a, b are local
def fun1() :
and limited its access
a, b = 10, 15 within this function.
print (“A”,a,“B=”, b,“X = ”, x, “Y = ”, y)
a and b variables
are declared in fun1
x, y are global and
() and cannot
its accessbe accessed
is everywhare.
because they are local
x, y = 1, 2
print (“X = ”, x, “Y = ”, y)
What is Wrong ? 
print (a, b)
Global Vs Local Memory

def fun1() : Creating a localized


10 3Run Me  variable ‘a’ in fun1() and
a = 10
hide global variable a = 1.
print ("In fun1 a = ", a) Output: In fun1 a = 10 Defferent ID

fun2() 4Run Me 
Creating global
def fun2() : variable ‘a’ at
print ("In fun2 a = ", a) Output: In fun2 a = 1 Memory Id
Start from below 1418093744

a =11 1Run Me 
print ("In main a = ", a) Output: In main a = 1
fun1() 2Run Me 
print ("In main a = ", a) Output: In main a = 1
def fun1() :
a = 10
will print? 
print ("In fun1 ", a)from What
fun2 ()ais=called fun1.Since 'a = 10' is
fun2() localized in fun1 (), fun2 () has no right to
access it. So fun2 () takes the global value of
'a'. So print the value 1.
def fun2() :
print Since
("In fun1
fun2()ais =called
", a)fromWhat
mainwill
(), print?
the 
statement 'a = 10' invalidates the statement 'a
a=1 = 1'. So it will print the value 10.

print ("In main a = ", a)


fun1()
print ("In main a = ", a)
OUTPUT
In main a = 1
In fun1 a = 10
In fun2 a = 1
In main a = 1
‘GLOBAL’
KEYWORD

The 'global' keyword is used to


create a global variable in a
local context and allows
changes to the variable.
Within a function, the value of a global variable
can be read but you can't change.

def ABC() : a = 10
print(“In ABC a = “, a) Global
variable a=10 Within a function, the
value of a global variable
a = 10 Global variable a=10 def ABC(): c a n' t b e c h a n ge .
print (“In Main a = “, a) a=a+5
ABC()

Within a function, the value of a
 print(“In ABC a = “, a)

global variable c a n b e r e a d . print (“In Main a = “, a)


ABC()
The 'global' keyword is used to create a global variable in a
local context and allows for changes in them.

def ABC() : Creating a local variable ‘a=10’ def ABC() : Argue that ‘a' is a global
variable and add value 5 to it.
a = 10 in ABC() and hide global
global a it will be reflected in "main
a = a + 5 variable a = 10. ()" as well
print("In ABC a = ", a) a=a+5
The above local variable print("In ABC a = ", a)
a = 10 a = 15 is not accessed here
print ("In Main a = ", a) a = 10
ABC() print ("In Main a = ", a)
print ("In Main a = ", a) ABC()
OUTPUT:
print ("In Main a = ", a)
OUTPUT:
In Main a = 10
In Main a = 10
In ABC a = 15
In ABC a = 15
In Main a = 10
In Main a = 15
Docstring or Documentation string is a string that
provide a help topic (what the function do).
 
def area: What will area() do ?
return 3.14 * r * r
Ask help() of area

= int ( input (“Enter radius


” ))
a=
print (“Area of circle is ”, a )
docstring
def area ( r ) :
''' Calculate area when giving radius.’’’
return a+b
Documentation String

Docstring provides a help topic when calling help.


>>> help(area)
Help on function area in module __main__:
area(r)
Calculate area when giving radius.
>>> def area ( r ) :
''' Calculate area when giving radius.'''
return a+b
Docstring provides a help
>>> help (area) topic when calling help.
Help on function area in module __main__:

area(r)
Calculate area when giving radius.
>>>
EXERCISES
1. Write function to convert Fahrenheit temperature into Celsius using formula C = (F-32)/1.8.
2. Covert length in feet and inches to centimeters. 1 inch = 2.5 cm & 1 feet = 12 inches.
3. Calculate the sum of elements in a list.
4. Find out the greatest value in a list.
5. Calculate factorial of given no using for loop. “ANIL “ + “KUMAR” = “ANIL KUMAR”
String : “10” + “20” = “1020”
def Celsius ( f ): Integer Operation : 10 + 20 = 30

Val = 45
73 int () convert a Number or
c = (f-32)/1.8 string into an integer.
Syntax is int (No, Base = 10)
return c Inputing digits as string
int ( “123” ) = 123
a = input("Enter Fahrenheit ")
int (“1010”, 2) = 10
Covert into integer
a = int(a) Int ( “11”,16 ) = 17
int ( “12”, 8 ) = 10
c = Celsius(a)
Int ( 3.14 ) = 3
print ("Celsius Temperature = ", c)
EXERCISES 2. Covert length in feet and inches to
centimeters. 1 inch = 2.5 cm & 1 feet = 12 inches.
F = 5 and I = 4
def Cal_cm ( F , I ): How many centimeters in
5 feet 4 inches.
return ( (F*12) + I) *2.5
1 Feet = 12 inches
Val = 45
73 5 feet = 5 *12 inches
= 60 inches
Total inches = ( 5 * 12 ) + 4
f = int ( input("Enter Feet ") ) 60 + 4 = 64
1 inch = 2.5 cm
i = int ( input("Enter Inch ")) 64 inches = 64 * 2.5
= 160 Cm
print("Total CM = ", Cal_cm (f,i) )
OUTPUT : Enter Feet 5
Enter Inch 4
Total CM = 160
EXERCISES 3. Calculate the sum of elements in a list.
def sum(List) : “for” loop fetch each item in the list.
sum = 0 List = [ 5, 10, 15, 20, 25 ]
Index 0 1 2 3 4

for val in List:


sum += val Val = 45
73

return sum Step 1: val = 5 sum = 5


eval() evaluates the string as a Python Step 2: val = 10 sum = 15
expression. Input String [5,10,15,20,25],
evaluated as a list Step 3: val = 15 sum = 30
Step 4: val = 20 sum = 50
a = eval(input("Enter a List ")) Step 5: val = 25 sum = 75
print("The Sum of List is ", sum ( a ) )
OUTPUT : Enter a List of Nos [5,10,15,20,25]
The Sum of List is 75
EXERCISES 4. Find out the greatest value in a list.
slice is an act to getting some elements from a collection of elements. 
Syntax is list [start : stop : steps] Default value of start is 0,stop is last
index of list and step is 1
Index 0 1 2 3 4 5
def greatest ( List ) : List = [65, -38, 56, -92, 73, 45 ]
max = List[0]
Passing [65, -38, 56, -92, 73,45 ]

Val = 45
73
List [0:3] = [65, -38, 56]
for val in List[1:] : List [1:4] = [-38, 56, -92]
List[::] = [65, -38, 56, -92, 73, 45]
List [::2] = [65, 56, 73]
if val > max : max = val List [1: ] = [ -38,56,-92, 73,45 ]
return max
List[1: : ] = [-38, 56, -92, 73,45 ]

a = eval(input("Enter a list of Nos ")) Assume


m = greatest(a) List = [65, -38, 56, -92, 73,45 ]
print ("The Greatest Value is ", m)
EXERCISES 4. Find out the greatest value in a list.
slice is an act to getting some elements from a collection of elements. 
Syntax is list [start : stop : steps] Default value of start is 0,stop is last
index of list and step is 1. Index 0 1 2 3 4 5
List = [65, -38, 56, -92, 73,45 ]
def greatest ( List ) :
al max = List[0]
Passing [65, -38, 56, -92, 73,45 ]

In i ti n List[1: ] = [-38, 56,-92, 73, 45]


ptio 5 Val = 45
73
m =6
s u
as ax for val in List[1:] :
m if val > max : max = val Step 1: val = -38 max = 65
return max Step 2: val = 56 max = 65
Step 3: val = -92 sum = 60
a = eval(input("Enter a list of Nos ")) Step 4: val = 73 sum = 73
m = greatest(a) Step 5: val = 45 sum = 73
print ("The Greatest Value is ", m)
“for” loop fetch each item in the List [1:]=[-38,56,-92,73, 45
EXERCISES 4. Find out the greatest value in a list.
slice is an act to getting some elements from a collection of elements. 
Syntax is list [start : stop : steps] Default value of start is 0,stop is last
index of list and step is 1. Index 0 1 2 3 4 5
List = [65, -38, 56, -92, 73,45 ]
def greatest ( List ) :
al max = List[0] List[1: : ] = [-38, 56, -92, 73,45 ]
ti
Ini tion65 Val = 45
73
p =
m
su ax for val in List[1:] :
as m
[65, -38, 56, -92, 73,45 ]

if val > max : max = val


Step 1: val = -38 max = 65
return max Step 2: val = 56 max = 65
Step 3: val = -92 sum = 60
a = eval(input("Enter a list of Nos "))
Step 4: val = 73 sum = 73
m = greatest(a)
print ("The Greatest Value is ", m) Step 5: val = 45 sum = 73
OUTPUT : Enter a List of Nos [65, -38, 56, -92, 73,45]
The Greatest Value is 73
EXERCISES 5. Calculate factorial of given no using for loop.
Factorial of n (n!) is the product of all numbers <= n.
5! = 1 x 2 x 3 x 4 x 5 = 120.

def fact(n) : n=5 range() function create a sequence


f=1 of values from start to stop-1.
Val =Range(start,
73
45 stop, step)
for x in range(1,n+1): Start and Step are optional
Passing 5

f *= x range (1, 5 ) = 1, 2, 3, 4
return f range (5, 10 ) = 5, 6, 7, 8, 9
Assume that range ( 1, 10, 2 ) = 1,3,5,7,9
input a = 5
a = int(input("Enter a No ")) range ( 0, 20, 5 ) = 0, 5, 10, 15
f = fact(a) range (5, 0, -1) = 5, 4, 3, 2, 1
print("The Factorial of ", a, " is ", f)
range ( 5 ) = 0, 1, 2, 3, 4
EXERCISES 5. Calculate factorial of given no using for loop.
Factorial of n (n!) is the product of all numbers <= n.
5! = 1 x 2 x 3 x 4 x 5 = 120.
def fact(n) : Assume that
f=1 n=5 input a = 5
Passing 5

Assuming n = 5
for x in range(2,n+1):
Val = 45
73
range (1, 6 ) = 1, 2, 3, 4, 5
f *= x
Muitiply value of At end of Step 1 : x = 2 f = 2
return f x with existing
value of f Step 2 : x = 3 f = 6
Step 3 : x = 4 f = 24
a = int(input("Enter a No "))
Step 4 : x = 5 f = 120
f = fact(a)
OUTPUT
print("The Factorial of ", a, " is ", f) Enter a No 5
The Factorial of 5 is 120
Let me know your thoughts on
improving future presentations.
NAMASTHE

All images used in these presentations


have been downloaded from the net.
I am indebted to them.

You might also like