Python Unit 3
Python Unit 3
Functional Programming
Unit: 3
Course Details
(B Tech 2nd Sem /1st Year)
• Map
• Filter
• Reduce
• Comprehensions
• Immutability
• Closures and Decorators
• Generators
• Co-routines, iterators
• Declarative programming
After you have read and studied this module, you should be able
to:
• To learn the Object Oriented Concepts in Python.
• To learn the concept of map, filter and reduce functions.
• To impart the knowledge of declarative programming.
• To learn the concepts of closures ,decorators and generators.
• To explore the knowledge of comprehensions and co routines.
• Operators
• Loop
• Method
• Variables
• Class , Objects
• Constructor
• Data Hiding
• Inheritance
• Polymorphism
• After you have read and studied this topic, you should be able
to
– Understand the concept of object oriented systems
Syntax:-
lambda argument_list : expression
Ex:- : represents beginning of the function
Argument List Expression
lambda x, y : x + y
sum = lambda x : x + 1
sum(5)
add = lambda x, y : x + y
add(5, 2)
OUTPUT
25,49,484,9409,2916,3844,5929,529,5329,3721
OUTPUT
193
OUTPUT
5,7,97,77,23,73,61
Syntax
The general syntax of list comprehensions is −
[expr for element in iterable if condition]
Above is equivalent to −
for element in iterable:
if condition:
expr
A better and faster way to write the above code is through list
comprehension.
Output
>>> [i for i in range(10) if i % 2 ==0] [0, 2, 4, 6, 8]
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Output :
[4, 16, 36, 64, 100]
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24,
26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46,
48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68,
70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90,
92, 94, 96, 98]
Output:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even',
'Odd', 'Even', 'Odd']
Output:
['h', 'e', 'l', 'l', 'o’]
>>> hello_letters = []
>>> for letter in 'hello':
>>> hello_letters.append(letter)
Output:
[[1, 3, 5, 7], [2, 4, 6, 8]]
Let's see how to create a dictionary from [1, 2, 3, 4, 5] and [a, b, c, d, e].
# keys
>>> keys = ['a', 'b', 'c', 'd', 'e’]
# values values = [1, 2, 3, 4, 5]
# creating a dict from the above lists
>>> dictionary = {key: value for (key, value) in zip(keys, values)}
>>> print(dictionary)
Output:
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
• In python, the string data types are immutable. Which means a string
value cannot be updated. We can verify this by trying to update a part of
the string which will led us to an error.
When we run the above program we get to see that N and N also
point to the same location
def outerfunc(x):
def innerfunc():
print(x)
innerfunc()
outerfunc(7)
OUTPUT
7
def outerfunc(x):
def innerfunc():
print(x)
return innerfunc #Return the object instead of
calling the function
OUTPUT
myfunc=outerfunc(7) 7
myfunc()
27-07-2021 (Problem Solving using Advanced Python) Unit No: III 42
CLOSURE
• The point to note here is that instead of calling innerfunc() here, we
returned it (the object).
• Once we’ve defined outerfunc(), we call it with the argument 7 and
store it in variable myfunc()
• when we call myfunc next, how does it remember that ‘x’ is 7?
• A Python3 closure is when some data gets attached to the code.
• So, this value is remembered even when the variable goes out of
scope, or the function is removed from the namespace.
def say_hi():
return 'hello there'
decorate = uppercase_decorator(say_hi)
decorate()
Output:
‘HELLO THERE’
# call of decoratots
@uppercase_decorator
def say_hi():
return 'hello there‘
say_hi() Output:
‘HELLO THERE’
• To understand how this code works, we’ll start with the for-loop.
For each item in the Python generator (each item that it yields), it
prints it, here.
• We begin with i=1. So, the first item that it yields is 1. The for-loop
prints this because of our print statement. Then, we increment I to
2.
• And the process follows until i is incremented to 11. Then, the
while loop’s condition becomes False.
• However, if you forget the statement to increment I, it results in an
infinite generator. This is because a Python generator needs to hold
only one value at a time.
• So, there are no memory restrictions.
(Problem Solving using Advanced Python) Unit No: III 53
07-2021
Working of Python Generator
def even(x):
while x%2==0:
yield 'Even’
for i in even(2):
print(i)
since 2 is even, 2%2 is always 0. Hence, the
Output: condition for while is always true.
Even
Even
Even
Even
Even
EvenEvenTraceback (most recent call last):File “<pyshell#24>”, line 2, in
<module>print(i)
KeyboardInterrupt (Problem Solving using Advanced Python) Unit No: III 54
07-2021
Working of Python Generator
Generator may contain more than one Python yield statement. This is comparable to
how a Python generator function may contain more than one return statement.
def my_gen(x):
while(x>0):
if x%2==0:
yield 'Even’
else:
yield 'Odd’
x-=1
for i in my_gen(7):
Output: Odd
print(i) Even
Odd
Even
Even
Odd
# sending inputs
corou.send(“XYZ")
corou.send("Dear XYZ")
Output:
Searching prefix:Dear Dear XYZ
OUTPUT
Searching prefix:Dear Dear XYZ Closing coroutine!!
• Lists, tuples, dictionaries, and sets are all iterable objects. They
are iterable containers which you can get an iterator from.
• All these objects have a iter() method which is used to get an
iterator:
Example:
Return an iterator from a tuple, and print each value:
mytuple = ("apple", "banana", "cherry")myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit)) OUTPUT
Apple
Banana
cherry
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output:
apple
banana
cherry
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x.
(Problem Solving using Advanced Python) Unit No: III 69
07-2021
Example
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter)) Output:-
1
2
3
4
5
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
myclass = MyNumbers() 15 16 17 18 19 20
myiter = iter(myclass)
for x in myiter:
print(x)
(Problem Solving using Advanced Python) Unit No: III 72
07-2021
Declarative Programming Language
Declarative Programming Languages focus on :
describing what should be computed - and avoid mentioning how that
computation should be performed. This means avoiding expressions of
control flow: loops and conditional statements are removed and replaced
with higher level constructs that describe the logic of what needs to be
computed.
The usual example of a declarative programming language is SQL. It lets
you define what data you want computed - and translates that efficiently
onto the database schema.
Python isn't a pure Declarative Language - but the same flexibility that
contributes to its sluggish speed can be be leveraged to create Domain
Specific API's that use the same principles.