We use different ways to organize code so it is easier to understand and reuse. Procedural and object-oriented are two common ways to do this.
0
0
Procedural vs object-oriented approach in Python
Introduction
When you want to write simple step-by-step instructions for a task.
When you want to group data and actions together to model real-world things.
When you need to reuse code by creating objects with shared behavior.
When your program grows bigger and you want to keep it organized.
When you want to make your code easier to change or add new features.
Syntax
Python
Procedural approach: def greet(name): print(f"Hello, {name}!") greet("Alice") Object-oriented approach: class Greeter: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") person = Greeter("Alice") person.greet()
Procedural code is a list of instructions or functions that run one after another.
Object-oriented code groups data and functions inside classes to create objects.
Examples
Procedural: A simple function adds two numbers and prints the result.
Python
def add(a, b): return a + b result = add(3, 4) print(result)
Object-oriented: A class has a method to add numbers. We create an object and call the method.
Python
class Calculator: def add(self, a, b): return a + b calc = Calculator() print(calc.add(3, 4))
Procedural: Just a function to greet someone by name.
Python
def greet(name): print(f"Hi, {name}!") greet("Bob")
Object-oriented: Person class stores name and has a greet method.
Python
class Person: def __init__(self, name): self.name = name def greet(self): print(f"Hi, {self.name}!") p = Person("Bob") p.greet()
Sample Program
This program shows both ways to greet someone. First, a simple function prints a greeting. Then, a class creates an object that prints a greeting.
Python
def procedural_greet(name): print(f"Hello from procedural, {name}!") class Greeter: def __init__(self, name): self.name = name def greet(self): print(f"Hello from object-oriented, {self.name}!") # Using procedural approach procedural_greet("Alice") # Using object-oriented approach person = Greeter("Alice") person.greet()
OutputSuccess
Important Notes
Procedural code is easier for small tasks but can get messy as programs grow.
Object-oriented code helps organize complex programs by bundling data and actions.
Both approaches can be mixed depending on what fits best.
Summary
Procedural programming uses functions and instructions step-by-step.
Object-oriented programming uses classes and objects to group data and behavior.
Choosing the right approach helps keep code clear and easy to maintain.