Programming Paradigms: Using Python

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Programming

Paradigms
Using Python
Programming Paradigms

• Imperative: Program state change

• Procedural: Procedural calls to modularize code

• Object Oriented: Entity state and behavior

• Functional: Everything is a math equation


Example: Computing square
of each item in the list

• [ 1, 2, 3, 4, 5 ]

Ans:

• [1, 4, 9, 16, 25 ]
Imperative

temp_list = [ 1, 2, 3, 4, 5]

result_list = [ ]

for item in temp_list:

result_list.append ( item ** 2 )

——————————————————-

result_list = [ 1, 4, 9, 16, 25 ]
Procedural
temp_list = [ 1, 2, 3, 4, 5]

def compute_square( arg_list ):

result_list = [ ]

for item in arg_list:

result_list.append ( item ** 2 )

return result_list

result_list = compute_square ( temp_list)

——————————————————-

result_list = [ 1, 4, 9, 16, 25 ]
Object Oriented
class ChangeList(object):

def __init__(self, any_list):

self.any_list = any_list

def do_square(self):

self.square = [ ]

for x in any_list:

square.append( x**2)

temp_list_object = ChangeList(my_list)

temp_list_object.do_square( )

print(temp_list_object.square)

——————————————————-

[ 1, 4, 9, 16, 25 ]
Functional

import functools

temp_list = [1, 2, 3, 4, 5]

square = lambda x: x**2

result_list = functools.reduce(square, temp_list)

print (result_list)

——————————————————-

[ 1, 4, 9, 16, 25 ]
Functions and Functional
Paradigms

for x in l:

function_name(x)

map ( function_name, l )

You might also like