Programming Paradigms

Learn about the different programming paradigms available in Python.

Programming paradigms

A programming paradigm is a general approach to developing software. There aren’t usually fixed rules about what is or isn’t part of a particular paradigm, but, rather, there are certain patterns, characteristics, and models that tend to be used. This is especially true of Python since it supports several paradigms with no real dividing line between them. Here are the paradigms available in Python:

Procedural programming

Procedural programming is the most basic form of coding. Code is structured hierarchically into blocks (such as if statements, loops, and functions). It is arguably the simplest form of coding. However, it can be difficult to write and maintain large and complex software due to its lack of enforced structure.

Object-oriented programming

Object-oriented programming (OOP) structures code into objects. An object typically represents a real item in the program, such as a file or a window on the screen, and it groups all the data and code associated with that item within a single software structure. Software is structured according to the relationships and interactions between different objects. Since objects are encapsulated, with well-defined behavior, and capable of being tested independently, it is much easier to write complex systems using OOP.

Functional programming

Functional programming (FP) uses functions as the main building blocks. Unlike procedural programming, the functional paradigm treats functions as objects that can be passed as parameters, allowing new functions to be built dynamically as the program executes.

Functional programming tends to be more declarative than imperative – your code defines what you want to happen, rather than stating exactly how the code should do it. Some FP languages don’t even contain constructs, such as loops or if statements. However, Python is more general-purpose and allows you to mix programming styles very easily.

Example

In the following code widget, we perform the task of adding the elements in a list to obtain their sum. The list, named my_list, contains the values, 1,2,3, and 4. Each tab sums the values in my_list in a different programming paradigm for the purpose of comparison.

Press the RUN button to execute each piece of code.

def add_values(any_list):
sum = 0
for x in any_list:
sum += x
return sum
my_list = [1,2,3,4]
print(add_values(my_list))
Using procedural programming to add the elements in my_list