Mahmoud Ahmed

Posted on

# Python Programming Styles

While reading an article about a new version of PyTorch, my eyes stop on sentence

Intrinsically, there are two main characteristics of PyTorch that distinguish it from other deep learning frameworks:

• Imperative Programming
• Dynamic Computation Graphing

and want to explore more about Imperative programming and find it so pretty and clear but what about other programming styles? and can code them in python?
from here I started my search journey about python programming styles then share it here.

Initially, Python is a great language not for coding simplicity only but because it differs about other languages in limitations of coding styles, most of the other languages use just one coding style like which reduce flexibility for the programmer but in python, the programmer can many coding styles to achieve different effects.

Here's an overview of Python coding styles:

1.Procedural
tasks proceed a step at a time and you can imagine the program sequential flow, it mostly used for sequencing, selection, and modularization. more reading about them

``````def get_total(my_list):
total=0
for x in my_list:
total+=x

print(get_total([1,2,3,4,5]))
``````

2.Functional
it's like a math equation and any forms of state or mutable data are avoided, some developers say it as part of the procedural style, it supports solution-focused thinking (not what to do but what to accomplish). Therefore the academics teach functional languages as first programming languages and data scientists prefer it for recursion and lambda.

``````from functools import reduce

def sum_nums(a, b):
return a + b

print(reduce(lambda a, b: sum_nums(a,b), [1, 2, 3, 4, 5]))

``````

3.Imperative
computations are performed as a direct to change in the program state, it produces simple code and very useful in data structures manipulation.

``````total = 0
for x in my_list:
total += x
print(total)

``````

4.Object-oriented
it simplifies the code by using objects to model the real world and gives the programmer ability to reuse code and encapsulation allows to treat code as a black box, and inheritance make it easier to expand the functionality.

``````class list_opertaions(object):
def __init__(self, my_list):
self.my_list = my_list
self.total = 0

def get_total(self):
self.total = sum(self.my_list)

obj = list_opertaions(my_list)
obj.get_total()
print(obj.total)
``````