3-2 CRT Python Examples
3-2 CRT Python Examples
Exercise: Write functions for basic math operations, factorial using recursion.
Higher-order functions
map(), filter(), reduce()
Function closures
Partial functions (functools.partial)
Exercise: Implement a closure that returns a function to multiply numbers by a fixed number.
Exercise: Create a Car class with attributes like brand, model, and year.
Exercise: Create a Vehicle class and extend it with Car and Bike classes.
Session 5: OOP - Encapsulation & Magic Methods
Exercise: Implement a class that represents a BankAccount with deposit and withdraw methods.
1. Functions in Python
Example 1: Email Validation Function
Method 1: Using Regular Expression
import re
def is_valid_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return bool(re.match(pattern, email))
print(is_valid_email("user@example.com")) # True
print(is_valid_email("invalid-email")) # False
at_index = email.index("@")
dot_index = email.rfind(".") # Last occurrence of '.'
return True
# Test cases
print(is_valid_email("user@example.com")) # True
print(is_valid_email("userexample.com")) # False
print(is_valid_email("@example.com")) # False
print(is_valid_email("user@.com")) # False
domain_parts = domain.split(".")
if any(not part for part in domain_parts):
return False # No empty sections in the domain
return True
# Test cases
print(is_valid_email("hello@domain.com")) # True
print(is_valid_email("user@domain")) # False
print(is_valid_email("user@domain.")) # False
print(is_valid_email("userdomain.com")) # False
usd_to_inr = 83.2
print(convert_currency(100, usd_to_inr)) # Converts 100 USD to INR
2. Advanced Functions
Example 1: Using map() for Temperature Conversion
celsius = [0, 10, 20, 30, 40]
discount_10 = discount(10)
print(discount_10(500)) # 450.0 (10% discount)
3. OOP - Basics
Example 1: Employee Class
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def show(self):
print(f"Employee Name: {self.name}, Salary: {self.salary}")
def display(self):
print(f"Student: {self.name}, Grade: {self.grade}")
s1 = Student("Alice", "A")
s1.display()
class SavingsAccount(BankAccount):
def add_interest(self):
interest = self.balance * 0.05
self.balance += interest
print(f"Interest added: {interest}, New Balance: {self.balance}")
acc = SavingsAccount(1000)
acc.deposit(500)
acc.add_interest()
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance
One base (parent) class and one derived (child) class.
def show_details(self):
print(f"Employee: {self.name}, Salary: {self.salary}")
def show_manager(self):
print(f"Manager of {self.department} Department")
2. Multiple Inheritance
A child class inherits from multiple parent classes.
car = HybridCar()
car.show_details()
3. Multilevel Inheritance
A chain of inheritance where a class inherits from another derived class.
class Parent(Grandparent):
def parent_job(self):
return "Engineer"
c = Child()
print(c.family_name()) # Inherited from Grandparent
print(c.parent_job()) # Inherited from Parent
print(c.child_hobby()) # Defined in Child class
4. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class Dog(Animal):
def sound(self):
return "Barks"
class Cat(Animal):
def sound(self):
return "Meows"
d = Dog()
c = Cat()
print(d.sound()) # Barks
print(c.sound()) # Meows
5. Hybrid Inheritance
A combination of two or more types of inheritance.
class Student(Person):
def student_id(self, id):
return f"Student ID: {id}"
class Teacher(Person):
def teacher_subject(self, subject):
return f"Teaches: {subject}"
ta = TeachingAssistant("John")
print(ta.name) # Inherited from Person
print(ta.student_id(101)) # Inherited from Student
print(ta.teacher_subject("Math")) # Inherited from Teacher
print(ta.role()) # Own method
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
atm = ATM(1000)
atm.withdraw(500)
def __str__(self):
return f"Book: {self.title} by {self.author}"
6.OOP - Abstraction
Abstraction is one of the core principles of Object-Oriented Programming (OOP) that focuses on
hiding implementation details and exposing only the necessary functionality. In Python,
abstraction is achieved using abstract classes and methods with the ABC (Abstract Base Class)
module.
# Abstract class
class ATM(ABC):
@abstractmethod
def deposit(self, amount):
pass
@abstractmethod
def withdraw(self, amount):
pass
# Concrete class
class BankATM(ATM):
def __init__(self, balance):
self.balance = balance
# Abstract class
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
# Concrete class - Car
class Car(Vehicle):
def start(self):
print("Car engine started with key ignition.")
def stop(self):
print("Car stopped using brakes.")
def stop(self):
print("Bike stopped using disc brakes.")
my_bike = Bike()
my_bike.start()
my_bike.stop()
Why Abstraction?
The Vehicle class defines a template (start() and stop()).
Every vehicle (Car, Bike) implements these methods in its own way.
Hides unnecessary details—users just need to know how to start/stop without worrying
about the internals.
Key Takeaways
1. Abstract classes define a blueprint without implementing complete functionality.
2. Concrete classes (subclasses) must provide implementations for the abstract methods.
3. Real-world applications include ATM machines, vehicles, payment gateways, and more.
4. Encapsulation & abstraction work together to create secure and scalable applications.
def __iter__(self):
return self
def __next__(self):
if self.a > self.limit:
raise StopIteration
value = self.a
self.a, self.b = self.b, self.a + self.b
return value
fib = Fibonacci(50)
for num in fib:
print(num, end=" ")
@log_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
@requires_auth
def dashboard(user):
print(f"Welcome, {user}!")
dashboard("guest")
dashboard("admin")
(math_utils.py)
(main.py)
import math_utils
print(math_utils.add(5, 3))
print(math_utils.subtract(10, 4))
Example 2: Installing & Using an External Package (requests)
Objective
Use the requests package to send an HTTP request and retrieve data from an API.
Explanation
1. requests.get(url) → Sends a GET request to the provided URL.
2. response.status_code → Returns the HTTP status code (e.g., 200 for success).
3. response.json() → Converts the response data into a Python dictionary (if JSON format).
Expected Output
Status Code: 200
Response JSON: {'current_user_url': 'https://api.github.com/user', ...}
This demonstrates how to use external packages for API communication in Python.
def validate_age(age):
if age < 18:
raise AgeError("Age must be 18 or above")
print("Age is valid")
try:
validate_age(15)
except AgeError as e:
print(e)
# Example Usage
account = BankAccount(500) # Account with $500 balance
print(account.withdraw(200)) # Successful withdrawal
print(account.withdraw(400)) # Raises InsufficientBalanceError
Explanation:
1. Creating a Custom Exception (InsufficientBalanceError):
o It inherits from Exception.
o The second withdrawal raises the custom exception and displays an error
message.
This ensures that the banking system prevents overdrawing and provides clear feedback to users.
11. File Handling
Example 1: Writing & Reading from a File
with open("data.txt", "w") as f:
f.write("Hello, World!")
Reading a File
with open("example.txt", "r") as file:
content = file.read() # Reads entire file
print(content)
Other reading methods:
.readline() – Reads one line at a time
.readlines() – Reads all lines into a list
Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, this is a test file.\n")
file.write("File handling in Python is easy!")
"w" mode overwrites the file if it exists.
Appending to a File
with open("example.txt", "a") as file:
file.write("\nThis line is appended.")
"a" mode adds content without deleting existing data.
Checking If a File Exists (Before Opening)
import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")
Implementation
import os
# File name
file_name = "attendance.txt"
Scenario Workflow
1. Checks if attendance.txt exists:
o If not, it creates a new file with a header.
Example Output
Attendance file not found. Creating a new one.
--- Attendance Records ---
EmployeeID, Date, Status