Python - Slide 4
Python - Slide 4
Function
• With the help of functions, an entire program can be divided into small
independent modules (each small module is called a function). This
improves the code’s readability as well as the flow of execution as small
modules can be managed easily.
Function in
Python Formal
arguments
def
function_name ( parameters Documentation
‘’’function_docstrin ): Option
string al
g’’’
Statement/s
return
[expression]
Actual
arguments
function_name( paramet
ers )
Function Example
-1
def fun(a, b):
'''Function to add two values'''
c=a+b
print(c) Output:
fun(10, 20)
Function Example
-1
def fun(a, b):
'''Function to add two values'''
c=a+b
return c Output:
print(fun(10, 20))
Function Example
-1
def fun(a, b):
'''Function to add two values'''
c=a+b
return c Output:
z = fun(10, 20)
print(z)
THE return STATEMENT
Output: 10 ‘hello’
10.5
Keyword
Arguments
• The caller identifies the arguments by the parameter name.
• This allows you to:
- skip arguments or
– place them out of order
>>>def fun(x = 0 , y =
0 , z= 0 ): print
(x , y , z)
>>>fun(100, 200,
300)
>>>fun(100, 200)
>>>fun(100)
>>>fun()
Default
Arguments
Default
Arguments
Output
Default
Arguments
Output
THE LOCAL AND GLOBAL SCOPE OF A VARIABLE
• Variables and parameters that are initialized within a function, are said
to exist in that function’s local scope. Variables that exist in local
scope are called local variables.
• Variables that are assigned outside functions are said to exist in global
scope. Therefore, variables that exist in global scope are called global
variables.
THE LOCAL AND GLOBAL SCOPE OF A VARIABLE
• No def keyword.
lambda [arg1
[,arg2,.....argn]]:expression
>>>def add(x, y,
z):
return x + y
+z
>>>a = lambda x, y,
z: x+y+z
>>>a(10,2
0,30) 60