Sunteți pe pagina 1din 61

 A function is a tool that groups a set of statements so they

can be run more than once in a program—a packaged


procedure invoked by name

 Functions serve two primary development roles:


- Maximizing code reuse and minimizing redundancy
- Procedural decomposition

 There are two sides to the function picture:


- a definition (the def that creates a function)
- and a call (an expression that tells Python to run the
function’s body).
 def statements: The def statement creates a function
object and assigns it to a name.
 Its general format is as follows:
def name(arg1, arg2,... argN):
...
return value
Or
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
 Function blocks begin with the keyword def followed by
the function name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed
within these parentheses. You can also define parameters
inside these parentheses.
 The code block within every function starts with a colon (:)
and is indented.
 The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
 The statement return [expression] exits a function,
passing back an expression to the caller. A return statement
with no arguments is the same as return None. The return
statement itself is optional too
 After defining a function, we can call the function
by using the same pair of parentheses that we are
used to.
 Ex:
def sum(n1, n2):
return n1+n2
a=int(input("enter a no="))
b=int(input("enter a no="))
s=sum(a,b)
print("sum=",s)
def Executes at Runtime
 The Python def is a true executable statement:
when it runs, it creates a new function object and
assigns it to a name
 Remember, all we have in Python is runtime; there
is no such thing as a separate compile time.
 Because it’s a statement, a def can appear
anywhere a statement can—even nested in other
statements
 Example
if test:
def func(): # Define func this way

...
else:
def func(): # Or else this way

...
...
func() # Call the version selected and built

(for prog of above ex see function with ifelse.py)


 def is much like an = statement
 Because function definition happens at runtime, there’s
nothing special about the function name. What’s
important is the object to which it refers:
othername = func # Assign function object
othername() # Call func again

Ex: def sum(n1,n2):


return n1+n2
a=int(input("enter a no="))
b=int(input("enter a no="))
s=sum
x=s(a,b)
print(“Addition of two numbers=",x)
WAP to accept 2 strings from user and print repeated/common
characters
def intersect(seq1, seq2):
res = [] # Start empty
for x in seq1: # Scan seq1
if x in seq2: # Common item?
res.append(x) # Add to end
return res

s1=input("enter a string1 =")


s2=input("enter a string2 =")
l=intersect(s1,s2)
print(l)

(See function2.py)
Scope
 The scope of a variable (where it can be used) is always determined by
where it is assigned in your source code
 Variables may be assigned at two different places, corresponding
to two different scopes:
- If a variable is assigned inside a def, it is local to that
function.
- If a variable is assigned outside all defs, it is global to the
entire file.
 Ex: X = 99 # Global (module) scope X
def func():
X = 88 # Local (function) scope X: a different variable
(program for above ex see function3.py)

 Even though both variables are named X, their scopes make


them different.
 Ex: # Global scope
X = 99 -# X and func assigned in module: global
def f1(Y): # Y and Z assigned in function: locals
# Local scope
Z=X+Y # X is a global
return Z
f1(1)
Output: 100
 we can classify the names as follows:
- Global names: X, f1 -
(i) X is global because it’s assigned at the top level of the
module file; it can be referenced inside the function.
(ii)f1 is global for the same reason; the def statement
assigns a function object to the name f1
- Local names: Y, Z –
Y and Z are local to the function (and exist only while the
function runs) because they are both assigned values in the
function definition
The global Statement
 Global names or variable: - Global names are variables
assigned at the top level of the enclosing module file.
- Global names must be declared only if they are assigned
within a function.
- Global names may be referenced within a function
without being declared.
 The global statement tells Python that a function plans to
change one or more local names to global names
 The global statement consists of the keyword ‘global’,
followed by one or more names separated by commas
 All the listed names will be mapped to the enclosing
module’s scope when assigned or referenced within the
function body.
The global Statement
 Ex: X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def

func()
print(X) # Prints 99
 We’ve added a ‘global’ declaration to the example here, such
that the X inside the def now refers to the X outside the def.
 They are the same variable this time, so changing X inside the
function changes the X outside it.
 Ex: 1) What will be output of following code?
X = 99
def func1():
global X
X = 88
def func2():
global X
X = 77

func1()
print(X)
Output: 88
 2) What will be output of following code?
X = 99
def func1():
global X
X = 88
def func2():
global X
X = 77

func2()
print(X)
Output: 77
 3) What will be output of following code?
X = 99
def func1():
global X
X = 88
def func2():
global X
X = 77
func1()
func2()
print(X)
Output: 77
 4) What will be output of following code?
X = 99
def func1():
global X
X = 88
def func2():
X = 77
func1()
func2()
print(X)
Output: 88
 5) What will be output of following code?
X = 99
def func1():
X = 88
def func2():
X = 77
func1()
func2()
print(X)
Output: 99
 6) What will be output of following code?

def func1():
global X
X = 88
def func2():
X = 77
func1()
func2()
print(X)

Output: 88
 What is the output of this code, and why?
X = 'Spam'
def func():
X = 'NI!'
func()
print(X)
 The output here is 'Spam' again because assigning
the variable inside the function makes it a local
and effectively hides the global of the same name.
The print statement finds the variable unchanged
in the global (module) scope.
 What does this code print, and why?
X = 'Spam'
def func():
X = 'NI'
print(X)
func()
print(X)

 It prints 'NI' on one line and 'Spam' on another,


because the reference to the variable within the
function finds the assigned local and the reference
in the print statement finds the global.
 What output does this code produce? Why?
X = 'Spam'
def func():
global X
X = 'NI'
func()
print(X)

 This time it just prints 'NI' because the global


declaration forces the variable assigned inside the
function to refer to the variable in the enclosing
global scope.
Nested function/Scope Example
 The def is simply an executable statement, which can appear anywhere
and any other statement can include another def(nested function)

X = 99 # Global scope name: not used


def f1():
X = 88 # Enclosing def local
def f2():
print(X) # Reference made in nested def
f2()
f1()
Output: 88 (see function5.py)
 Here, the nested def runs when there is a call to the function f1
 It generates a new function and assigns it to the name f2, a local
variable within f1’s local scope.
 Here, f2 is a temporary function that lives only during the execution of
(and is visible only to code in) the enclosing f1.
 What about this code—what’s the output, and why?
X = 'Spam'
def func():
X = 'NI'
def nested():
print(X)
nested()
func()
print(X)
 The output in this case is 'NI' on one line and 'Spam' on
another, because the print statement in the nested
function finds the name in the enclosing function’s local
scope, and the print at the end finds the variable in the
global scope.
 If X is declared ‘global’ within the function, the assignment creates or changes
the name X in the enclosing module’s scope.
 If, on the other hand, X is declared ‘nonlocal’ within the function in 3.X (only),
the assignment changes the name X in the closest enclosing function’s local
scope.
 Syntax: def func():
nonlocal name1, name2, ... # OK here
>>> nonlocal X
SyntaxError: nonlocal declaration not allowed at module level
 The names listed in a nonlocal must have been previously defined in an
enclosing def
 The net effect is much like global: global means the names reside in the
enclosing module, and nonlocal means they reside in an enclosing def.
 Nonlocal variable are used in nested function whose local scope is not defined.
 Ex: def func():
X = 'NI'
def nested():
nonlocal X
X = 'Spam'
nested()
print(X)
func()

What will be output of this code?

Output: Spam
What will be output of following codes?
1) x = "global“
def f1():
print("x inside :", x)
f1()
print("x outside:", x)
Output: x inside : global
x outside: global
2) x = "global“
def f1():
x=x*2
print(x)
f1()
Output: Error
3) def f1():
y = "local“
f1()
print(y)
Output: Error
4) def f1():
y = "local“
print(y)
f1()
Output: local
5) x = "global“
def f1():
global x
y = "local“
x=x*2
print(x)
print(y)
f1()
Output: global global
local
6) x=5
def f1():
x = 10
print(“ x=", x)
f1()
print(“x=", x)
Output: x=10
x=5

7) def f1():
x=5
def f2():
nonlocal x
x = 10
print(“x in f2=", x)
f2()
print(“x in f1=:", x)
f1()
Output: x in f2 : 10
x in f1 : 10
Factory Functions/ Closure functions
 A function that creates and returns another function
 Ex:1) def maker(N):
def action(X): # Make and return action
return X **N
return action
f 1= maker(2)
f2=f1(3)
print(f2)
print(f1(4))
 Output: 9
16
 “maker” makes object “action”, and returns “action” without running it.
 f1 contain object “action”. So calling f1() means calling action()
 Factory functions are sometimes used by programs that need to
generate event handlers in response to conditions at runtime.
 Ex: 2) def f1(a,b):
def f2(x,y):
print("Inside function2")
print(x)
print(y)
def f3(p,q):
print("Inside function3")
print(p)
print(q) Output: Inside function1
1
return f3
2
print("Inside function1") Inside function2
print(a) 3
print(b) 4
return f2 Inside function3
5
f4=f1(1,2)
6
f5=f4(3,4)
f5(5,6)
• Here, f4 contain object of f2, so calling f4 means calling f2.
• Similarly, f5 contain object of f3, so calling f5 means calling f3.

Output: Inside function1


1
2
Inside function2
3
4
Inside function3
5
6
 Ex: 2) def f1(a,b):
Output: Inside function1
print("Inside function1")
1
print(a) 2
print(b) Inside function2
def f2(x,y): 3
print("Inside function2") 4
Inside function3
print(x)
5
print(y) 6
def f3(p,q):
print("Inside function3")
print(p)
print(q)
return f3
return f2
f4=f1(1,2)
f5=f4(3,4)
f5(5,6)
 Ex: 2) def f1(a,b):
def f2(x,y):
print("Inside function2")
print(x)
print(y)
def f3(p,q):
print("Inside function3")
print(p)
print(q) Output:
Inside function2
return f3
3
return f2 4
print("Inside function1") Inside function3
print(a) 5
print(b) 6
f4=f1(1,2)
f5=f4(3,4)
f5(5,6)
Argument passing
 All parameters (arguments) in the Python language are passed
by reference.
 Immutable arguments are effectively passed “by value.”
 Objects such as integers and strings are passed by object reference
instead of by copying, but because you can’t change immutable objects
in place anyhow, the effect is much like making a copy.
 Ex: def f(a):
print(a)
b = 88
f(b)
print(b)
Output: 88
88
 Mutable arguments are effectively passed “by pointer.”
 Objects such as lists and dictionaries are also passed by object reference,
which is similar to the way C passes arrays as pointers—mutable objects
can be changed in place in the function.
 Ex: def change( l2 ):
l2.append([1,2,3,4])
print ("Values inside the function: ", l2 )
return
l1 = [10,20,30]
change( l1 )
print ("Values outside the function: ", l1 )

 Output: Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
 Here, we are maintaining reference of the passed object and
appending values in the same object.
 So, appending in l2 means appending in l1 also
 Ex: def change( l2 ):
l2 = [1,2,3,4]
print ("Values inside the function: ", l2 )
return
l1 = [10,20,30]
change( l1 )
print ("Values outside the function: ", l1 )

 Output: Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]
 Here, argument is being passed by reference and the reference
is being overwritten inside the called function.
 The parameter l2 is local to the function change. Changing l2
within the function does not affect l1
Function Arguments
 You can call a function by using the following types of formal
arguments:
 Required arguments/positional arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
 Required arguments: are the arguments passed to a
function in correct positional order (from left to right).
 Here, the number of arguments in the function call should
match exactly with the function definition.
 Ex: def f(a, b, c):
print(a, b, c)
f(1, 2, 3)
Output: 1 2 3
 Here, we pass by position—a is matched to 1, b is matched
to 2, and so on
 To call the function which is having arguments, you
definitely need to pass the arguments, otherwise it gives a
syntax error
 Ex:
def printme( str ):
print str
printme()
Output: error

 The above example contains function which requires 1


parameter. In the main program code, function is called
without passing a parameter
 Keyword arguments : When you use keyword arguments
in a function call, the caller identifies the arguments by the
parameter name.
 Keyword arguments allow us to match by name, instead of
by position
 This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
 Ex: 1) def f(a, b, c):
print(a, b, c)
f(c=3, b=2, a=1)
Output: 1 2 3
 Keywords typically have two roles in Python:
1. They make your calls a bit more self-documenting : For
example, a call of this form:
func(name='Bob', age=40, job='dev')
is much more meaningful than a call with three values
separated by commas, especially in larger programs—the
keywords serve as labels for the data in the call.
2. The major use of keywords occurs in conjunction with
default keyword
 Ex: 2) def printme( str ):
print(str )
printme( str = "My string")

Output: My string
 Ex: 3)

def stud(rno, nm, course):


print("Roll no=",rno,"name=",nm,"course=",course)
stud(nm='aaa', rno=10,course='bbb')

 Output: Roll no= 10 name= aaa course= bbb


 Default argument: A default argument is an argument
that assumes a default value if a value is not provided in the
function call for that argument.
 Ex:
def fun1(a, b=2, c=3):
print(a, b, c)
fun1(1)

Output: 123
 Here f() is a function that requires one argument and two
defaults.
 When we call this function, we must provide a value for a,
either by position or by keyword
 However, providing values for b and c is optional.
If we don’t pass values to b and c, they take default
values as 2 and 3, respectively
 If we pass two values, only c gets its default value
 Ex: f(1,4)
Output: 1 4 3

 Keyword arguments and default arguments can be


combined :
 Ex: f(1, c=6)
Output: 126
 What will be output of following code?
def fun(spam, eggs, toast=0, ham=0):
print((spam, eggs, toast, ham))
fun(1, 2)
fun(1, ham=1, eggs=0)
fun(spam=1, eggs=0)
fun(toast=1, eggs=2, spam=3)
fun(1, 2, 3, 4)
Output: 1, 2, 0, 0
1, 0, 0, 1
1, 0, 0, 0
3, 2, 1, 0
1, 2, 3, 4
 What will be output of following code?

def printinfo( name, age = 15 ):


print( "Name: ", name)
print("Age ", age)

printinfo( age=500, name=“Mohseen" );


printinfo( name=“Mohseen" )

Output: Name: Mohseen


Age 50
Name: Mohseen
Age 15
 Variable Length Arguments: To process a function for
more arguments than you specified while defining the
function, variable-length arguments can be used.
 * and **, are designed to support functions that take
variable-length arguments
 Both can appear in either the function definition or a
function call
 The first use, in the function definition, collects
unmatched positional arguments into a tuple
 When the function is called, Python collects all the
positional arguments into a new tuple and assigns the
variable args to that tuple
 Because it is a normal tuple object, it can be indexed,
stepped through with a for loop etc.
 Ex: def f(*args): #see function10.py
print(args)
f()
f(1)
f(1, 2, 3, 4)

Output: ()
(1,)
(1, 2, 3, 4)
 The ** feature is similar, but it only works for keyword
arguments—it collects them into a new dictionary.
 ** form allows you to convert from keywords to dictionaries,
which you can then step through with keys calls, dictionary
iterators etc.
 It works roughly like dict(), but it returns the new dictionary
 Ex: def f(**args):
print(args)
f()
f(a=1, b=2)
f(1, 2)
Output: {}
{'a': 1, 'b': 2}
error
 Function definition can combine * and ** -
 Ex: def f(a, *pargs, **kargs):
print(a, pargs, kargs)
f(1, 2, 3, x=1, y=2)
output: 1 (2, 3) {'y': 2, 'x': 1}
 Here, 1 is passed to ‘a’ by position, 2 and 3 are collected into
the ‘pargs’ positional tuple, and x and y wind up in the
‘kargs’ keyword dictionary

 The second use, in the function call, we can use the *


syntax when we call a function, too.
 In this context, its meaning is the inverse of its meaning in
the function definition—it unpacks a collection of
arguments, rather than building a collection of arguments.
 Ex:1) def fun(a,b,c):
print(a,b,c)
l=[1,2,3]
d={'a':11,'c':33 ,'b':22}
Output: 1 2 3
fun(*l)
11 22 33
fun(**d)

2) def fun(a,b,c,d,e):
print(a,b,c,d,e)
l=[1,2,3]
l.append(4) Output: 1 2 3 4 5
l.append(5)
fun(*l)
lambda functions Or anonymous function
 anonymous function is defined without a name.
 While normal functions are defined using the def keyword,
anonymous functions are defined using the “lambda keyword.
 Syntax: lambda arguments: expression
 Lambda functions can have any number of arguments but only
one expression. The expression is evaluated and returned.
 Ex. mult = lambda x: x * 2
print(mult(5))
Output: 10
• Here, lambda x: x * 2 is the lambda function, x is the argument
and x * 2 is the expression that gets evaluated and returned.
 The above ex is nearly the same as -
def mult(x):
return x * 2
 We use lambda functions when we require a nameless
function for a short period of time.
 In Python, we generally use it as an argument to a higher-
order function (a function that takes in other functions
as arguments).
 Lambda functions are used along with built-in functions
like filter(), map() and reduce()
 Filter(): The filter() function takes in a function and a list
as its arguments.
 The function is called with all the items in the list and a
new list is returned which contains items for which the
function evaluates to True.
 To get new list, filter() must be wrapped in list()
 The filter() resembles a for loop but it is a built-in function
and faster.
 Ex: 1) # Program to filter out only the even items from a list
l1 = [1, 5, 4, 6, 8, 11, 3, 12]
l2 = list(filter(lambda x: (x%2 == 0) , l1))
print(l2)
Output: [4, 6, 8, 12]
2) l = range(-5, 5)
new = list(filter(lambda x: x < 0, l))
print(new)
Output: [-5, -4, -3, -2, -1]
 map(): The map() function in Python takes in a function and a
list.
 map() applies a function to all the items in an input list.
 If we want to pass all the list elements to a function one-by-one
and then collect the output, map() can be used.
 Ex: # Program to double each item in a list using map()
l = [1, 5, 4, 6, 8, 11, 3, 12]
l1 = list(map(lambda x: x * 2 , l))
print(l1)
Output: [2, 10, 8, 12, 16, 22, 6, 24]
2) What will be output of the following code and implement
it using map()
l = [1, 2, 3, 4, 5]
l = [1, 2, 3, 4, 5] s = []
s = list(map(lambda x: x**2, l))
for i in l:
print(s)
Output: [1,4,9,16,25]
s.append(i**2)
print(s)
 reduce(): Reduce is a really useful function for performing some
computation on a list and returning the result.
 Applies a rolling computation to sequential pairs of values in a list.
 reduce() is function from “functools” package.
 Ex: #program to compute the product of a list of integers.
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print(product)
# Output: 24
 Write the above program using for loop:
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
print(product)
 WAP to display powers of 2 using Anonymous
Function and without using anonymous function
[if n=5 then print 12 22 32 42 and 52 ]

 WAP to accept a list from user find numbers divisible


by thirteen using anonymous function
Programs
 WAP to convert decimal number into binary, octal and hexadecimal number
system using functions
 WAP to find the factors of a number
 Define a function that can receive two integral numbers in string form and
compute their sum and then print it in console.
 Define a function that can accept two strings as input and concatenate them
and then print it in console.
 Define a function that can accept two strings as input and print the string with
maximum length in console. If two strings have the same length, then the
function should print both strings line by line.(see fun_maxlen_string.py)
 Define a function which can print a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys.
 Define a function which can generate a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys. The
function should just print the keys only.
 Define a function which can generate a list where the values are square of
numbers between 1 and 20 (both included). Then the function needs to print
the first 5 elements in the list.
 Write a Python function to check whether a number is in a given range.

def test_range(n):
if n in range(3,9):
print( " %d is in the range"%n)
else :
print("The number is outside the given range.")
test_range(5)

 Write a program to generate and print another tuple whose values are
even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
t1=(1,2,3,4,5,6,7,8,9,10)
l=list() # or l=[ ]
for i in t1:
if t1[i]%2==0:
l.append(t1[i])
t2=tuple(l)
print(t2)
 Write a program which can filter() to make a list whose elements are
even number between 1 and 20 (both included).

even = filter(lambda x: x%2==0, range(1,21))


print(even)

 Write a program which can map() and filter() to make a list whose
elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
(see filt_map.py)

S-ar putea să vă placă și