Programming paradigms
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
What is a paradigm?
- A programming paradigm is a style of organising a program.
- The same problem can be solved in different styles.
- Python lets you mix several paradigms in one program.
Imperative and procedural
- Imperative code is a list of steps that change the program's state.
- It says how to do something, step by step (loops, assignments).
- Procedural style groups those steps into reusable procedures and functions.
def total(nums):
result = 0
for n in nums:
result = result + n
return result
print(total([2, 4, 6]))
Object-oriented
- Object-oriented code bundles data and the methods that act on it into objects.
- You model the problem as a set of classes that talk to each other.
- It suits large programs because each class is a self-contained part.
class Counter:
def __init__(self):
self.count = 0
def add(self):
self.count = self.count + 1
c = Counter()
c.add()
c.add()
print(c.count)
Declarative
- Declarative code says what you want, not how to compute it.
- The language or library works out the steps for you.
- Examples: a database query (SQL), or a Python list comprehension.
nums = [1, 2, 3, 4, 5]
print(sum(nums)) # say WHAT: the total
print([n * n for n in nums]) # a list comprehension
Low-level
- Low-level code is close to the machine: assembly and machine code.
- The CPU runs it directly, so it is fast but hard to write.
- High-level languages like Python are translated down to it before running.
Now you try
- Each task solves a small problem in a different paradigm.
- Press Check answer to test your code.
Procedural style. Write sum_list(nums) that uses a loop and an accumulator to add up the list and return the total.
Click Run to see the output here.
Declarative style. Write evens(nums) that returns a list of the even numbers, using a single list comprehension [... for ... if ...].
Click Run to see the output here.
Object-oriented style. Write a class Bag whose __init__(self, items) stores a list, and whose method total(self) returns the sum of those items.
Click Run to see the output here.