How to code in Python (using Paradigms)
Tags: python, programming, machinelearning, tutorial
Published: 2023-02-15 23:50:27

## Introduction
 
Programming Paradigms are the different approaches to solving computational problems through programming.  

In this article, we will be talking about programming Paradigms, why they're an important part of programming, the different programming paradigms that can be applied using python, and how to apply them. 

## Programming Paradigms 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2zirg5vi90e31x83dr3t.png)

Before we delve into programming paradigms, it is crucial to understand the meaning of Paradigms in its basic form,  unrelated to computer science, paradigms are essentially the models, guidelines or patterns by which certain objectives are achieved, analogically, they can be likened to how [scaffolding](https://en.wikipedia.org/wiki/Scaffolding) serves as the basic structure for buildings.

[Programming Paradigms]("https://en.wikipedia.org/wiki/Programming_paradigm#Overview") are the different styles which a program can be written in a certain programming language, they are the different ways in which code in a given programming language (like Python, Java, JavaScript, etc) can be organised.

In simple words, every programming language has a special way (methodologies) in which it's code can be structured and run and these are called programming paradigms, some programming languages only support the use of one paradigm, these are called _single paradigm languages_ while others support multiple paradigms, these are called _multi paradigm languages_.

There are 2 core classifications of Programming Paradigms, and they are:
- **Imperative:** In this technique, the programmer specifies how to solve a particular program in the code, examples of paradigms that follow this technique include; _Procedural_ and _Object Oriented Programming_.


- **Declarative:** In this technique, the programmer only declares the problem to be solved without explicitly describing how it is to be solved, examples of paradigms that follow this technique are; _Functional Programming_,  _reactive programming_, etc

## Python Paradigms

As stated earlier, every programming language has it's paradigm style or styles(depending on it's architecture), for example, perhaps the most popular programming language in the imperative division is [C]("https://en.wikipedia.org/wiki/C_(programming_language")) which was designed as a single paradigm language(supporting only Imperative programming styles), on the other hand, [Haskell](https://en.wikipedia.org/wiki/Haskell), while being obscure, is a great example of a language which supports Declarative programming.

As stated earlier on, the focus of this article will be python and the paradigms it supports. Python is a multi paradigm language as it support procedural,  Functional, and Declarative paradigms. 

In this article we will explain Python's two most popular paradigms (Object Oriented Programming and Functional programming) and present their code implementations. 

### Functional Programming

In simple words, Functional programming is a programming paradigm which emphasizes on writing code in little reusable blocks called functions, rather than the changing of states, it takes in one or more inputs and performs computations on them based on a pre-written set of rules and then returns an output without changing any of the data outside the function. It is declarative by nature. 

**Here is an example of a simple function and its usage**

```
#defining the function
def add(x, y):
  ans = x+y
  return ans
  
```

```
#using the function
a = 2

b = 3

ans = add(a,b)

print(ans)

```

**Higher order functions**

Higher order functions are basically functions which have other functions passed as arguments, for example using our other example;
```
#defining a higher order function

def answer(func, x, y):
  res = func(x,y)
  print(res)
  

#using higher order functions
answer(add, a, b)
   

```

### Object Oriented Programming (OOPs)
Object Oriented Programming, is a programming paradigm which deals with code as objects; giving it properties and behaviours. For example, a house is an object with properties like; color, a door, roof, stairs, etc. 

In Object Oriented Programming, objects are defined with their properties and behaviours, now the interactions between the properties and behaviours of these objects is what creates the logic for a computer program. 

Analogically, you can think of Object Oriented Programming(OOPs) as [Lego bricks](https://en.wikipedia.org/wiki/Lego), combining the bricks in diffrent ways produces different objects, combining them in a certain way can get you a house, combining them in another way can get you a car, in the same manner, combining properties of objects in a certain way creates a logic in the code which generates a certain output. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vexrs920r11eu0bt05xv.jpg)

**Classes**
Classes are a crucial part of Object Oriented Programming, they are essentially a set of functions that define and construct the structure of objects, you can think of them as a blueprint for a building in the sense that they outline how a structure should be built.

**Magic Methods**
Magic methods(also called Dunder methods), they are essentially used to create customisation for objects in classes, they start and end with underscores.
 
_Code implementation_
 
```

 # Creating the class
class Pet(object):
    """Class object for a pet."""

    def __init__(self, species, name):
        """Initialise a Pet."""
        self.species = species
        self.name = name
        
    def __str__(self):
        """Output when printing an instance of a Pet."""
        return f"{self.species} named {self.name}"
        
     
# Creating an instance of the class
my_dog = Pet(species="dog",
             name="Breakthrough")
print (my_dog)
print (my_dog.name)
  
 ```
 Above we created a class for _pets_, created the magic methods _init & str_ which help in initialising instances of the class and parsing strings for output, respectively.
 
 **Object Functions**
 
 Objects can also have functions which provide certain behaviour for the objects.
 
  _code implementation_
  
  ```
 
 def change_name(self, new_name):
        """Change the name of your Pet."""
        self.name = new_name
        
# Using the change_name function
my_dog.change_name(new_name="Chivoma")
print (my_dog)
print (my_dog.name)
 
 ```
Above we created a  function which made it possible to change the name of the pet object.

**Inheritance**

This is another really interesting feature of OOPs. Inheritance makes it possible to inherit the behaviours and properties of a certain class and implement them in another class, this makes it possible to build classes on-top of each other. 

 _code implementation_

```
#creating class
class Dog(Pet):
    def __init__(self, name, breed):
        super().__init__(species="dog", name=name)
        self.breed = breed

    def __str__(self):
        return f"A {self.breed} dog named {self.name}"

#creating an instance of the class
Ariel = Dog(species="dog", breed="Great Dane", name="Ariel")
print (Ariel)

```

Above we created a class named _Dog_ which inherited from the _Pet_ class.


## Summary

In conclusion, Paradigms are crucial in designing the structure, organisation, flow, and logic of computer software and every programming language has paradigms it supports. A language can either support one paradigm (single paradigm) or more than one(multi paradigm).

Two of the most popular paradigms supported by Python are Functional Programming and Object Oriented Programming(OOPs). 

Functional Programming deals with writing code in little reusable blocks called functions rather than the changing of states, it takes in one or more inputs performs computation on them based on a pre-written set of rules and then returns an output without changing any of the data outside the function. It is declarative by nature.

On the other hand, Object Oriented Programming deals with code as objects; giving it properties and behaviours. For example, a house is an object with properties like; color, a door, roof, stairs, etc. 

Due to its vast application in AI and Data Science/Engineering, Python continues to grow in popularity, as such, it is important for developers to have a solid understanding of these programming paradigms in order to write efficient and maintainable code. 

By embracing functional programming and OOP principles, developers can create software that is scalable, modular, and easy to maintain, ensuring that their code is well-structured, optimised, and future-proof.