Documente Academic
Documente Profesional
Documente Cultură
...
else:
def func(): # Or else this way
...
...
func() # Call the version selected and built
(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)
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)
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: 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: My string
Ex: 3)
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
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
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 ]
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).
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)