SlideShare una empresa de Scribd logo
1 de 95
Descargar para leer sin conexión
CHAPTER 3
SELF-STUDY PRESENTATION
THROUGH ANIMATIONS.
Not for commercial use.
In programming Language, A function is a block of
statements to perform an action.
In dictionary,
FUNCTION means DEED
( പ്രവർത്തനം )
FUNCTION = പ്രവൃത്തി
കൃത്യം
ആചരണം
ചുമത്ല
ആഘ ോഷം
തത്ോഴില്‍
ധര്‍മ്മം
രരിരോടി
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 …..
 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 ?
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.
REMEMBER 3 THINGS.
TITLE OF PARAGRAPH
FULL COLON
HANGING ( INDENT ) LINES
How I wrote a Paragraph ?.
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.
INDENT = മോര്‍മ്ജിനില്‍ നിന്ന അക ലം വിട്ന ടടപ്ന തചയ്യുക
-----
1
2
3
def greatest ( List ) :
max = List[0]
for val in List[1:] :
if val > max : max = val
return max
eval(input("Ent
greatest(a)
DATA OUTPUT
For x = , the result is 2 * 12 = 2
For x = , the result is 2 * 22 = 8
For x = , the result is 2 * 32 = 18
𝑓 𝑥 = 2x2

Click here to watch 
Click here to watch 
Click here to watch 
𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 𝒄𝒂𝒏
𝒖𝒔𝒆 𝒎𝒂𝒏𝒚 𝒕𝒊𝒎𝒆𝒔 𝒘𝒊𝒕𝒉
𝒅𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒕 𝒗𝒂𝒍𝒖𝒆𝒔
FUNCTION TAKES DATA
PRODUCE OUTPUT
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)
-20
>>> max(-25,80)
80
>>> pow(2,3)
8
>>> len("ANIL")
4
>>> int(3.14)
3
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
>>> math.sqrt(25)
5.0
>>> math.floor(3.14)
3
>>> math.ceil(3.14)
4
>>> import random
>>> 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.
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.
--------
def function Name ( ) :
Statement 1
Statement 2
… … … … …
Function Body
or function suit.
--------
A pair of Brackets “()”
It begins with the keyword “def”
Function Name.
End with a colon (“:”)
Space before statements (Indentation)
2
4( )
def pie ( ) :
return 22 / 7
def root2 ( ) :
return 1.4142
def pledge ( ) :
print ( “India is my country…”)
Click Me 
Click Me 
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.
def 𝑃𝑖𝑒 ( ) :
return 22/7
𝑝 = Pie( )
print (“Value of Pie is “, p)
Goto the function
definition and return
back with the result.
Function call statement
>>> def pie ( ) :
return 22 / 7
>>> def root2 ( ) :
return 1.4142
>>> def pledge ( ) :
print ( "India is my country…")
>>> pledge()
>>> India is my country…
>>> b = root2()
>>> print ( b )
>>> 1.4142
>>> a = pie()
>>> print ( a )
>>> 3.142857142857143
Function Call
FunctionCall
Function Call
CallingDefinitions
Function
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 
INVOKE THE FUNCTIONS IN THE
FOLLOWING ORDER
B()
D()
A()
C()
>>> def A ( ) :
print("Up above the world so high,")
C()
>>> def B ( ):
print ("TWINKLE, twinkle, little star,")
D()
>>> def C ( ) :
print ( "Like a diamond in the sky." )
>>> def D ( ) :
print ( "How I wonder what you are! " )
A()
>>> B()
OUTPUT
>>>
TWINKLE, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
>>>
# Calling the Function C()
# Calling the Function D()
# Calling the Function A()
Arguments act as an input to the function, to
carries out the specified task.
1. Accepts Data
2. Carried out desired process.
3. Produce Output
ARGUMENTS OR PARAMETERS
Arguments act as an input to
the function, to carry out
the specified task.
Function Definition Returns output
For x = , the result is 2 * 12 = 2
For x = , the result is 2 * 22 = 8
For x = , the result is 2 * 32 = 18
𝑓 𝑥 = 2x2
𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 𝒄𝒂𝒏 𝒖𝒔𝒆
𝒎𝒂𝒏𝒚 𝒕𝒊𝒎𝒆𝒔 𝒘𝒊𝒕𝒉
𝒅𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒕 𝒗𝒂𝒍𝒖𝒆𝒔

Click here to watch 
Click here to watch 
Click here to watch 
X’ ‘ receives a value,
and f() returns 2 * x2
def 𝑓 𝑥 :
return 2 * 𝑥 * 𝑥
𝑥 = int ( input ( “Enter No ” ) )
a = 𝑓 𝑥
print (“Answer is ”, a )
What is the answer if x = 5 ?
def 𝑓(𝑥) :
return 2 * 𝑥 * 𝑥
𝑥 = int ( input ( “Enter No ” ) )
a = 𝑓(𝑥)
print (“Answer is ”, a )
OUTPUT
>>>
Answer is 50
>>>
# Calling the Function F(5) by
passing the value 5.
# Input the Value 5.
def add ( a , b , c , d ) :
print ( “Sum is “, a+b+c+d )
add ( 10 , 20, 30, 40 )
a=10 b=20 c=30 d=40
Arguments act as an input to the function, to
carry out the specified task.
Difference between Arguments and
Parameters
Arguments are the actual
values passed to the function
when it is called
Parameter are variables,
which receives the values
of passing arguments.
ARGUMENTS OR PARAMETERS
def area ( r ) :
return 3.14 * r ** r
a = area ( 10 )
print ( “Area of the circle is”, a)
Arguments are the actual
values passed to the
function when it is called
Parameter are variables, receiving passing
values within the function definition.
return a+b+c
X = 20
add (10, X, (3*10) )
Literal
Variable
Expression
Literal 10, value of
variable x and the end
result of expression
(3*10) i.e. 30 will be
passed as arguments.
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)
Missing Return statement here
Example of
Void Functions.
No Return
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.
Causing the error TypeError:
unsupported operand type(s) for /:
'NoneType' and 'int'
DON ’ T DO


Give me some
numbers. I'll return
their sum.
The return statement
stops the execution of
a function and returns
to the caller function.
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 a+b+c+d
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.
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] )
ALL IN ONE
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]
RETURN MULTIPLE VALUES
def Sum_Avg ( a , b , c , d ) :
t=a+b+c+d
return t, t/4
sum, avg = Sum_Avg (10, 20, 30, 40)
print (“Sum = “, sum , ” Avg = “, avg)
t=100
100 25
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
>>> name, roll, Class = “Anil”, 15, “XII”
>>> a = b = c = 0
>>> print (x, y, z )
>>> 10 20 30
>>> print (name, roll, Class)
>>> Anil 15, XII
>>> print(a,b,c)
>>> 0 0 0
There are 3 (4) types of arguments.
and Varying arguments.
1
2
3
These are mandatory arguments and take orderly.
Provides default value to an argument. It will be
used when we omit value during function call.
Keyword arguments are same as default
arguments but it allows you to give
name-value pairs instead of just the value.
1
2
3
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.
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.
TypeError: add() missing 2 required
Positional arguments: 'c' and 'd‘
DON ’ T DO
Missing c & d

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…..

Example Program.
Interest= Principal Amount * Rate * Years.
Parameter Values
prin = 1000, Rate = 0.1
Years = 3
def interest (prin, rate, years) :
return prin*rate*years
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
What a dilemma !
How I satisfies
both of them
I want sum of
3 Nos(10,20
and 30)
I want sum of 2
Nos(10 and 20)
default (Optional ) arguments.
What a dilemma !
How I satisfies
both of them
I allows 2
entry only.
When we omit some
arguments, it uses the
default values.
def add (a, b, c=0) :
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)
Output
Enter 1st No 10
Enter 2nd No 20
Enter 3rd No 30
Sum of 2 Nos = 30
Sum of 3 Nos = 60
Since we omit 3rd argument, c becomes 0
def add(a=0, b=0, c=0, d=0, e=0) :
return a+b+c+d+e
What do you think ?.
Is it correct in all
situations.
def greet (𝐧𝐚𝐦𝐞, 𝐚𝐠𝐞 ) :
print(“Hai ”, name, “, you are”, age, “years old”)
greet („Aswin‟, 18)
What happened when I call
Click Me 
Aswin,
Roll no 16,
stand up.
I am Aswin,
Roll no 16.
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)
greet (roll = 16, name = “Aswin”)
x = 10 y = 20 The repeating variable
(y=100) will hides the
previous (y=20).
Built-In : It is top level scope.
Objects in this scope are visible
from everywhere.
Global : entire program can
access it, unless duplicated.
Enclosing scope : It is
the scope of nested
functions.
Local Scope : It is
the scope exists
inside a function.
Internal elements
should not be accessed
from the outside.
Nothing goes out
like a black Hole.
Built-InScope:
GlobalScope:
Enclosing
Local scope
A = 10
B = 20
C = 30
D = 40
Click Me
Click Me
Click Me 
Click Me
Variables, declared
outside of functions
are called
Global and local scope
Variables that
declare within a
function are called
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.
Global vs local Variables.
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 ?
Memory
1Run Me
2Run Me
4Run Me
3Run Me
Start from below
Output: In main a = 1
Output: In main a = 1
Output: In fun2 a = 1
Output: In fun1 a = 10
OUTPUT
In main a = 1
In fun1 a = 10
In fun2 a = 1
In main a = 1
The 'global' keyword is used to
create a global variable in a
local context and allows
changes to the variable.
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 a=10
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)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
The above local variable
a = 15 is not accessed here
Creating a local variable ‘a=10’
in ABC() and hide global
variable a = 10.
Docstring
def area ( r ) :
return 3.14 * r * r
𝑟 = int ( input (“Enter radius ” ))
a = 𝐚𝐫𝐞𝐚 𝑟
print (“Area of circle is ”, a )
docstring
def area ( r ) :
return a+b
>>> 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
>>> help (area)
Help on function area in module __main__:
area(r)
Calculate area when giving radius.
>>>
Val = 73Val = 45
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.
def Celsius ( f ):
c = (f-32)/1.8
return c
a = input("Enter Fahrenheit ")
a = int(a)
c = Celsius(a)
print ("Celsius Temperature = ", c)
Inputing digits as string
Covert into integer
int () convert a Number or
string into an integer.
Syntax is
int ( “123” ) = 123
int (“1010”, 2) = 10
Int ( “11”,16 ) = 17
int ( “12”, 8 ) = 10
Int ( 3.14 ) = 3
“ANIL “ + “KUMAR” = “ANIL KUMAR”
String : “10” + “20” = “1020”
Integer Operation : 10 + 20 = 30
Val = 73Val = 45
def Cal_cm ( F , I ):
f = int ( input("Enter Feet ") )
i = int ( input("Enter Inch "))
print("Total CM = ", )
OUTPUT : Enter Feet 5
Enter Inch 4
Total CM = 160
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
EXERCISES 2. Covert length in feet and inches to
centimeters. 1 inch = 2.5 cm & 1 feet = 12 inches.
F = 5 and I = 4
Val = 73Val = 45
def sum(List) :
sum = 0
for val in List:
sum += val
return sum
a = (input("Enter a List "))
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
“for” loop fetch each item in the list.
List = [ 5, 10, 15, 20, 25 ]
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
EXERCISES 3. Calculate the sum of elements in a list.
Index 0 1 2 3 4
eval() evaluates the string as a Python
expression. Input String [5,10,15,20,25],
evaluated as a list
Val = 73Val = 45
max = List[0]
for val in :
if val > max : max = val
return max
print ("The Greatest Value is ", m)
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
List[1: : ] = [-38, 56, -92, 73,45 ]
List [0:3] = [65, -38, 56]
List [1:4] = [-38, 56, -92]
List[::] = [65, -38, 56, -92, 73, 45]
List [::2] = [65, 56, 73]
List [1: ] = [ -38,56,-92, 73,45 ]
EXERCISES 4. Find out the greatest value in a list.
List = [65, -38, 56, -92, 73,45 ]
List = [65, -38, 56, -92, 73, 45 ]
Index 0 1 2 3 4 5
Assume
Passing[65,-38,56,-92,73,45]
Val = 73Val = 45
def greatest ( List ) :
max = List[0]
for val in List[1:] :
if val > max : max = val
return max
a = eval(input("Enter a list of Nos "))
m = greatest(a)
print ("The Greatest Value is ", m)
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.
List[1: ] = [-38, 56,-92, 73, 45]
EXERCISES 4. Find out the greatest value in a list.
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
List = [65, -38, 56, -92, 73,45 ]
Index 0 1 2 3 4 5
Passing[65,-38,56,-92,73,45]
“for” loop fetch each item in the List [1:]=[-38,56,-92,73, 45
Val = 73Val = 45
def greatest ( List ) :
max = List[0]
for val in List[1:] :
if val > max : max = val
return max
a = eval(input("Enter a list of Nos "))
m = greatest(a)
print ("The Greatest Value is ", m)
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.
List[1: : ] = [-38, 56, -92, 73,45 ]
EXERCISES 4. Find out the greatest value in a list.
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
List = [65, -38, 56, -92, 73,45 ]
Index 0 1 2 3 4 5
OUTPUT : Enter a List of Nos [65, -38, 56, -92, 73,45]
The Greatest Value is 73
[65,-38,56,-92,73,45]
Val = 73Val = 45
def fact(n) :
f = 1
for x in range(1,n+1):
f *= x
return f
a = int(input("Enter a No "))
f = fact(a)
print("The Factorial of ", a, " is ", f)
EXERCISES 5. Calculate factorial of given no using for loop.
range() function create a sequence
of values from start to stop-1.
Range(start, stop, step)
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
Factorial of n (n!) is the product of all numbers <= n.
5! = 1 x 2 x 3 x 4 x 5 = 120.
Assume that
input a = 5
n = 5
Passing5
Val = 73Val = 45
def fact(n) :
f = 1
for x in range(2,n+1):
f *= x
return f
a = int(input("Enter a No "))
f = fact(a)
print("The Factorial of ", a, " is ", f)
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.
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
OUTPUT
Enter a No 5
The Factorial of 5 is 120
Muitiply value of
x with existing
value of f
Assume that
input a = 5n = 5
Passing5
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.

Más contenido relacionado

La actualidad más candente

Inline function
Inline functionInline function
Inline function
Tech_MX
 

La actualidad más candente (20)

Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Python list
Python listPython list
Python list
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
python Function
python Function python Function
python Function
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
List in Python
List in PythonList in Python
List in Python
 
Inline function
Inline functionInline function
Inline function
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 

Similar a FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE

Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#
Dmitri Nesteruk
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 

Similar a FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE (20)

FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Python programming
Python  programmingPython  programming
Python programming
 
Python basic
Python basicPython basic
Python basic
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative Practice
 
Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
functions
functionsfunctions
functions
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Elixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental ConceptsElixir in a nutshell - Fundamental Concepts
Elixir in a nutshell - Fundamental Concepts
 
Dictionary
DictionaryDictionary
Dictionary
 
Kotlin for Android Developers - 2
Kotlin for Android Developers - 2Kotlin for Android Developers - 2
Kotlin for Android Developers - 2
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 

Más de Venugopalavarma Raja

Más de Venugopalavarma Raja (12)

Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSLINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSINHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
POINTERS IN C++ CBSE +2 COMPUTER SCIENCEPOINTERS IN C++ CBSE +2 COMPUTER SCIENCE
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
 
Be happy Who am I
Be happy Who am IBe happy Who am I
Be happy Who am I
 
Be happy
Be happyBe happy
Be happy
 
Chess for beginers
Chess for beginersChess for beginers
Chess for beginers
 

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE

  • 1. CHAPTER 3 SELF-STUDY PRESENTATION THROUGH ANIMATIONS. Not for commercial use.
  • 2.
  • 3. In programming Language, A function is a block of statements to perform an action. In dictionary, FUNCTION means DEED ( പ്രവർത്തനം ) FUNCTION = പ്രവൃത്തി കൃത്യം ആചരണം ചുമത്ല ആഘ ോഷം തത്ോഴില്‍ ധര്‍മ്മം രരിരോടി
  • 4.
  • 5. 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 …..  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 ?
  • 6. 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. REMEMBER 3 THINGS. TITLE OF PARAGRAPH FULL COLON HANGING ( INDENT ) LINES How I wrote a Paragraph ?. 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. INDENT = മോര്‍മ്ജിനില്‍ നിന്ന അക ലം വിട്ന ടടപ്ന തചയ്യുക ----- 1 2 3
  • 8. def greatest ( List ) : max = List[0] for val in List[1:] : if val > max : max = val return max eval(input("Ent greatest(a)
  • 9.
  • 11. For x = , the result is 2 * 12 = 2 For x = , the result is 2 * 22 = 8 For x = , the result is 2 * 32 = 18 𝑓 𝑥 = 2x2  Click here to watch  Click here to watch  Click here to watch  𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 𝒄𝒂𝒏 𝒖𝒔𝒆 𝒎𝒂𝒏𝒚 𝒕𝒊𝒎𝒆𝒔 𝒘𝒊𝒕𝒉 𝒅𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒕 𝒗𝒂𝒍𝒖𝒆𝒔 FUNCTION TAKES DATA 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 simplefunction 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.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) -20 >>> max(-25,80) 80 >>> pow(2,3) 8 >>> len("ANIL") 4 >>> int(3.14) 3
  • 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. >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(25) 5.0 >>> math.floor(3.14) 3 >>> math.ceil(3.14) 4 >>> import random >>> 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.
  • 17.
  • 18. 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. def function Name ( ) : Statement 1 Statement 2 … … … … … Function Body or function suit. -------- A pair of Brackets “()” It begins with the keyword “def” Function Name. End with a colon (“:”) Space before statements (Indentation) 2 4( )
  • 20. def pie ( ) : return 22 / 7 def root2 ( ) : return 1.4142 def pledge ( ) : print ( “India is my country…”) Click Me  Click Me 
  • 21.
  • 22.
  • 23. 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. def 𝑃𝑖𝑒 ( ) : return 22/7 𝑝 = Pie( ) print (“Value of Pie is “, p) Goto the function definition and return back with the result. Function call statement
  • 25. >>> def pie ( ) : return 22 / 7 >>> def root2 ( ) : return 1.4142 >>> def pledge ( ) : print ( "India is my country…") >>> pledge() >>> India is my country… >>> b = root2() >>> print ( b ) >>> 1.4142 >>> a = pie() >>> print ( a ) >>> 3.142857142857143 Function Call FunctionCall Function Call CallingDefinitions Function
  • 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  INVOKE THE FUNCTIONS IN THE FOLLOWING ORDER B() D() A() C()
  • 27. >>> def A ( ) : print("Up above the world so high,") C() >>> def B ( ): print ("TWINKLE, twinkle, little star,") D() >>> def C ( ) : print ( "Like a diamond in the sky." ) >>> def D ( ) : print ( "How I wonder what you are! " ) A() >>> B() OUTPUT >>> TWINKLE, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. >>> # Calling the Function C() # Calling the Function D() # Calling the Function A()
  • 28.
  • 29.
  • 30. Arguments act as an input to the function, to carries out the specified task. 1. Accepts Data 2. Carried out desired process. 3. Produce Output
  • 31. ARGUMENTS OR PARAMETERS Arguments act as an input to the function, to carry out the specified task. Function Definition Returns output
  • 32. For x = , the result is 2 * 12 = 2 For x = , the result is 2 * 22 = 8 For x = , the result is 2 * 32 = 18 𝑓 𝑥 = 2x2 𝑭𝒖𝒏𝒄𝒕𝒊𝒐𝒏𝒔 𝒄𝒂𝒏 𝒖𝒔𝒆 𝒎𝒂𝒏𝒚 𝒕𝒊𝒎𝒆𝒔 𝒘𝒊𝒕𝒉 𝒅𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒕 𝒗𝒂𝒍𝒖𝒆𝒔  Click here to watch  Click here to watch  Click here to watch  X’ ‘ receives a value, and f() returns 2 * x2
  • 33. def 𝑓 𝑥 : return 2 * 𝑥 * 𝑥 𝑥 = int ( input ( “Enter No ” ) ) a = 𝑓 𝑥 print (“Answer is ”, a ) What is the answer if x = 5 ?
  • 34. def 𝑓(𝑥) : return 2 * 𝑥 * 𝑥 𝑥 = int ( input ( “Enter No ” ) ) a = 𝑓(𝑥) print (“Answer is ”, a ) OUTPUT >>> Answer is 50 >>> # Calling the Function F(5) by passing the value 5. # Input the Value 5.
  • 35. def add ( a , b , c , d ) : print ( “Sum is “, a+b+c+d ) add ( 10 , 20, 30, 40 ) a=10 b=20 c=30 d=40 Arguments act as an input to the function, to carry out the specified task. Difference between Arguments and Parameters Arguments are the actual values passed to the function when it is called Parameter are variables, which receives the values of passing arguments.
  • 36. ARGUMENTS OR PARAMETERS def area ( r ) : return 3.14 * r ** r a = area ( 10 ) print ( “Area of the circle is”, a) Arguments are the actual values passed to the function when it is called Parameter are variables, receiving passing values within the function definition.
  • 37. return a+b+c X = 20 add (10, X, (3*10) ) Literal Variable Expression Literal 10, value of variable x and the end result of expression (3*10) i.e. 30 will be passed as arguments.
  • 38.
  • 39. 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) Missing Return statement here Example of Void Functions. No Return
  • 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. Causing the error TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' DON ’ T DO  
  • 41. 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. 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 a+b+c+d 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.
  • 44.
  • 45. 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] ) ALL IN ONE 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.
  • 47. RETURN MULTIPLE VALUES def Sum_Avg ( a , b , c , d ) : t=a+b+c+d return t, t/4 sum, avg = Sum_Avg (10, 20, 30, 40) print (“Sum = “, sum , ” Avg = “, avg) t=100 100 25
  • 48.
  • 49. 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 >>> name, roll, Class = “Anil”, 15, “XII” >>> a = b = c = 0 >>> print (x, y, z ) >>> 10 20 30 >>> print (name, roll, Class) >>> Anil 15, XII >>> print(a,b,c) >>> 0 0 0
  • 50. There are 3 (4) types of arguments. and Varying arguments. 1 2 3
  • 51. These are mandatory arguments and take orderly. Provides default value to an argument. It will be used when we omit value during function call. 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.
  • 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. TypeError: add() missing 2 required Positional arguments: 'c' and 'd‘ DON ’ T DO Missing c & 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. Parameter Values prin = 1000, Rate = 0.1 Years = 3
  • 56. def interest (prin, rate, years) : return prin*rate*years 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
  • 57.
  • 58. What a dilemma ! How I satisfies both of them I want sum of 3 Nos(10,20 and 30) I want sum of 2 Nos(10 and 20)
  • 59. default (Optional ) arguments. What a dilemma ! How I satisfies both of them I allows 2 entry only.
  • 60. When we omit some arguments, it uses the default values.
  • 61. def add (a, b, c=0) : 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) Output Enter 1st No 10 Enter 2nd No 20 Enter 3rd No 30 Sum of 2 Nos = 30 Sum of 3 Nos = 60 Since we omit 3rd argument, c becomes 0
  • 62. def add(a=0, b=0, c=0, d=0, e=0) : return a+b+c+d+e
  • 63. What do you think ?. Is it correct in all situations.
  • 64. def greet (𝐧𝐚𝐦𝐞, 𝐚𝐠𝐞 ) : print(“Hai ”, name, “, you are”, age, “years old”) greet („Aswin‟, 18) What happened when I call Click Me 
  • 65.
  • 66. Aswin, Roll no 16, stand up. I am Aswin, Roll no 16. Giving arguments in the form of key-value pairs are called keyword arguments.
  • 67.
  • 68. def greet (name, roll ): print (“Hai“,name,“Your Roll No is”, roll) greet (roll = 16, name = “Aswin”)
  • 69.
  • 70.
  • 71. x = 10 y = 20 The repeating variable (y=100) will hides the previous (y=20).
  • 72.
  • 73. Built-In : It is top level scope. Objects in this scope are visible from everywhere. Global : entire program can access it, unless duplicated. Enclosing scope : It is the scope of nested functions. Local Scope : It is the scope exists inside a function. Internal elements should not be accessed from the outside. Nothing goes out like a black Hole.
  • 74. Built-InScope: GlobalScope: Enclosing Local scope A = 10 B = 20 C = 30 D = 40 Click Me Click Me Click Me  Click Me
  • 75. Variables, declared outside of functions are called Global and local scope Variables that declare within a function are called
  • 76. 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. Global vs local Variables.
  • 77. 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. Memory 1Run Me 2Run Me 4Run Me 3Run Me Start from below Output: In main a = 1 Output: In main a = 1 Output: In fun2 a = 1 Output: In fun1 a = 10
  • 79.
  • 80. OUTPUT In main a = 1 In fun1 a = 10 In fun2 a = 1 In main a = 1
  • 81. The 'global' keyword is used to create a global variable in a local context and allows changes to the variable.
  • 82. 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 a=10 Global variable a=10  
  • 83. 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)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 The above local variable a = 15 is not accessed here Creating a local variable ‘a=10’ in ABC() and hide global variable a = 10.
  • 84. Docstring def area ( r ) : return 3.14 * r * r 𝑟 = int ( input (“Enter radius ” )) a = 𝐚𝐫𝐞𝐚 𝑟 print (“Area of circle is ”, a )
  • 85. docstring def area ( r ) : return a+b >>> help(area) Help on function area in module __main__: area(r) Calculate area when giving radius.
  • 86. >>> def area ( r ) : ''' Calculate area when giving radius.''' return a+b >>> help (area) Help on function area in module __main__: area(r) Calculate area when giving radius. >>>
  • 87. Val = 73Val = 45 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. def Celsius ( f ): c = (f-32)/1.8 return c a = input("Enter Fahrenheit ") a = int(a) c = Celsius(a) print ("Celsius Temperature = ", c) Inputing digits as string Covert into integer int () convert a Number or string into an integer. Syntax is int ( “123” ) = 123 int (“1010”, 2) = 10 Int ( “11”,16 ) = 17 int ( “12”, 8 ) = 10 Int ( 3.14 ) = 3 “ANIL “ + “KUMAR” = “ANIL KUMAR” String : “10” + “20” = “1020” Integer Operation : 10 + 20 = 30
  • 88. Val = 73Val = 45 def Cal_cm ( F , I ): f = int ( input("Enter Feet ") ) i = int ( input("Enter Inch ")) print("Total CM = ", ) OUTPUT : Enter Feet 5 Enter Inch 4 Total CM = 160 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 EXERCISES 2. Covert length in feet and inches to centimeters. 1 inch = 2.5 cm & 1 feet = 12 inches. F = 5 and I = 4
  • 89. Val = 73Val = 45 def sum(List) : sum = 0 for val in List: sum += val return sum a = (input("Enter a List ")) 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 “for” loop fetch each item in the list. List = [ 5, 10, 15, 20, 25 ] 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 EXERCISES 3. Calculate the sum of elements in a list. Index 0 1 2 3 4 eval() evaluates the string as a Python expression. Input String [5,10,15,20,25], evaluated as a list
  • 90. Val = 73Val = 45 max = List[0] for val in : if val > max : max = val return max print ("The Greatest Value is ", m) 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 List[1: : ] = [-38, 56, -92, 73,45 ] List [0:3] = [65, -38, 56] List [1:4] = [-38, 56, -92] List[::] = [65, -38, 56, -92, 73, 45] List [::2] = [65, 56, 73] List [1: ] = [ -38,56,-92, 73,45 ] EXERCISES 4. Find out the greatest value in a list. List = [65, -38, 56, -92, 73,45 ] List = [65, -38, 56, -92, 73, 45 ] Index 0 1 2 3 4 5 Assume Passing[65,-38,56,-92,73,45]
  • 91. Val = 73Val = 45 def greatest ( List ) : max = List[0] for val in List[1:] : if val > max : max = val return max a = eval(input("Enter a list of Nos ")) m = greatest(a) print ("The Greatest Value is ", m) 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. List[1: ] = [-38, 56,-92, 73, 45] EXERCISES 4. Find out the greatest value in a list. 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 List = [65, -38, 56, -92, 73,45 ] Index 0 1 2 3 4 5 Passing[65,-38,56,-92,73,45] “for” loop fetch each item in the List [1:]=[-38,56,-92,73, 45
  • 92. Val = 73Val = 45 def greatest ( List ) : max = List[0] for val in List[1:] : if val > max : max = val return max a = eval(input("Enter a list of Nos ")) m = greatest(a) print ("The Greatest Value is ", m) 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. List[1: : ] = [-38, 56, -92, 73,45 ] EXERCISES 4. Find out the greatest value in a list. 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 List = [65, -38, 56, -92, 73,45 ] Index 0 1 2 3 4 5 OUTPUT : Enter a List of Nos [65, -38, 56, -92, 73,45] The Greatest Value is 73 [65,-38,56,-92,73,45]
  • 93. Val = 73Val = 45 def fact(n) : f = 1 for x in range(1,n+1): f *= x return f a = int(input("Enter a No ")) f = fact(a) print("The Factorial of ", a, " is ", f) EXERCISES 5. Calculate factorial of given no using for loop. range() function create a sequence of values from start to stop-1. Range(start, stop, step) 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 Factorial of n (n!) is the product of all numbers <= n. 5! = 1 x 2 x 3 x 4 x 5 = 120. Assume that input a = 5 n = 5 Passing5
  • 94. Val = 73Val = 45 def fact(n) : f = 1 for x in range(2,n+1): f *= x return f a = int(input("Enter a No ")) f = fact(a) print("The Factorial of ", a, " is ", f) 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. 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 OUTPUT Enter a No 5 The Factorial of 5 is 120 Muitiply value of x with existing value of f Assume that input a = 5n = 5 Passing5
  • 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.