YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
- Python Programming & OOP Exercises
- 🧩 Notebook 1 — Class and Inheritance
- 🧮 Notebook 2 — Functions, Recursion, Lambda & Decorators
- 1️⃣ Mathematical Expression Evaluator
- 2️⃣ Recursive Fibonacci Sequence
- 3️⃣ Lambda Functions & Higher-Order Functions
- 4️⃣ Input Validation Using Decorators
- 🧰 Notebook 3 — Python Control Flow & Data Analysis
- 1️⃣ Calculator Using Match-Case
- 2️⃣ Number Pattern Generation
- 3️⃣ List Comparison & Analysis
- 4️⃣ Collatz Conjecture
- 🛠️ Technologies & Python Concepts
- 📋 General Coding Requirements
- 📂 Suggested Repository Structure
- 🚀 How to Run
- 🎓 Learning Outcomes
- 🔑 Keywords
- 📌 Project Summary
Python Programming & OOP Exercises
This repository contains three Jupyter Notebooks covering Python fundamentals, Object-Oriented Programming, recursion, functional programming, decorators, control flow, list comprehensions, and algorithmic problem solving.
The notebooks are designed as practical exercises with a focus on clean, readable, typed, documented, and PEP 8-compliant Python code.
📚 Repository Contents
The project is divided into three notebooks:
| Notebook | Main Topics |
|---|---|
01_OOP_Class_and_Inheritance.ipynb |
Abstract Classes, Inheritance, Encapsulation |
02_Functions_Recursion_Lambda_Decorators.ipynb |
Functions, Expression Parsing, Recursion, Lambda, Higher-Order Functions, Decorators |
03_Python_Control_Flow_and_Data_Analysis.ipynb |
Match-Case, Loops, List Comprehensions, Lists, Collatz Conjecture |
🧩 Notebook 1 — Class and Inheritance
🎯 Objective
The first notebook focuses on Object-Oriented Programming (OOP) concepts, particularly:
- Abstract classes
- Inheritance
- Encapsulation
- Private attributes
- Methods
- Properties
- Method overriding
- Type annotations
- Documentation
🏗️ Shape Class
An abstract Shape class is created as the base representation for geometric shapes.
The class provides an area() method that must be implemented by subclasses.
Conceptually:
Shape
│
└── Rectangle
The Shape class defines the expected interface while leaving the actual area calculation to the child class.
▭ Rectangle Class
Rectangle inherits from Shape and represents a rectangle using:
width
height
The dimensions are stored as private attributes:
self.__width
self.__height
The class implements:
Area
Area = width × height
Perimeter
Perimeter = 2 × (width + height)
🔐 Encapsulation
The notebook demonstrates how private attributes can prevent direct modification of internal object state.
Instead of exposing:
rect.__width
the class can provide controlled access through properties.
This allows code such as:
print(rect.width)
print(rect.height)
and controlled assignment such as:
rect.width = 10
rect.height = 20
while keeping the actual attributes private.
🧠 Concepts Demonstrated
Object-Oriented Programming
│
├── Classes
├── Inheritance
├── Abstraction
├── Encapsulation
├── Private Attributes
├── Properties
└── Method Overriding
🧮 Notebook 2 — Functions, Recursion, Lambda & Decorators
The second notebook contains four advanced Python exercises.
1️⃣ Mathematical Expression Evaluator
🎯 Objective
Implement:
evaluate_expression(expr)
to evaluate mathematical expressions containing:
+
-
*
/
(
)
without using:
eval()
or similar built-in expression evaluators.
⚙️ Supported Operations
The evaluator follows standard mathematical precedence:
Parentheses
↓
Multiplication / Division
↓
Addition / Subtraction
For example:
evaluate_expression("3+5*2-8/4")
produces:
10.0
because:
5 × 2 = 10
8 / 4 = 2
3 + 10 - 2 = 11
Note: If the intended expected result is
10.0, the example expression or expected output should be corrected; standard PEMDAS gives 11.0.
🔍 Parsing Approach
Instead of relying on eval(), the expression is processed manually.
The parser identifies:
- Numbers
- Operators
- Parentheses
- Operator precedence
A match-case statement can be used to apply the appropriate arithmetic operation.
🛡️ Error Handling
The implementation is expected to handle invalid input such as:
Invalid characters
Malformed expressions
Division by zero
Unbalanced parentheses
Missing operands
2️⃣ Recursive Fibonacci Sequence
🎯 Objective
Implement:
fibonacci_sequence(n)
which returns the first n Fibonacci numbers.
The Fibonacci sequence is defined as:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2)
Example:
fibonacci_sequence(10)
returns:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
🔁 Recursive Approach
The exercise demonstrates how a sequence can be constructed recursively.
A naive implementation repeatedly calculates the same Fibonacci values and becomes inefficient for large inputs.
Therefore, the notebook explores optimization techniques such as:
- Memoization
- Recursive sequence construction
- Avoiding unnecessary repeated calculations
✅ Input Validation
The function validates that:
n is an integer
n >= 0
Invalid values should raise an appropriate exception.
3️⃣ Lambda Functions & Higher-Order Functions
🎯 Objective
A list of student dictionaries is processed using functional programming techniques.
Example structure:
students = [
{"name": "Alice", "age": 20, "grade": 88},
{"name": "Bob", "age": 19, "grade": 75},
{"name": "Charlie", "age": 22, "grade": 93},
{"name": "David", "age": 21, "grade": 85},
]
The notebook performs three operations.
📊 Sorting
Students are sorted by grade in descending order using a lambda function.
Charlie → 93
Alice → 88
David → 85
Bob → 75
🔎 Filtering
The user provides a minimum age.
Students younger than that age are removed using:
filter()
with a lambda function.
For:
minimum age = 20
the result is:
Charlie
Alice
David
📈 Average Grade
The average grade is calculated from the filtered students using a combination of:
lambda
+
map/reduce
For the example:
93 + 88 + 85
---------------- = 88.666...
3
🧠 Functional Programming Concepts
Lambda
│
├── sorted()
│
├── filter()
│
├── map()
│
└── reduce()
4️⃣ Input Validation Using Decorators
🎯 Objective
Create a reusable decorator:
validate_inputs
that validates function arguments before the function executes.
It is applied to:
calculate_power(base, exponent)
⚙️ Validation Rules
Base
Must be:
int
or
float
Exponent
Must be:
integer
and:
exponent >= 0
Example
@validate_inputs
def calculate_power(base, exponent):
return base ** exponent
Valid:
calculate_power(2, 3)
Result:
8
Invalid:
calculate_power(5, -2)
or:
calculate_power("a", 2)
should raise:
ValueError
with an appropriate error message.
🔄 Decorator Flow
Function Call
│
▼
validate_inputs
│
├── Valid ──────► calculate_power()
│
└── Invalid ────► ValueError
🧰 Notebook 3 — Python Control Flow & Data Analysis
The third notebook focuses on fundamental Python programming techniques:
match-case- User input
- Loops
- Nested loops
- Lists
- List comprehensions
- Conditional logic
- Numerical algorithms
It contains four exercises.
1️⃣ Calculator Using Match-Case
🎯 Objective
Create a calculator that accepts:
First number
Second number
Operator
Supported operators:
+
-
*
/
%
The operation is selected using Python's:
match-case
statement.
Example
Enter the first number: 10
Enter the second number: 5
Enter an operator: /
Result: 2.0
🛡️ Error Handling
The calculator handles:
Division by zero
Error: Cannot divide by zero.
Invalid operator
Error: Invalid operator.
Invalid numerical input
The program should also prevent crashes when the user enters non-numeric values.
2️⃣ Number Pattern Generation
🎯 Objective
Generate a sequential number pattern based on a user-provided n.
The implementation must use nested for loops.
For:
n = 10
the expected pattern is:
1
2 3
4 5 6
7 8 9 10
🔄 Pattern Logic
The program progressively increases the number of elements in each row.
Conceptually:
Row 1 → 1 number
Row 2 → 2 numbers
Row 3 → 3 numbers
Row 4 → 4 numbers
...
The process stops when adding another number would exceed n.
3️⃣ List Comparison & Analysis
🎯 Objective
Given two integer lists:
list_a = [1, 2, 3, 4]
list_b = [3, 4, 5, 6]
the program calculates:
- Common elements
- Elements unique to
list_a - Elements unique to
list_b - Sum of absolute differences between corresponding elements
📊 Example
Common Elements
[3, 4]
Unique to list_a
[1, 2]
Unique to list_b
[5, 6]
📐 Sum of Differences
Corresponding elements are compared:
|1 - 3| = 2
|2 - 4| = 2
|3 - 5| = 2
|4 - 6| = 2
Therefore:
2 + 2 + 2 + 2 = 8
Result:
Sum of differences: 8
📌 Requirements
The implementation uses:
list comprehensions
instead of sets.
It also handles lists with different lengths by comparing elements only up to the length of the shorter list.
The original lists remain unchanged.
4️⃣ Collatz Conjecture
🎯 Objective
Generate the Collatz sequence for a positive integer using a while loop.
The rules are:
Even number
n → n / 2
Odd number
n → 3n + 1
The process continues until:
n = 1
Example
Input:
6
Output:
[6, 3, 10, 5, 16, 8, 4, 2, 1]
🔄 Algorithm
Input n
│
▼
Is n > 0?
│
├── No → Ask again
│
└── Yes
│
▼
Add n to list
│
▼
n == 1?
/ \
Yes No
│ │
▼ ▼
Stop Is n even?
│
┌────┴────┐
│ │
Yes No
│ │
n/2 3n+1
│ │
└────┬────┘
│
▼
Repeat
🛠️ Technologies & Python Concepts
The notebooks use standard Python functionality and do not require external machine-learning frameworks.
Core Python
- Python 3
- Variables
- Data types
- Input/output
- Conditional statements
- Loops
- Lists
- Dictionaries
- List comprehensions
- Exception handling
Object-Oriented Programming
- Classes
- Inheritance
- Abstraction
- Encapsulation
- Private attributes
- Properties
- Method overriding
Functional Programming
- Lambda expressions
map()filter()reduce()- Higher-order functions
sorted()
Advanced Python
- Decorators
- Recursion
- Memoization
- Type annotations
- Docstrings
- PEP 8
📋 General Coding Requirements
All three notebooks follow the provided coding requirements.
Type Annotations
Variables and function parameters/return values should use Python's typing system where appropriate.
Example:
def calculate_power(base: float, exponent: int) -> float:
...
Docstrings
Classes and public methods/functions include descriptive triple-quoted docstrings.
Example:
def fibonacci_sequence(n: int) -> list[int]:
"""Return the first n Fibonacci numbers."""
Comments
Multi-line comments are used where they improve understanding of:
- Algorithms
- Parsing logic
- Recursion
- Validation
- Control flow
Comments are intended to explain why something is being done rather than simply repeating the code.
Code Quality
The implementations aim to follow:
PEP 8
│
├── Readability
├── Consistent naming
├── Type annotations
├── Documentation
├── Error handling
└── Maintainability
📂 Suggested Repository Structure
Python-Programming-Exercises/
│
├── README.md
│
├── notebooks/
│ │
│ ├── 01_OOP_Class_and_Inheritance.ipynb
│ │
│ ├── 02_Functions_Recursion_Lambda_Decorators.ipynb
│ │
│ └── 03_Control_Flow_and_Algorithms.ipynb
│
└── requirements.txt
🚀 How to Run
Clone the repository:
git clone <repository-url>
cd Python-Programming-Exercises
Install Jupyter Notebook if needed:
pip install notebook
Start Jupyter:
jupyter notebook
Then open the notebooks from:
notebooks/
Alternatively, the notebooks can be opened directly using JupyterLab, Google Colab, or VS Code.
🎓 Learning Outcomes
After completing these notebooks, the following concepts are covered:
Python Fundamentals
│
├── Variables & Input
├── Conditions
├── Loops
├── Lists & Dictionaries
│
▼
Functions
│
├── Normal Functions
├── Recursion
├── Lambda
├── Higher-Order Functions
└── Decorators
│
▼
Object-Oriented Programming
│
├── Classes
├── Inheritance
├── Abstraction
└── Encapsulation
│
▼
Algorithmic Thinking
│
├── Expression Parsing
├── Fibonacci
├── Pattern Generation
├── List Analysis
└── Collatz Conjecture
🔑 Keywords
Python
Python Programming
OOP
Object-Oriented Programming
Classes
Inheritance
Abstraction
Encapsulation
Private Attributes
Functions
Recursion
Fibonacci
Lambda Functions
Higher-Order Functions
Decorators
Input Validation
Match-Case
List Comprehension
Loops
Nested Loops
Expression Evaluation
PEMDAS
Algorithms
Collatz Conjecture
Type Annotations
Docstrings
PEP 8
Jupyter Notebook
📌 Project Summary
Python Programming & OOP Exercises is a collection of three practical notebooks designed to demonstrate Python programming from fundamental concepts to more advanced programming techniques.
The project progresses from:
Python Fundamentals
↓
Control Flow & Algorithms
↓
Functions & Recursion
↓
Functional Programming
↓
Decorators
↓
Object-Oriented Programming
↓
Clean & Maintainable Python
Together, the three notebooks provide hands-on practice in Python problem solving, OOP, functional programming, recursion, decorators, algorithms, and software development best practices.