FUNCTION IN PYTHON - PowerPoint PPT Presentation

About This Presentation
Title:

FUNCTION IN PYTHON

Description:

WORKING WITH FUNCTION. CLASS 12 COMPUTER SCIENCE – PowerPoint PPT presentation

Number of Views:3629

less

Transcript and Presenter's Notes

Title: FUNCTION IN PYTHON


1
CHAPTER 3
SELF-STUDY PRESENTATION THROUGH ANIMATIONS.
Not for commercial use.
2
Dictionary meaning of Function ?
3
What is FUNCTION ?
FUNCTIONS
FUNCTIONS
In dictionary, FUNCTION means DEED ( ??????????
) FUNCTION ????????? ?????? ????? ?????
?????? ???????? ???????? ???????
In programming Language, A function is a block of
statements to perform an action.
4
Why Function is needed ?
5
  • It is difficult to write much more statements as
    a single program or unit.
  • And also difficult to find the content.

Big matter on a tiny page. Horrible ! What are
my Duties ?
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. ) to cherish and follow the noble
ideals which inspired our national strugg ..
6
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 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.
Easy to read.
7
How I wrote a Paragraph ?.
REMEMBER 3 THINGS. TITLE OF PARAGRAPH
FULL COLON HANGING ( INDENT ) LINES
1
2
3
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 happiness and prosperity
alone lies my happiness.
Indentation Space before statements
-----
INDENT ???????????? ??????? ?? ?? ???????
??????? ???????
8
What is the link between PARAGRAPH and PYTHON
PROGRAM.
def greatest ( List ) max List0 for
val in List1 if val gt 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.
9
What does the function do?
10
FUNCTION TAKES DATA, AND WILL PRODUCE DESIRED
OUTPUT
What does the function do?
DATA
OUTPUT
11
Assume any value in x and calculate polynomial 2x2
?????????????????? ?????? ?????? ????????
?????????? ???????? ??????????????????
????????????
?? ?? 2x2
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
?
?? ?? 2 Click here to watch ?
FUNCTION TAKES DATA
?? ?? 8 Click here to watch ?
?? ?? 18 Click here to watch ?
PRODUCE OUTPUT
12
Different type of functions. 1) Built in
Functions. 2) Modules. 3) User - defined
functions.
13
  • Built in Functions.
  • The predefined functions are called
  • built-in functions. It can be execute
  • by a simple function call statement.
  • min() Return smallest.
  • max() Return largest.
  • pow() Returns xy.
  • len() Returns length.
  • int() Returns integer.

14
Python 3.7.4 (tags/v3.7.4e09359112e, Jul 8
2019, 192922) MSC v.1916 32 bit (Intel) on
win32 Type "help", "copyright", "credits" or
"license()" for more information. gtgtgt
min(10,-20) -20 gtgtgt max(-25,80) 80 gtgtgt
pow(2,3) 8 gtgtgt len("ANIL") 4 gtgtgt int(3.14) 3
min() Return smallest value. max() Return
largest. pow() Returns xy. len() Returns
length. int() Returns integer.
The predefined functions are called built-in
functions. It can be execute by a simple function
call statement.
15
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.
16
gtgtgt import math gtgtgt math.pi 3.141592653589793 gtgtgt
math.sqrt(25) 5.0 gtgtgt math.floor(3.14) 3 gtgtgt
math.ceil(3.14) 4 gtgtgt import random gtgtgt
random.randomint(10,20) 17
After importing the modules, use the
function.
math.floor() - Drop down to the
nearest integer. math.ceil() - Grow up to the
nearest integer.
A module contains many functions and other
objects. After importing the modules, use the
function.
17

How to define a function?
18
Anatomy of a function.
def ??unction name ( arguments ) statement
1 statement 2
Keyword def is used to define a function. The
very first line is 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.
19
What is a function, what does a function do and
why do we use them? A function is a structuring
element in programming languages to group a set
of statements so they can be utilized more than
once in a program. (https//www.python-course.eu/
python3_functions.php) We use functions in order
to allow for better comprehension and efficiency
of the code. If you have code that is written all
over the place with little structure and flow to
it as happens without functions, it can become
very difficult to read, and code will be read far
more times than it will be written. Efficiency is
another primary concern when writing code
effectively, you rarely want to write the same
thing twice, so we create functions that
essentially perform the role of the copy and
paste buttons. As a matter of fact, copy and
paste are functions of the programs you
use. Anatomy of a Python function To initialize a
Python function you must preface it with the
keyword def. This stands for define. You are
going to define the function. Following the def
keyword is a space and the actual function name.
Unlike other programming languages, in Python, a
functions name does not use camel case, but
convention dictates that a combination of
lowercase and underscores are used. A good post
about naming conventions in Python can be found
here and an in-depth introduction to Python
styling can be found here, if interested. A
function takes parameter(s)/argument(s) which are
like car parts going through an assembly line and
the function (the workers) puts them together for
the desired output (a fully assembled car). These
parameters must go in parenthesis with no space
in between the function name and themselves. Not
every function will have parameter(s). Following
the parameters is one singular colon followed by
the body of the function. In the body is where
the magic happens, this is where the car is put
together. Typically a function outputs something,
but this is not always the case as a function can
also be used simply to change an existing
variable. The function of a function is not
always the same. Finally, a function would be
worthless without a call. You are saying, okay
function, I taught you what to do now come do it.
Click this link to see an example of a function
call. A function call always needs to have
parenthesis after it, whether or not the function
has parameters. This is an example of a complete
function in Python. If any part of this lesson
didnt make sense to you and you need further
explanation, please dont hesitate to contact us
at TheValleyCodes Facebook page. Thanks for
reading, and be sure to subscribe to our
newsletter for weekly programming goodies. We
promise not to sell your information for anything
less than six figures Dont act like you
wouldnt.
Function header Has these 4 elements.
( )
def function Name ( ) Statement
1 Statement 2
End with a colon ()
4
2
1
A pair of Brackets ()
3
Function Name.
It begins with the keyword def
--------
Function Body or function suit.
Space before statements (Indentation)
20
Some examples
def pie ( ) return 22 / 7 def root2 ( )
return 1.4142 def pledge ( ) print (
India is my country)
Pledge ( ) will print few lines of National
Pledge.
Pie ( ) will return result of 22 / 7 3.14.
???????? ???????? ?????? ( ) ???? Click Me ?
???????? ???????? ???????????? ( ) ???? Click Me
?
21
Calling function?
22
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.
23
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.
?
24
Function call is a request to perform the action
defined by the function.
def ?????? ( ) return 22/7 ?? Pie(
) print (Value of Pie is , p)
Goto the function definition and return back with
the result.
Start execution from below.
Function call statement
25
Function call is a request to perform the action
defined by the function.
gtgtgt def pie ( ) return 22 / 7 gtgtgt def
root2 ( ) return 1.4142 gtgtgt def pledge (
) print ( "India is my country") gtgtgt
pledge() gtgtgt India is my country gtgtgt b
root2() gtgtgt print ( b ) gtgtgt 1.4142 gtgtgt a
pie() gtgtgt print ( a ) gtgtgt 3.142857142857143
Definitions
Function Call
Function
Calling Functions.
Calling
Function Call
Function Call
26
def A ( ) print( Up above the world
so high, ) def B ( ) print
(TWINKLE, twinkle, little star,) def C ( )
print ( Like a diamond in the sky.
) def D ( ) print ( How I wonder
what you are! )
???????????? ???????? Click Me ?
I wrote the lyrics of a song into 4 functions.
In what order I should call (invoke) these
functions.
?
27
gtgtgt def A ( ) print("Up above the world so
high,") C() gtgtgt def B ( ) print ("TWINKLE,
twinkle, little star,") D() gtgtgt def C ( )
print ( "Like a diamond in the sky." ) gtgtgt def
D ( ) print ( "How I wonder what you are! " )
A() gtgtgt B()
Calling the Function C()
Calling the Function D()
OUTPUT gtgtgt TWINKLE, twinkle, little star, How I
wonder what you are! Up above the world so
high, Like a diamond in the sky. gtgtgt
Calling the Function A()
28
OUT OF SYLLABUS.
Who made this parody and what it means ?
29
Arguments Parameters
30
Imagines that functions are processing machines.
What does the function do?
Input data
  1. Accepts Data
  2. Carried out desired process.
  3. Produce Output

Output
Arguments act as an input to the function, to
carries out the specified task.
31
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.
Returns output
Function Definition
32
Assume any value in x and calculate 2x2
X receives a value, and f() returns 2 x2
?? ?? 2x2
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
?????????????????? ?????? ?????? ????????
?????????? ???????? ??????????????????
????????????
?
?? ?? 2 Click here to watch ?
?? ?? 8 Click here to watch ?
?? ?? 18 Click here to watch ?
33
Assume any value in x and calculate 2x2
def ?? ?? return 2 ?? ?? ?? int (
input ( Enter No ) ) a ?? ?? print (Answer
is , a )
What is the answer if x 5 ?
Start execution from below.
Click Me ?
34
def ??(??) return 2 ?? ?? ?? int (
input ( Enter No ) ) a ??(??) print (Answer
is , a )
Input the Value 5.
OUTPUT gtgtgt Answer is 50 gtgtgt
Calling the Function F(5) by passing the value
5.
35
Difference between Arguments and Parameters
def add ( a , b , c , d ) print (
Sum is , abcd ) add ( 10 , 20, 30, 40 )
a10
b20
c30
d40
Parameter are variables, which receives the
values of passing arguments.
Arguments are the actual values passed to the
function when it is called
30
40
10
20
Arguments act as an input to the function, to
carry out the specified task.
36
ARGUMENTS OR PARAMETERS
def area ( r ) return 3.14 r r
a area ( 10 ) print ( Area of the
circle is, a)
What is this ?
This is parameter
Parameter are variables, receiving passing values
within the function definition.
Arguments are the actual values passed to the
function when it is called
What is this ?
This is argument
37
ARGUMENTS CAN BE EITHER LITERALS, VARIABLES OR
EXPRESSIONS.
def add ( a,b,c) return abc X 20 add
(10, X, (310) )
Literal 10, value of variable x and the end
result of expression (310) i.e. 30 will be
passed as arguments.
Start execution from here.
Expression
Variable
Literal
38
Return nothing. VOID FUNCTIONS.
39
NO RETURN VOID FUNCTIONS functions which will
not return values are called void functions.
def add ( a, b , c , d ) print (
Sum is , a b c d ) s add(10, 20,
30, 40) avg s/4
Example of Void Functions.
No Return
Missing Return statement here
Start execution from below.
How can calculate average if add () will not
return any value.
40
def add ( a, b , c , d ) print (
Sum is , a b c d ) s add(10, 20, 30,
40) avg s/4
Print the sum 100. No return or return None.
?
DON T Do
OUTPUT gtgtgt Answer is 50 gtgtgt
Causing the error TypeError unsupported operand
type(s) for / 'NoneType' and 'int'
?
41
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.
42
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.

43
RETURN ONE VALUE
def add ( a , b , c , d ) return
abcd 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.
Return 100
Return statement returns the result.
Start execution from below.
10
20
30
40
44
Return statement, stop function execution and
come back. It also returns the result if we
needed. By default it will return a None value.
45
ALL IN ONE
def add ( a , b ) return a b s
add(10,20 ) s add ( 1.5, 2.5 ) s add(anil,
kumar ) s add( 10,20, 5,15 )
Python is a dynamically-typed language. It
doesn't know about the type of the variable until
the code runs.
ALL IN ONE
10 20 30
1.5 2.5 4.0
anil kumar anilkumar
10,20,5,15
46
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.
47
RETURN MULTIPLE VALUES
def Sum_Avg ( a , b , c , d )
tabcd return t, t/4 sum, avg
Sum_Avg (10, 20, 30, 40) print (Sum , sum ,
Avg , avg)
t100
Python can return multiple values from a function.
100
25
Passing 10,20,30,40
Here I got sum and average.
48
In Python, multiple assignment is posible like
this.
Name Anil Roll 15 Class XII
x , y , z 10 , 20 , 30
30
20
A 0 B 0 C 0
10
X, Y and Z have gets values ??10, 20 and 30
name, roll, class Anil, 15, XII What will
hapened ? ?
a b c 0 What will hapened ? ?
49
Python 3.7.4 (tags/v3.7.4e09359112e, Jul 8
2019, 192922) MSC v.1916 32 bit (Intel) on
win32 Type "help", "copyright", "credits" or
"license()" for more information. gtgtgt x , y ,
z 10 , 20 , 30 gtgtgt name, roll, Class
Anil, 15, XII gtgtgt a b c 0 gtgtgt print
(x, y, z ) gtgtgt 10 20 30 gtgtgt print (name, roll,
Class) gtgtgt Anil 15, XII gtgtgt print(a,b,c) gtgtgt 0
0 0
Assigning multiple values ??into multiple
variables using a single statement is called
'multiple assignment'
50
Different types of arguments.
There are 3 (4) types of arguments. Required
arguments or Positional arguments Default
arguments Keyword arguments and Varying
arguments.
1
2
3
51
Required (Positional) arguments. These are
mandatory arguments and take orderly. Default
arguments Provides default value to an argument.
It will be used when we omit value during
function call. Keyword arguments Keyword
arguments are same as default arguments but it
allows you to give name-value pairs instead of
just the value.
1
2
3
52
POSITIONAL ARGUMENTS
def add ( a , b , c , d ) return a
b c d S add ( 10 , 20 , 30 , 40 )
Positional arguments are mandatory and take
values orderly. That is why we called it Required
arguments. Both the Arguments and Parameters
should be matched.
Values 10, 20, 30, 40 will assigned in a,b,c and
d respectively.
30
40
10
20
53
POSITIONAL ARGUMENTS
def add ( a , b , c , d ) return a b c
d add ( 10 , 20 , 30 , 40 ) add (10 , 20 )
Positional arguments are mandatory and take
values orderly. That is why we called it as
Required arguments. Both the Arguments and
Parameters should be matched.
?
DON T Do
Missing c d
10
20
TypeError add() missing 2 required Positional
arguments 'c' and 'd
54
POSITIONAL ARGUMENTS
def add ( a , b , c , d ) return a b c
d add ( 10 , 20 , 30 , 40 ) add (10 , 20,
30, 40, 50 )
Positional arguments are mandatory and take
values orderly. That is why we called it as
Required arguments. Both the Arguments and
Parameters should be matched.
?
DON T Do
TypeError add() takes 4 positional arguments but
5 were given..
55
Example Program. Interest Principal Amount
Rate Years.
def interest (prin, rate, years) return
prinrateyears
prin 1000, Rate 0.1 Years 3 10000.13
300.0
Parameter Values prin 1000, Rate 0.1 Years 3
i interest(1000, 0.1, 3) What will be the
result ? ?
56
def interest (prin, rate, years) return
prinrateyears 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)
Start execution from below.
Output Enter Principal amoumt 1000 Enter rate of
interest 0.1 Enter No of years 3 Interest 300.0
57
(No Transcript)
58
Consider a situation, One asks for the sum of 2
Nos and the other asks sum of 3 numbers.
def add (a,b ) return ab
I want sum of 3 Nos(10,20 and 30)
I want sum of 2 Nos(10 and 20)
What a dilemma ! add () has only 2 arguments. How
I satisfies both of them
59
default (Optional ) arguments.
def add (a,b ) return ab
I allows 2 entry only.
What a dilemma ! add () has only 2 arguments. How
I satisfies both of them
My statement is correct. a becomes 10 and b
becomes 20. ??1 add(10,20)
s2 add(10,20,30) ? Click Me
??1 add(10,20) ? Click Me
60
def add (a,b, ???? ) return abc
????
I want sum of 10 and 20
I want sum of 10,20 and 30
When we omit some arguments, it uses the default
values.
?
10
20
s2 add(10,20,30) ? Click Me
??1 add(10,20) ? Click Me
Arguments which has default values are called
default arguments.
61
def add (a, b, c0) return a b c v1
int(input("Enter 1st No ")) v2 int(input("Enter
2nd No ")) v3 int(input("Enter 3rd No ")) s1
add(v1, v2) s2 add(v1, v2, v3) print("Sum of 2
Nos ", s1) print("Sum of 3 Nos ", s2)
Start from here.
Since we omit 3rd argument, c becomes 0
Output Enter 1st No 10 Enter 2nd No 20 Enter 3rd
No 30 Sum of 2 Nos 30 Sum of 3 Nos 60
62
If the function is called without arguments, that
argument gets its default value.
def add(a0, b0, c0, d0, e0) return
abcde
What are the result ?
??1 add( ) Click Me ?
No arguments given. a,b,c,d,e becomes 0 Answer is
0
One value given, that will be assigned in a.
Remaining b,c,d,e becomes 0 Answer is 1
Two values given, which will be assigned in a
and b. Remaining c,d,e becomes 0 Answer is 3
Three values given, which are assigned in a,b and
c. Remaining d,e becomes 0. Answer is 6
Four values given, which are assigned in a,b and
c. Remaining d,e becomes 0. Answer is 10
All arguments are given. Which are assigned in
a,b,c,d,e respectively. Answer is 15
???? add(1) Click Me ?
???? add(1,2) Click Me ?
??4 add(1,2,3) Click Me ?
???? add(1,2,3,4) Click Me ?
???? add(1,2,3,4,5) Click Me ?
63
def p???????????? (a,b, ???? ) return
abc
c 1
What do you think ?. Is it correct in all
situations.
If the function is called without argument, that
argument gets its default value. When you call
product(5,6) 3rd parameter c gets 0. Answer is
560 0
When you call product(5,6,7), (no missing
arguments) Parameters a,b and c catch our values
5,6,7. (a5, b6, c7) Answer is 567 210
??1 add( 5, 6 ) What is Result ? ?
s2 add(5,6,7) What is Result ? ?
Can you correct it? ?
64
Argument values get assigned in the parameters in
the order of they placed is the Drawback of
positional arguments.
def greet (????????,?????? ) print(Hai ,
name, , you are, age, years old) greet
(Aswin, 18)
Parameter Values. name 16, roll
Aswin Output Hai 16, you are Aswin years
old.
Aswin
18
What happened when I call greet(16, Aswin)
Click Me ?
65
Aswin 16 stand up.
I am Aswin 16 years old. Does he means me ?
I am Aswin Roll No 16. Does he mean me?
Keyword Arguments
66
I am Aswin, Roll no 16.
Key-value pair
Aswin, Roll no 16, stand up.
Giving arguments in the form of key-value pairs
are called keyword arguments.
67
def greet (name, roll ) print
(Hai,name,Your Roll No is, roll)
greet (16, Aswin) produce different output
because the function is called in the style of
positional argument. Argument values takes
orderly. Name 16 roll Aswin Output Hai
16, your Roll No is Aswin.
Different ways of calling function.
greet (roll16, nameAswin) Click Me ?
nameAswin
roll16
roll16
greet (nameAswin, roll16) Click Me ?
nameAswin
greet (Aswin, 16) Click Me ?
greet (16, Aswin) Click Me ?
Which makes different output?
68
def greet (name, roll ) print
(Hai,name,Your Roll No is, roll) greet (roll
16, name Aswin)
greet (roll16, nameAswin) Show Execution ? ?
roll16
nameAswin
greet (nameAswin, roll16) Show Execution ? ?
roll16
nameAswin
greet (NameAswin, roll16) Whats wrong ? ?
69
(No Transcript)
70
SCOPE OF VARIABLE OR LEGB RULE
71
Scope is the area, where data is active and
accessible.
x 10 y 20
The repeating variable (y100) will hides the
previous (y20).
û
û
Variable Values x 10 y 20 p 15 q 25
Variable Values a 5 b 8 x 10 y 100
Scope A p,q 15, 25 What are the values of x, y,
p and q ? ?
Scope B a,b 5, 8 y100 What are the values of
x, y, a and b ? ?
û
72
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.
73
4 scopes in Python
Built-In It is top level scope. Objects in this
scope are visible from everywhere.
B
Global entire program can access it, unless
duplicated.
G
Enclosing scope It is the scope of nested
functions.
Data of outer scope can be accessed from inner
scope.
E
Local Scope It is the scope exists inside a
function.
L
Internal elements should not be accessed from the
outside.
Nothing goes out like a black Hole.
74
Data from outer scope can be accessed from inner
scope. Data from inner scope cant be accessed
from outer scope.
A 10
Clicking on each Scope to see the data visible in
that Scope
B 20
Only the Objects defined in the Built - in scope
are available. A 10
C 30
Only the Objects defined in Built-in and global
scope are available. A 10 and B 20
All objects defined in the LEGB' scope can be
accessed from Local Scope. A10, B20, C30 and D
40
All objects defined in the 'BGE' scope can be
accessed from Enclosing Scope. A10, B20 and C30
?
D 40 Click Me
Global Scope
Enclosing
Built-In Scope
Local scope
Click Me ?
Click Me ?
Click Me ?
75
Variables, declared outside of functions are
called Global variable
Variables that declare within a function are
called Local Variable
76
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 stored If it is not initialized zero is stored as default.
It is created when the function starts execution and lost when the functions terminate. It is created before the program's global execution starts and lost when the program terminates.
Data sharing is not possible as data of the local variable can be accessed by only one function. Data sharing is possible as multiple functions can access the same global variable.
When the value of the local variable is modified in one function, the changes are not visible in another function. When the value of the global variable is modified in one function changes are visible in the rest of the program.
Local variables can be accessed inside a function in which they are declared. You can access global variables by any statement in the program.
77
def fun1() a, b 10, 15 print (A,a,B,
b,X , x, Y , y) x, y 1, 2 print (X
, x, Y , y) print (a, b)
variables a, b are local and limited its access
within this function.
variables x, y are global and its access is
everywhare.
What is Wrong ? ?
78
Global Vs Local
Memory







def fun1() a 10 print ("In fun1 a
", a) fun2() def fun2() print ("In fun2
a ", a) a 1 print ("In main a ",
a) fun1() print ("In main a ", a)
Creating a localized variable a in fun1()
and hide global variable a 1. Defferent ID
10
Output In fun1 a 10
Creating global variable a at Memory Id
1418093744
Output In fun2 a 1
1
Output In main a 1
Output In main a 1
79
def fun1() a 10 print ("In fun1 a
", a) fun2() def fun2() print ("In
fun2 a ", a) a 1 print ("In main a ",
a) fun1() print ("In main a ", a)
What will print? ?
What will print? ?
80
OUTPUT In main a 1 In fun1 a 10 In fun2 a
1 In main a 1
81
GLOBAL KEYWORD
The 'global' keyword is used to create a global
variable in a local context and allows changes to
the variable.
82
Within a function, the value of a global
variable can be read but you can't change.
def ABC() print(In ABC a , a) a
10 print (In Main a , a) ABC()
a 10 def ABC() a a 5
print(In ABC a , a) print (In Main a ,
a) ABC()
Global variable a10
Within a function, the value of a global
variable can't be change.
Global variable a10
?
?
Within a function, the value of a global
variable can be read.
83
The 'global' keyword is used to create a global
variable in a local context and allows for
changes in them.
Argue that a' is a global variable and add value
5 to it. it will be reflected in "main ()" as well
Creating a local variable a10 in ABC() and
hide global variable a 10.
def ABC() a 10 a a 5
print("In ABC a ", a) a 10 print ("In Main a
", a) ABC() print ("In Main a ", a)
def ABC() global a a a 5
print("In ABC a ", a) a 10 print ("In Main a
", a) ABC() print ("In Main a ", a)
The above local variable a 15 is not accessed
here
OUTPUT In Main a 10 In ABC a 15 In Main a
10
OUTPUT In Main a 10 In ABC a 15 In Main a
15
84
Docstring or Documentation string is a string
that provide a help topic (what the function do).
What will area() do ?
def area ( r ) return 3.14 r r ?? int
( input (Enter radius )) a ???????? ??
print (Area of circle is , a )
Ask help() of area
85
docstring
def area ( r ) ''' Calculate area when
giving radius. return ab
Documentation String
Docstring provides a help topic when calling help.
gtgtgt help(area) Help on function area in module
__main__ area(r) Calculate area when
giving radius.
86
gtgtgt def area ( r ) ''' Calculate area when
giving radius.''' return ab gtgtgt help
(area) Help on function area in module
__main__ area(r) Calculate area when giving
radius. gtgtgt
Docstring provides a help topic when calling help.
87
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 Integer Operation 10 20 30
def Celsius ( f ) c (f-32)/1.8 return
c a input("Enter Fahrenheit ") a int(a) c
Celsius(a) print ("Celsius Temperature ", c)
int () convert a Number or string into an
integer. Syntax is int (No, Base 10) int (
123 ) 123 int (1010, 2) 10 Int ( 11,16
) 17 int ( 12, 8 ) 10 Int ( 3.14 ) 3
Val 73
Val 45
Inputing digits as string
Covert into integer
88
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 ) return ( (F12) I)
2.5 f int ( input("Enter Feet ") ) i int (
input("Enter Inch ")) print("Total CM ", Cal_cm
(f,i) )
How many centimeters in 5 feet 4 inches. 1 Feet
12 inches 5 feet 5 12 inches 60
inches Total inches ( 5 12 ) 4 60 4
64 1 inch 2.5 cm 64 inches 64 2.5 160
Cm
Val 73
Val 45
OUTPUT Enter Feet 5 Enter Inch 4
Total CM 160
89
EXERCISES 3. Calculate the sum of elements in a
list.
def sum(List) sum 0 for val in List
sum val return sum a
eval(input("Enter a List ")) print("The Sum of
List is ", sum ( a ) )
for loop fetch each item in the list. List
5, 10, 15, 20, 25
Index 0 1 2 3 4
Val 73
Val 45
Step 1 val 5 sum 5 Step 2 val 10
sum 15 Step 3 val 15 sum 30 Step 4
val 20 sum 50 Step 5 val 25 sum 75
eval() evaluates the string as a Python
expression. Input String 5,10,15,20,25,
evaluated as a list
OUTPUT Enter a List of Nos 5,10,15,20,25
The Sum of List is 75
90
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 ) max List0 for
val in List1 if val gt max max
val return max a eval(input("Enter a list
of Nos ")) m greatest(a) print ("The Greatest
Value is ", m)
Val 73
Val 45
List 03 65, -38, 56 List 14 -38, 56,
-92 List 65, -38, 56, -92, 73, 45 List
2 65, 56, 73 List 1 -38,56,-92,
73,45
Passing 65, -38, 56, -92, 73,45
List1 -38, 56, -92, 73,45
Assume
List 65, -38, 56, -92, 73,45
91
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 ) max List0 for
val in List1 if val gt max max
val return max a eval(input("Enter a list
of Nos ")) m greatest(a) print ("The Greatest
Value is ", m)
List1 -38, 56,-92, 73, 45
Initial assumption max 65
Val 73
Val 45
Step 1 val -38 max 65 Step 2 val 56
max 65 Step 3 val -92 sum 60 Step 4
val 73 sum 73 Step 5 val 45 sum 73
Passing 65, -38, 56, -92, 73,45
for loop fetch each item in the List
1-38,56,-92,73, 45
92
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 ) max List0 for
val in List1 if val gt max max
val return max a eval(input("Enter a list
of Nos ")) m greatest(a) print ("The Greatest
Value is ", m)
List1 -38, 56, -92, 73,45
Val 73
Val 45
Initial assumption max 65
Step 1 val -38 max 65 Step 2 val 56
max 65 Step 3 val -92 sum 60 Step 4
val 73 sum 73 Step 5 val 45 sum 73
65, -38, 56, -92, 73,45
OUTPUT Enter a List of Nos 65, -38, 56,
-92, 73,45 The Greatest
Value is 73
93
EXERCISES 5. Calculate factorial of given no
using for loop.
Factorial of n (n!) is the product of all numbers
lt n. 5! 1 x 2 x 3 x 4 x 5 120.
def fact(n) f 1 for x in
range(1,n1) f x return f a
int(input("Enter a No ")) f fact(a) print("The
Factorial of ", a, " is ", f)
range() function create a sequence of values from
start to stop-1. Range(start, stop, step)
n 5
Val 73
Val 45
Start and Step are optional range (1, 5 ) 1, 2,
3, 4 range (5, 10 ) 5, 6, 7, 8, 9 range ( 1,
10, 2 ) 1,3,5,7,9 range ( 0, 20, 5 ) 0, 5,
10, 15 range (5, 0, -1) 5, 4, 3, 2, 1 range ( 5
) 0, 1, 2, 3, 4
Passing 5
Assume that input a 5
94
EXERCISES 5. Calculate factorial of given no
using for loop.
Factorial of n (n!) is the product of all numbers
lt n. 5! 1 x 2 x 3 x 4 x 5 120.
def fact(n) f 1 for x in
range(2,n1) f x return f a
int(input("Enter a No ")) f fact(a) print("The
Factorial of ", a, " is ", f)
Assume that input a 5
n 5
Assuming n 5 range (1, 6 ) 1, 2, 3, 4, 5 At
end of Step 1 x 2 f 2 Step 2 x 3
f 6 Step 3 x 4 f 24 Step 4 x 5
f 120
Val 73
Val 45
Passing 5
Muitiply value of x with existing value of f
OUTPUT Enter a No 5 The Factorial of 5 is 120
95
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.
Write a Comment
User Comments (0)
About PowerShow.com