0% found this document useful (0 votes)
8 views

Python Programs All concepts

The document provides a comprehensive guide to Python programming basics, covering topics such as calculating the area of a circle, swapping numbers, checking for prime numbers, and finding factorials. It also includes sections on operators, conditional statements, loops, type casting, and operations on lists, tuples, and dictionaries. Each topic is accompanied by example questions and corresponding code solutions.

Uploaded by

Lohith Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Programs All concepts

The document provides a comprehensive guide to Python programming basics, covering topics such as calculating the area of a circle, swapping numbers, checking for prime numbers, and finding factorials. It also includes sections on operators, conditional statements, loops, type casting, and operations on lists, tuples, and dictionaries. Each topic is accompanied by example questions and corresponding code solutions.

Uploaded by

Lohith Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Python Basics

1. Calculate the Area of a Circle


o Question: Write a program to calculate the area of a circle given its radius.
o Answer:

import math

radius = float(input("Enter the radius of the circle: "))


area = math.pi * (radius ** 2)
print(f"The area of the circle is: {area}")

2. Swap Two Numbers


o Question: Write a program to swap two numbers without using a temporary
variable.
o Answer:

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))

x, y = y, x

print(f"After swapping: x = {x}, y = {y}")

3. Check Prime Number


o Question: Write a program to check if a number is prime.
o Answer:

num = int(input("Enter a number: "))


if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")

4. Factorial of a Number
o Question: Write a program to find the factorial of a number.
o Answer:

num = int(input("Enter a number: "))


factorial = 1

if num < 0:
print("Sorry, factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}")

5. Reverse a String
o Question: Write a program to reverse a given string.
o Answer:

string = input("Enter a string: ")


reversed_string = string[::-1]
print(f"Reversed string: {reversed_string}")

Operators

1. Arithmetic Operations
o Question: Write a program to perform basic arithmetic operations: addition,
subtraction, multiplication, and division.
o Answer:

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))

addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b if b != 0 else "undefined"

print(f"Addition: {addition}, Subtraction: {subtraction},


Multiplication: {multiplication}, Division: {division}")

2. Relational Operators
o Question: Write a program to compare two numbers using relational
operators.
o Answer:

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))

print(f"a > b: {a > b}")


print(f"a < b: {a < b}")
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
print(f"a >= b: {a >= b}")
print(f"a <= b: {a <= b}")
3. Logical Operators
o Question: Write a program to demonstrate the use of logical operators.
o Answer:

a = True
b = False

print(f"a and b: {a and b}")


print(f"a or b: {a or b}")
print(f"not a: {not a}")

4. Bitwise Operators
o Question: Write a program to demonstrate the use of bitwise operators.
o Answer:

a = 10 # 1010 in binary
b = 4 # 0100 in binary

print(f"a & b: {a & b}") # Bitwise AND


print(f"a | b: {a | b}") # Bitwise OR
print(f"a ^ b: {a ^ b}") # Bitwise XOR
print(f"~a: {~a}") # Bitwise NOT
print(f"a << 1: {a << 1}") # Left shift
print(f"a >> 1: {a >> 1}") # Right shift

5. Assignment Operators
o Question: Write a program to demonstrate the use of assignment operators.
o Answer:

a = 5
print(f"Initial value of a: {a}")

a += 3
print(f"a += 3: {a}")

a -= 2
print(f"a -= 2: {a}")

a *= 4
print(f"a *= 4: {a}")

a /= 2
print(f"a /= 2: {a}")

Conditional Statements

1. If Statement
o Question: Write a program to check if a number is positive.
o Answer:
num = float(input("Enter a number: "))
if num > 0:
print(f"{num} is positive")

2. If-Else Statement
o Question: Write a program to check if a number is odd or even.
o Answer:

num = int(input("Enter a number: "))


if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")

3. If-Elif-Else Statement
o Question: Write a program to check if a number is positive, negative, or zero.
o Answer:

num = float(input("Enter a number: "))


if num > 0:
print(f"{num} is positive")
elif num < 0:
print(f"{num} is negative")
else:
print(f"{num} is zero")

4. Nested If Statement
o Question: Write a program to determine the largest of three numbers using
nested if statements.
o Answer:

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

if a >= b:
if a >= c:
print(f"The largest number is {a}")
else:
print(f"The largest number is {c}")
else:
if b >= c:
print(f"The largest number is {b}")
else:
print(f"The largest number is {c}")

5. If-Else with Multiple Conditions


o Question: Write a program to check if a year is a leap year.
o Answer:

year = int(input("Enter a year: "))


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")

Loops

1. For Loop
o Question: Write a program to print the first 10 natural numbers using a for
loop.
o Answer:

for i in range(1, 11):


print(i)

2. Nested For Loop


o Question: Write a program to print a multiplication table up to 10 using
nested for loops.
o Answer:

for i in range(1, 11):


for j in range(1, 11):
print(f"{i} x {j} = {i * j}")
print("") # Blank line for better readability

3. For Loop with Break


o Question: Write a program to search for an element in a list. If found, print
"Element found" and stop searching.
o Answer:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


target = int(input("Enter a number to search: "))

for num in numbers:


if num == target:
print("Element found")
break
else:
print("Element not found")

4. For Loop with Continue


o Question: Write a program to print all numbers from 1 to 10 except 5 using a
for loop and continue statement.
o Answer:

for i in range(1, 11):


if i == 5:
continue
print(i)

5. For Loop with Pass


o Question: Write a program that iterates over a list of numbers and does
nothing if the number is even using the pass statement.
o Answer:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in numbers:


if num % 2 == 0:
pass
else:
print(f"Odd number: {num}")

While Loop

1. Simple While Loop


o Question: Write a program to print numbers from 1 to 5 using a while loop.
o Answer:

i = 1
while i <= 5:
print(i)
i += 1

2. While Loop with Break


o Question: Write a program to repeatedly take user input until the user enters
0.
o Answer:

while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
print(f"You entered: {num}")

3. While Loop with Continue


o Question: Write a program to print only odd numbers from 1 to 10 using a
while loop and continue statement.
o Answer:
i = 1
while i <= 10:
if i % 2 == 0:
i += 1
continue
print(i)
i += 1

4. While Loop with Else


o Question: Write a program to search for an element in a list using a while
loop with an else statement.
o Answer:

numbers = [10, 20, 30, 40, 50]


i = 0
target = int(input("Enter the number to search: "))

while i < len(numbers):


if numbers[i] == target:
print("Element found")
break
i += 1
else:
print("Element not found")

5. While Loop for Factorial Calculation


o Question: Write a program to calculate the factorial of a number using a
while loop.
o Answer:

num = int(input("Enter a number: "))


factorial = 1
i = 1

while i <= num:


factorial *= i
i += 1

print(f"The factorial of {num} is {factorial}")

Type Casting

1. String to Integer Conversion


o Question: Write a program to convert a string containing a number into an
integer.
o Answer:

str_num = "100"
int_num = int(str_num)
print(f"String to integer: {int_num}")

2. Integer to Float Conversion


o Question: Write a program to convert an integer into a float.
o Answer:

int_num = 25
float_num = float(int_num)
print(f"Integer to float: {float_num}")

3. Float to String Conversion


o Question: Write a program to convert a float into a string.
o Answer:

float_num = 50.75
str_num = str(float_num)
print(f"Float to string: {str_num}")

4. List to Tuple Conversion


o Question: Write a program to convert a list into a tuple.
o Answer:

my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(f"List to tuple: {my_tuple}")

5. String to List Conversion


o Question: Write a program to convert a string into a list of characters.
o Answer:

my_string = "Hello"
my_list = list(my_string)
print(f"String to list: {my_list}")

List Operations

1. List Append
o Question: Write a program to append an element to a list.
o Answer:

my_list = [1, 2, 3]
my_list.append(4)
print(f"List after append: {my_list}")
2. List Insert
o Question: Write a program to insert an element at the second position in a list.
o Answer:

my_list = [1, 2, 3]
my_list.insert(1, "Hello")
print(f"List after insert: {my_list}")

3. Nested List
o Question: Write a program to create a nested list and access an element from
it.
o Answer:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


print(f"Element at nested_list[1][2]: {nested_list[1][2]}")

4. List Pop
o Question: Write a program to remove and return the last element from a list
using pop().
o Answer:

my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop()
print(f"Popped element: {popped_element}")
print(f"List after pop: {my_list}")

5. List with For Loop


o Question: Write a program to iterate over a list using a for loop and print
each element.
o Answer:

my_list = [10, 20, 30, 40, 50]


for element in my_list:
print(element)

Tuple Operations

1. Tuple Creation
o Question: Write a program to create a tuple and print its elements.
o Answer:

my_tuple = (1, 2, 3, 4, 5)
print(f"My tuple: {my_tuple}")
2. Tuple Operations
o Question: Write a program to perform concatenation and repetition operations
on tuples.
o Answer:

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

concatenated_tuple = tuple1 + tuple2


repeated_tuple = tuple1 * 2

print(f"Concatenated tuple: {concatenated_tuple}")


print(f"Repeated tuple: {repeated_tuple}")

3. Tuple with For Loop


o Question: Write a program to iterate over a tuple using a for loop and print
each element.
o Answer:

my_tuple = ('a', 'b', 'c', 'd')


for element in my_tuple:
print(element)

4. Tuple Indexing
o Question: Write a program to access elements from a tuple using positive and
negative indexing.
o Answer:

my_tuple = (10, 20, 30, 40, 50)


print(f"Element at index 1: {my_tuple[1]}")
print(f"Element at index -1: {my_tuple[-1]}")

Dictionary Operations

1. Dictionary Creation and Access


o Question: Write a program to create a dictionary and access its elements.
o Answer:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}


print(f"Name: {my_dict['name']}")
print(f"Age: {my_dict['age']}")
print(f"City: {my_dict['city']}")

2. Dictionary Insertion
o Question: Write a program to add a new key-value pair to an existing
dictionary.
o Answer:

my_dict = {'name': 'Alice', 'age': 25}


my_dict['city'] = 'New York'
print(f"Updated dictionary: {my_dict}")

3. Dictionary Deletion
o Question: Write a program to delete a key-value pair from a dictionary.
o Answer:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}


del my_dict['age']
print(f"Dictionary after deletion: {my_dict}")

4. Dictionary with For Loop


o Question: Write a program to iterate over a dictionary and print each key-
value pair.
o Answer:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}


for key, value in my_dict.items():
print(f"{key}: {value}")

5. Check Key in Dictionary


o Question: Write a program to check if a specific key exists in a dictionary.
o Answer:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}


key_to_check = 'age'

if key_to_check in my_dict:
print(f"'{key_to_check}' exists in the dictionary with
value: {my_dict[key_to_check]}")
else:
print(f"'{key_to_check}' does not exist in the
dictionary.")

Set Operations

1. Set Creation and Access


o Question: Write a program to create a set and print its elements.
o Answer:

my_set = {1, 2, 3, 4, 5}
print(f"My set: {my_set}")
2. Set Union and Intersection
o Question: Write a program to perform union and intersection operations on
two sets.
o Answer:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2)
intersection_set = set1.intersection(set2)

print(f"Union: {union_set}")
print(f"Intersection: {intersection_set}")

3. Set Difference
o Question: Write a program to find the difference between two sets.
o Answer:

set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 6}

difference_set = set1.difference(set2)

print(f"Difference: {difference_set}")

4. Set Symmetric Difference


o Question: Write a program to find the symmetric difference between two sets.
o Answer:

set1 = {1, 2, 3}
set2 = {2, 3, 4}

sym_diff = set1.symmetric_difference(set2)

print(f"Symmetric Difference: {sym_diff}")

5. Set Update
o Question: Write a program to update a set with another set using the
update() method.
o Answer:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

set1.update(set2)

print(f"Updated set: {set1}")


Functions

1. Function Definition
o Question: Write a simple function to calculate the square of a number.
o Answer:

def square(num):
return num * num

result = square(5)
print(f"Square of 5: {result}")

2. Function with Arguments


o Question: Write a function that takes two numbers and returns their sum.
o Answer:

def add(a, b):


return a + b

result = add(10, 20)


print(f"Sum: {result}")

3. Function with Default Arguments


o Question: Write a function that greets a person. If no name is provided, it
should greet with "Hello, World!".
o Answer:

def greet(name="World"):
print(f"Hello, {name}!")

greet() # Default greeting


greet("Alice") # Custom greeting

4. Function with Return Values


o Question: Write a function that returns the factorial of a given number.
o Answer:

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

result = factorial(5)
print(f"Factorial of 5: {result}")

5. Function with Variable Length Arguments


o Question: Write a function that takes a variable number of arguments and
returns their sum.
o Answer:

def sum_of_numbers(*args):
return sum(args)

result = sum_of_numbers(1, 2, 3, 4, 5)
print(f"Sum: {result}")

Exception Handling

1. Basic Try-Except
o Question: Write a program that handles division by zero using try-except.
o Answer:

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

2. Multiple Exceptions
o Question: Write a program that handles both ValueError and
ZeroDivisionError.
o Answer:

try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")

3. Finally Clause
o Question: Write a program that demonstrates the use of the finally clause.
o Answer:

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute.")

4. Custom Exception
o Question: Write a program that raises a custom exception if a number is
negative.
o Answer:

class NegativeNumberError(Exception):
pass

def check_positive(number):
if number < 0:
raise NegativeNumberError("Negative number detected!")
return number

try:
check_positive(-5)
except NegativeNumberError as e:
print(e)

5. Raise Exception
o Question: Write a program that raises a ValueError if the input is not an
integer.
o Answer:

def check_integer(value):
if not isinstance(value, int):
raise ValueError("Input is not an integer!")
return value

try:
check_integer("abc")
except ValueError as e:
print(e)

File Handling

1. File Read
o Question: Write a program to read the content of a text file and print it.
o Answer:

with open('example.txt', 'r') as file:


content = file.read()
print(content)

2. File Write
o Question: Write a program to write a string to a text file.
o Answer:

with open('example.txt', 'w') as file:


file.write("Hello, World!")
3. File Append
o Question: Write a program to append a string to an existing text file.
o Answer:

with open('example.txt', 'a') as file:


file.write("\nAppended text.")

4. File Read Line by Line


o Question: Write a program to read a file line by line and print each line.
o Answer:

with open('example.txt', 'r') as file:


for line in file:
print(line, end='')

5. File Handling with Exception


o Question: Write a program to handle file not found exception while trying to
open a file.
o Answer:

try:
with open('non_existent_file

Classes and Objects

1. Basic Class
o Question: Write a class Person with attributes name and age. Create an object
and print its attributes.
o Answer:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Alice", 30)


print(f"Name: {person.name}")
print(f"Age: {person.age}")

2. Class with Method


o Question: Write a class Circle with a method to calculate the area of the
circle.
o Answer:
class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius * self.radius

circle = Circle(5)
print(f"Area of circle: {circle.area()}")

3. Encapsulation
o Question: Write a class BankAccount with private attributes balance.
Provide methods to deposit and withdraw money.
o Answer:

class BankAccount:
def __init__(self):
self.__balance = 0

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if self.__balance >= amount:
self.__balance -= amount
return amount
else:
return "Insufficient balance"

def get_balance(self):
return self.__balance

account = BankAccount()
account.deposit(100)
print(f"Balance: {account.get_balance()}")
account.withdraw(50)
print(f"Balance: {account.get_balance()}")

4. Polymorphism
o Question: Write a program to demonstrate polymorphism with a method
named area in different classes.
o Answer:

class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth

def area(self):
return self.length * self.breadth

class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

shapes = [Rectangle(10, 5), Circle(7)]

for shape in shapes:


print(f"Area: {shape.area()}")

5. Inheritance (Single Inheritance)


o Question: Write a program to demonstrate single inheritance with a base class
Animal and a derived class Dog.
o Answer:

class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "Animal Sound"

class Dog(Animal):
def speak(self):
return "Bark"

dog = Dog("Buddy")
print(f"{dog.name} says {dog.speak()}")

6. Inheritance (Multiple Inheritance)


o Question: Write a program to demonstrate multiple inheritance with classes
Parent1, Parent2, and Child.
o Answer:

class Parent1:
def function1(self):
return "Function 1"

class Parent2:
def function2(self):
return "Function 2"

class Child(Parent1, Parent2):


pass

child = Child()
print(child.function1())
print(child.function2())

7. Inheritance (Multilevel Inheritance)


o Question: Write a program to demonstrate multilevel inheritance with classes
Grandparent, Parent, and Child.
o Answer:
class Grandparent:
def grandparent_function(self):
return "Grandparent Function"

class Parent(Grandparent):
def parent_function(self):
return "Parent Function"

class Child(Parent):
def child_function(self):
return "Child Function"

child = Child()
print(child.grandparent_function())
print(child.parent_function())
print(child.child_function())

8. Inheritance (Hierarchical Inheritance)


o Question: Write a program to demonstrate hierarchical inheritance with a base
class Vehicle and derived classes Car and Bike.
o Answer:

class Vehicle:
def __init__(self, make):
self.make = make

def info(self):
return f"Make: {self.make}"

class Car(Vehicle):
def car_function(self):
return "Car Function"

class Bike(Vehicle):
def bike_function(self):
return "Bike Function"

car = Car("Toyota")
bike = Bike("Yamaha")

print(car.info())
print(car.car_function())

print(bike.info())
print(bike.bike_function())

9. Inheritance (Hybrid Inheritance)


o Question: Write a program to demonstrate hybrid inheritance involving
multiple base and derived classes.
o Answer:

class Base1:
def base1_function(self):
return "Base1 Function"

class Base2:
def base2_function(self):
return "Base2 Function"

class Derived1(Base1, Base2):


def derived1_function(self):
return "Derived1 Function"

class Derived2(Derived1):
def derived2_function(self):
return "Derived2 Function"

derived = Derived2()
print(derived.base1_function())
print(derived.base2_function())
print(derived.derived1_function())
print(derived.derived2_function())

1. Single Inheritance

Example 1: Basic Inheritance

class Animal:
def sound(self):
return "Some sound"

class Dog(Animal):
def sound(self):
return "Bark"

dog = Dog()
print(dog.sound()) # Output: Bark

Example 2: Inheriting Methods

class Vehicle:
def start(self):
return "Vehicle started"

class Car(Vehicle):
def accelerate(self):
return "Car is accelerating"

car = Car()
print(car.start()) # Output: Vehicle started
print(car.accelerate()) # Output: Car is accelerating

Example 3: Overriding Methods


class Bird:
def fly(self):
return "Flying"

class Penguin(Bird):
def fly(self):
return "Cannot fly"

penguin = Penguin()
print(penguin.fly()) # Output: Cannot fly

Example 4: Using super()

class Person:
def greet(self):
return "Hello"

class Employee(Person):
def greet(self):
original_greet = super().greet()
return f"{original_greet}, I am an employee"

employee = Employee()
print(employee.greet()) # Output: Hello, I am an employee

Example 5: Real-world Example - Bank Account

class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance

def deposit(self, amount):


self.balance += amount
return self.balance

class SavingsAccount(Account):
def add_interest(self, rate):
self.balance += self.balance * rate
return self.balance

savings = SavingsAccount("John Doe", 1000)


savings.deposit(500)
print(savings.add_interest(0.05)) # Output: 1575.0

2. Multiple Inheritance

Example 1: Basic Multiple Inheritance

class Father:
def tall(self):
return "Tall"

class Mother:
def beautiful(self):
return "Beautiful"

class Child(Father, Mother):


pass

child = Child()
print(child.tall()) # Output: Tall
print(child.beautiful()) # Output: Beautiful

Example 2: Method Resolution Order (MRO)

class A:
def method(self):
return "A"

class B(A):
def method(self):
return "B"

class C(A):
def method(self):
return "C"

class D(B, C):


pass

d = D()
print(d.method()) # Output: B
print(D.mro()) # Output: [D, B, C, A, object]

Example 3: Inheriting from Multiple Parents

class Writer:
def write(self):
return "Writing"

class Painter:
def paint(self):
return "Painting"

class Artist(Writer, Painter):


pass

artist = Artist()
print(artist.write()) # Output: Writing
print(artist.paint()) # Output: Painting

Example 4: Diamond Problem and super()


class A:
def __init__(self):
print("A's init called")

class B(A):
def __init__(self):
super().__init__()
print("B's init called")

class C(A):
def __init__(self):
super().__init__()
print("C's init called")

class D(B, C):


def __init__(self):
super().__init__()
print("D's init called")

d = D()

Output:

csharp

A's init called


C's init called
B's init called
D's init called

Example 5: Real-world Example - Multi-skilled Worker

class Electrician:
def work(self):
return "Fixing electrical issues"

class Plumber:
def work(self):
return "Fixing plumbing issues"

class Handyman(Electrician, Plumber):


def work(self):
return f"{Electrician.work(self)}, {Plumber.work(self)}"

handyman = Handyman()
print(handyman.work()) # Output: Fixing electrical issues, Fixing plumbing
issues

3. Multilevel Inheritance

Example 1: Basic Multilevel Inheritance

class Animal:
def eat(self):
return "Eating"

class Mammal(Animal):
def drink(self):
return "Drinking"

class Dog(Mammal):
def bark(self):
return "Barking"

dog = Dog()
print(dog.eat()) # Output: Eating
print(dog.drink()) # Output: Drinking
print(dog.bark()) # Output: Barking

Example 2: Overriding in Multilevel Inheritance

class A:
def show(self):
return "A's show"

class B(A):
def show(self):
return "B's show"

class C(B):
def show(self):
return "C's show"

c = C()
print(c.show()) # Output: C's show

Example 3: Calling Parent Method with super()

class Vehicle:
def move(self):
return "Vehicle moving"

class Car(Vehicle):
def move(self):
return super().move() + " on road"

class SportsCar(Car):
def move(self):
return super().move() + " with speed"

sports_car = SportsCar()
print(sports_car.move()) # Output: Vehicle moving on road with speed

Example 4: Multilevel Inheritance with Init Method

class A:
def __init__(self):
print("A's init")

class B(A):
def __init__(self):
super().__init__()
print("B's init")

class C(B):
def __init__(self):
super().__init__()
print("C's init")

c = C()
# Output:
# A's init
# B's init
# C's init

Example 5: Real-world Example - Organization Hierarchy

class Employee:
def __init__(self, name):
self.name = name

class Manager(Employee):
def __init__(self, name, department):
super().__init__(name)
self.department = department

class Director(Manager):
def __init__(self, name, department, region):
super().__init__(name, department)
self.region = region

director = Director("Alice", "IT", "North America")


print(director.name) # Output: Alice
print(director.department) # Output: IT
print(director.region) # Output: North America

4. Hybrid Inheritance

Example 1: Combination of Single and Multiple Inheritance

class A:
def method_A(self):
return "A"

class B(A):
def method_B(self):
return "B"

class C(A):
def method_C(self):
return "C"
class D(B, C):
def method_D(self):
return "D"

d = D()
print(d.method_A()) # Output: A
print(d.method_B()) # Output: B
print(d.method_C()) # Output: C
print(d.method_D()) # Output: D

Example 2: Hybrid with Multiple Parents

class X:
def x_method(self):
return "Method from X"

class Y:
def y_method(self):
return "Method from Y"

class Z(X, Y):


def z_method(self):
return "Method from Z"

class A(Z):
def a_method(self):
return "Method from A"

a = A()
print(a.x_method()) # Output: Method from X
print(a.y_method()) # Output: Method from Y
print(a.z_method()) # Output: Method from Z
print(a.a_method()) # Output: Method from A

Example 3: Combining Hierarchical and Multiple Inheritance

class A:
def method_A(self):
return "A"

class B(A):
def method_B(self):
return "B"

class C(A):
def method_C(self):
return "C"

class D(B, C):


def method_D(self):
return "D"

class E(D):
def method_E(self):
return "E"
e = E()
print(e.method_A()) # Output: A
print(e.method_B()) # Output: B

4. Hybrid Inheritance (continued)

Example 4: Real-world Example - Educational Structure

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id

class Teacher(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id

class TeachingAssistant(Student, Teacher):


def __init__(self, name, age, student_id, employee_id):
Student.__init__(self, name, age, student_id)
Teacher.__init__(self, name, age, employee_id)

ta = TeachingAssistant("John Doe", 24, "S123", "T456")


print(f"Name: {ta.name}, Age: {ta.age}, Student ID: {ta.student_id},
Employee ID: {ta.employee_id}")
# Output: Name: John Doe, Age: 24, Student ID: S123, Employee ID: T456

Example 5: Complex Hybrid Structure

class Engine:
def engine_type(self):
return "V8"

class Car(Engine):
def wheels(self):
return 4

class Boat(Engine):
def propeller(self):
return 1

class AmphibiousVehicle(Car, Boat):


def vehicle_type(self):
return "Amphibious Vehicle"

vehicle = AmphibiousVehicle()
print(vehicle.engine_type()) # Output: V8
print(vehicle.wheels()) # Output: 4
print(vehicle.propeller()) # Output: 1
print(vehicle.vehicle_type()) # Output: Amphibious Vehicle

5. Hierarchical Inheritance

Example 1: Basic Hierarchical Inheritance

class Animal:
def sound(self):
return "Some sound"

class Dog(Animal):
def sound(self):
return "Bark"

class Cat(Animal):
def sound(self):
return "Meow"

dog = Dog()
cat = Cat()
print(dog.sound()) # Output: Bark
print(cat.sound()) # Output: Meow

Example 2: Shared Method in Parent Class

class Person:
def greet(self):
return "Hello!"

class Student(Person):
def study(self):
return "Studying"

class Teacher(Person):
def teach(self):
return "Teaching"

student = Student()
teacher = Teacher()
print(student.greet()) # Output: Hello!
print(student.study()) # Output: Studying
print(teacher.greet()) # Output: Hello!
print(teacher.teach()) # Output: Teaching

Example 3: Adding More Children

class Device:
def turn_on(self):
return "Device is now on"

class Phone(Device):
def call(self):
return "Calling"

class Laptop(Device):
def code(self):
return "Coding"

class Tablet(Device):
def draw(self):
return "Drawing"

phone = Phone()
laptop = Laptop()
tablet = Tablet()
print(phone.turn_on()) # Output: Device is now on
print(phone.call()) # Output: Calling
print(laptop.turn_on()) # Output: Device is now on
print(laptop.code()) # Output: Coding
print(tablet.turn_on()) # Output: Device is now on
print(tablet.draw()) # Output: Drawing

Example 4: Real-world Example - Employee Types

class Employee:
def __init__(self, name, emp_id):
self.name = name
self.emp_id = emp_id

def work(self):
return "Working"

class Developer(Employee):
def code(self):
return "Writing code"

class Designer(Employee):
def design(self):
return "Designing graphics"

class Manager(Employee):
def manage(self):
return "Managing team"

developer = Developer("Alice", "D001")


designer = Designer("Bob", "D002")
manager = Manager("Charlie", "M001")

print(developer.work()) # Output: Working


print(developer.code()) # Output: Writing code
print(designer.work()) # Output: Working
print(designer.design()) # Output: Designing graphics
print(manager.work()) # Output: Working
print(manager.manage()) # Output: Managing team

Example 5: Hierarchical Inheritance with Additional Methods


class Vehicle:
def start(self):
return "Starting engine"

class Car(Vehicle):
def drive(self):
return "Driving"

class Motorcycle(Vehicle):
def ride(self):
return "Riding"

car = Car()
motorcycle = Motorcycle()
print(car.start()) # Output: Starting engine
print(car.drive()) # Output: Driving
print(motorcycle.start()) # Output: Starting engine
print(motorcycle.ride()) # Output: Riding

6. Datetime Functions

Example 1: Getting Current Date and Time

from datetime import datetime

now = datetime.now()
print("Current Date and Time:", now)

Example 2: Formatting Date and Time

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date and Time:", formatted_date)

Example 3: Parsing Date Strings

from datetime import datetime

date_string = "2024-08-31 10:30:00"


date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed Date Object:", date_object)

Example 4: Date Arithmetic

from datetime import datetime, timedelta

now = datetime.now()
future_date = now + timedelta(days=10)
print("Current Date:", now)
print("Date 10 Days Later:", future_date)

Example 5: Real-world Example - Time Difference Calculation

from datetime import datetime

start_time = datetime(2024, 8, 31, 9, 0, 0)


end_time = datetime(2024, 8, 31, 17, 0, 0)
work_duration = end_time - start_time
print("Work Duration:", work_duration)

7. Iterator

Example 1: Custom Iterator Class

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

my_numbers = MyNumbers()
my_iter = iter(my_numbers)

print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3

Example 2: Iterating Over a String

my_string = "Hello"
my_iter = iter(my_string)

print(next(my_iter)) # Output: H
print(next(my_iter)) # Output: e
print(next(my_iter)) # Output: l

Example 3: Creating a Reverse Iterator

class Reverse:
def __init__(self, data):
self.data = data
self.index = len(data)

def __iter__(self):
return self

def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]

rev = Reverse('')
for char in rev:
print(char, end=" ") # Output: n o h t y P

Example 4: Real-world Example - Fibonacci Iterator

class Fibonacci:
def __init__(self, max):
self.max = max

def __iter__(self):
self.a, self.b = 0, 1
return self

def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib

fib_iter = iter(Fibonacci(10))
for num in fib_iter:
print(num, end=" ") # Output: 0 1 1 2 3 5 8

Example 5: Using iter() with Sentinel

with open('example.txt', 'r') as f:


for line in iter(f.readline, ''):
print(line, end="")

8. Generator

Example 1: Basic Generator Function

def simple_generator():
yield 1
yield 2
yield 3
for value in simple_generator():
print(value)

Output:

1
2
3

Example 2: Generator for Fibonacci Sequence

def fibonacci(max_value):
a, b = 0, 1
while a <= max_value:
yield a
a, b = b, a + b

for number in fibonacci(10):


print(number, end=" ") # Output: 0 1 1 2 3 5 8

Example 3: Infinite Generator

def infinite_sequence():
num = 0
while True:
yield num
num += 1

gen = infinite_sequence()
print(next(gen)) # Output: 0
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2

Example 4: Generator Expression

squares = (x * x for x in range(5))

for square in squares:


print(square)

Output:

0
1
4
9
16

Example 5: Real-world Example - Reading Large File


def read_large_file(file_path):
with open(file_path, 'r') as file:
while True:
data = file.readline()
if not data:
break
yield data

for line in read_large_file('large_file.txt'):


print(line, end="")

9. Decorator

Example 1: Basic Decorator

def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

Output:

vbnet

Something is happening before the function is called.


Hello!
Something is happening after the function is called.

Example 2: Decorator with Arguments

def my_decorator(func):
def wrapper(*args, **kwargs):
print("Arguments passed:", args, kwargs)
return func(*args, **kwargs)
return wrapper

@my_decorator
def add(a, b):
return a + b

print(add(3, 4)) # Output: Arguments passed: (3, 4) {}


# 7

Example 3: Chaining Decorators


def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper

def split_string_decorator(func):
def wrapper():
result = func()
return result.split()
return wrapper

@split_string_decorator
@uppercase_decorator
def say_hello():
return "hello world"

print(say_hello()) # Output: ['HELLO', 'WORLD']

Example 4: Real-world Example - Timing Function Execution

import time

def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
return result
return wrapper

@timer_decorator
def slow_function():
time.sleep(2)
print("Function complete")

slow_function()

Output:

sql

Function complete
Execution time: 2.000234603881836 seconds

Example 5: Caching Results with Decorator

def cache_decorator(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper

@cache_decorator
def slow_addition(a, b):
time.sleep(1)
return a + b

print(slow_addition(3, 4)) # Output: 7 (after 1 second)


print(slow_addition(3, 4)) # Output: 7 (almost instantly)

10. Deque (Double-Ended Queue)

Example 1: Basic Operations with Deque

from collections import deque

d = deque()

d.append(1)
d.append(2)
d.appendleft(3)

print(d) # Output: deque([3, 1, 2])

d.pop()
d.popleft()

print(d) # Output: deque([1])

Example 2: Rotating Elements in Deque

from collections import deque

d = deque([1, 2, 3, 4, 5])
d.rotate(2)

print(d) # Output: deque([4, 5, 1, 2, 3])

d.rotate(-1)

print(d) # Output: deque([5, 1, 2, 3, 4])

Example 3: Limiting Deque Size

from collections import deque

d = deque(maxlen=3)
d.append(1)
d.append(2)
d.append(3)

print(d) # Output: deque([1, 2, 3], maxlen=3)

d.append(4)
print(d) # Output: deque([2, 3, 4], maxlen=3)

Example 4: Real-world Example - Browser History

from collections import deque

class BrowserHistory:
def __init__(self, capacity=5):
self.history = deque(maxlen=capacity)

def visit(self, site):


self.history.append(site)
print(f"Visited {site}")

def back(self):
if self.history:
site = self.history.pop()
print(f"Back to {site}")
else:
print("No history")

browser = BrowserHistory()
browser.visit("google.com")
browser.visit("stackoverflow.com")
browser.visit("github.com")
browser.visit(".org")
browser.visit("reddit.com")
browser.visit("youtube.com") # This will remove "google.com" from history
browser.back() # Output: Back to youtube.com

Example 5: Implementing a Queue with Deque

from collections import deque

class Queue:
def __init__(self):
self.queue = deque()

def enqueue(self, item):


self.queue.append(item)

def dequeue(self):
if not self.is_empty():
return self.queue.popleft()
return "Queue is empty"

def is_empty(self):
return len(self.queue) == 0

q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue()) # Output: 1
print(q.dequeue()) # Output: 2
print(q.dequeue()) # Output: 3
print(q.dequeue()) # Output: Queue is empty

11. namedtuple

Example 1: Basic Usage of namedtuple

from collections import namedtuple

Point = namedtuple('Point', 'x y')


p = Point(1, 2)

print(p.x) # Output: 1
print(p.y) # Output: 2

Example 2: namedtuple with Default Values

from collections import namedtuple

Point = namedtuple('Point', 'x y z', defaults=[0, 0])


p1 = Point(1, 2)
p2 = Point(1, 2, 3)

print(p1) # Output: Point(x=1, y=2, z=0)


print(p2) # Output: Point(x=1, y=2, z=3)

Example 3: Unpacking namedtuple

from collections import namedtuple

Point = namedtuple('Point', 'x y z')


p = Point(1, 2, 3)

x, y, z = p
print(x, y, z) # Output: 1 2 3

Example 4: Real-world Example - Employee Record

from collections import namedtuple

Employee = namedtuple('Employee', 'name age department')

emp1 = Employee('Alice', 30, 'HR')


emp2 = Employee('Bob', 25, 'IT')
print(emp1) # Output: Employee(name='Alice', age=30, department='HR')
print(emp2) # Output: Employee(name='Bob', age=25, department='IT')

Example 5: Using namedtuple for 3D Coordinates

from collections import namedtuple

Coordinate = namedtuple('Coordinate', 'x y z')

point1 = Coordinate(3, 4, 5)
point2 = Coordinate(-1, 2, -3)

def euclidean_distance(p1, p2):


return ((p1.x - p2.x)**2 + (p1.y - p2.y)**2 + (p1.z - p2.z)**2) ** 0.5

print(euclidean_distance(point1, point2)) # Output: 8.774964387392123

12. ChainMap

Example 1: Basic Usage of ChainMap

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 3, 'c': 4}
chain = ChainMap(dict1, dict2)

print(chain['a']) # Output: 1
print(chain['b']) # Output: 2 (from dict1, since it appears first)
print(chain['c']) # Output: 4

Example 2: Updating ChainMap

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 3, 'c': 4}
chain = ChainMap(dict1, dict2)

chain['a'] = 10
chain['c'] = 40

print(dict1) # Output: {'a': 10, 'b': 2}


print(dict2) # Output: {'b': 3, 'c': 40}

Example 3: Adding a New Dictionary to ChainMap

from collections import ChainMap


dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5, 'e': 6}

chain = ChainMap(dict1, dict2)


chain = chain.new_child(dict3)

print(chain['d']) # Output: 5
print(chain['b']) # Output: 2 (from dict1, since it appears first)

Example 4: Real-world Example - Configurations Management

from collections import ChainMap

default_config = {'theme': 'light', 'language': 'EN', 'show_tips': True}


user_config = {'theme': 'dark', 'show_tips': False}

config = ChainMap(user_config, default_config)

print(config['theme']) # Output: dark (user preference overrides default)


print(config['language']) # Output: EN
print(config['show_tips']) # Output: False

Example 5: Merging Dictionaries with ChainMap

from collections import ChainMap

dict1 = {'x': 10, 'y': 20}


dict2 = {'y': 30, 'z': 40}
dict3 = {'z': 50, 'w': 60}

chain = ChainMap(dict1, dict2, dict3)


merged = dict(chain)

print(merged) # Output: {'x': 10, 'y': 20, 'z': 40, 'w': 60}

13. Counter

Example 1: Basic Counter Usage

from collections import Counter

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(data)

print(counter) # Output: Counter({4: 4, 3: 3, 2: 2, 1: 1})

Example 2: Counting Characters in a String

from collections import Counter


string = "abracadabra"
counter = Counter(string)

print(counter) # Output: Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

Example 3: Finding the Most Common Elements

from collections import Counter

data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']


counter = Counter(data)

print(counter.most_common(2)) # Output: [('apple', 3), ('banana', 2)]

Example 4: Real-world Example - Word Frequency in Text

from collections import Counter

text = "the quick brown fox jumps over the lazy dog the quick brown fox"
words = text.split()
counter = Counter(words)

print(counter) # Output: Counter({'the': 3, 'quick': 2, 'brown': 2, ...})

Example 5: Subtracting Counters

from collections import Counter

inventory = Counter(apples=10, oranges=5, bananas=7)


sold = Counter(apples=4, oranges=1, bananas=6)

inventory.subtract(sold)
print(inventory) # Output: Counter({'apples': 6, 'oranges': 4, 'bananas':
1})

14. OrderedDict

Example 1: Maintaining Insertion Order

from collections import OrderedDict

od = OrderedDict()
od['one'] = 1
od['two'] = 2
od['three'] = 3

print(od) # Output: OrderedDict([('one', 1), ('two', 2), ('three', 3)])


Example 2: Comparing OrderedDicts

from collections import OrderedDict

od1 = OrderedDict({'a': 1, 'b': 2, 'c': 3})


od2 = OrderedDict({'a': 1, 'c': 3, 'b': 2})

print(od1 == od2) # Output: False (order matters)

Example 3: Reordering OrderedDict

from collections import OrderedDict

od = OrderedDict({'one': 1, 'two': 2, 'three': 3})


od.move_to_end('one')

print(od) # Output: OrderedDict([('two', 2), ('three', 3), ('one', 1)])

Example 4: Real-world Example - LRU Cache

from collections import OrderedDict

class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity

def get(self, key: int) -> int:


if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]

def put(self, key: int, value: int) -> None:


if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)

lru_cache = LRUCache(2)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
print(lru_cache.get(1)) # Output: 1
lru_cache.put(3, 3)
print(lru_cache.get(2)) # Output: -1 (evicted)

Example 5: Sorting an OrderedDict

from collections import OrderedDict


od = OrderedDict({'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2})
sorted_od = OrderedDict(sorted(od.items(), key=lambda t: t[1]))

print(sorted_od) # Output: OrderedDict([('pear', 1), ('orange', 2),


('banana', 3), ('apple', 4)])

15. defaultdict

Example 1: defaultdict with List

from collections import defaultdict

d = defaultdict(list)

d['fruits'].append('apple')
d['fruits'].append('banana')

print(d) # Output: defaultdict(<class 'list'>, {'fruits': ['apple',


'banana']})

Example 2: defaultdict with int for Counting

from collections import defaultdict

word_count = defaultdict(int)
text = "hello world hello hello world"

for word in text.split():


word_count[word] += 1

print(word_count) # Output: defaultdict(<class 'int'>, {'hello': 3,


'world': 2})

Example 3: Grouping Items by Key

from collections import defaultdict

names = [('John', 'A'), ('Jane', 'B'), ('Jack', 'A'), ('Jill', 'B')]


grade_group = defaultdict(list)

for name, grade in names:


grade_group[grade].append(name)

print(grade_group) # Output: defaultdict(<class 'list'>, {'A': ['John',


'Jack'], 'B': ['Jane', 'Jill']})

Example 4: Real-world Example - Creating an Adjacency List


from collections import defaultdict

edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D')]


adjacency_list = defaultdict(list)

for start, end in edges:


adjacency_list[start].append(end)

print(adjacency_list) # Output: defaultdict(<class 'list'>, {'A': ['B',


'C'], 'B': ['D'], 'C': ['D']})

Example 5: defaultdict with a Custom Factory Function

from collections import defaultdict

def default_factory():
return "Unknown"

city_country = defaultdict(default_factory)
city_country['Paris'] = 'France'
city_country['Berlin'] = 'Germany'

print(city_country['Paris']) # Output: France


print(city_country['London']) # Output: Unknown

16. Datetime Functions

Example 1: Getting Current Date and Time

from datetime import datetime

current_datetime = datetime.now()
print(current_datetime) # Output: e.g., 2024-08-31 14:25:32.123456

Example 2: Formatting Dates

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: e.g., 2024-08-31 14:30:00

Example 3: Parsing Strings into Dates

from datetime import datetime

date_str = "2024-08-31 14:30:00"


parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed_date) # Output: 2024-08-31 14:30:00
Example 4: Calculating Time Differences

from datetime import datetime, timedelta

now = datetime.now()
future_date = now + timedelta(days=5)
difference = future_date - now

print(f"Days until future date: {difference.days}") # Output: 5

Example 5: Real-world Example - Deadline Calculation

from datetime import datetime, timedelta

def calculate_deadline(start_date_str, days_to_add):


start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
deadline = start_date + timedelta(days=days_to_add)
return deadline.strftime("%Y-%m-%d")

start_date = "2024-08-31"
print(calculate_deadline(start_date, 7)) # Output: 2024-09-07

17. Iterator

Example 1: Creating a Custom Iterator

class Counter:
def __init__(self, start, end):
self.current = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.current > self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1

counter = Counter(1, 5)
for number in counter:
print(number) # Output: 1, 2, 3, 4, 5

Example 2: Implementing a Reverse Iterator

class Reverse:
def __init__(self, data):
self.data = data
self.index = len(data)

def __iter__(self):
return self

def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]

rev = Reverse('')
for char in rev:
print(char) # Output: n o h t y P

Example 3: Iterating Over a Dictionary

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:


print(key, my_dict[key]) # Output: a 1, b 2, c 3

Example 4: Real-world Example - File Line Iterator

class FileLineIterator:
def __init__(self, file_name):
self.file = open(file_name, 'r')

def __iter__(self):
return self

def __next__(self):
line = self.file.readline()
if not line:
self.file.close()
raise StopIteration
return line.strip()

file_iter = FileLineIterator('sample.txt')
for line in file_iter:
print(line)

Example 5: Using Iterator to Iterate Over Two Lists Simultaneously

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

iter1 = iter(list1)
iter2 = iter(list2)

for _ in range(len(list1)):
print(next(iter1), next(iter2)) # Output: (1, 'a'), (2, 'b'), (3, 'c')
18. Multilevel Inheritance

Example 1: Basic Multilevel Inheritance

class Grandparent:
def __init__(self):
print("Grandparent Constructor")

class Parent(Grandparent):
def __init__(self):
super().__init__()
print("Parent Constructor")

class Child(Parent):
def __init__(self):
super().__init__()
print("Child Constructor")

child = Child()

Output:

Grandparent Constructor
Parent Constructor
Child Constructor

Example 2: Overriding Methods in Multilevel Inheritance

class A:
def show(self):
print("A")

class B(A):
def show(self):
print("B")

class C(B):
def show(self):
print("C")

obj = C()
obj.show() # Output: C

Example 3: Calling Parent Class Methods in Multilevel Inheritance

class Animal:
def sound(self):
print("Animal makes sound")

class Mammal(Animal):
def sound(self):
super().sound()
print("Mammal makes sound")

class Dog(Mammal):
def sound(self):
super().sound()
print("Dog barks")

dog = Dog()
dog.sound()

Output:

Animal makes sound


Mammal makes sound
Dog barks

Example 4: Real-world Example - Company Hierarchy

class Company:
def __init__(self, name):
self.name = name

class Department(Company):
def __init__(self, name, department_name):
super().__init__(name)
self.department_name = department_name

class Employee(Department):
def __init__(self, name, department_name, employee_name):
super().__init__(name, department_name)
self.employee_name = employee_name

def get_details(self):
return f"Employee: {self.employee_name}, Department:
{self.department_name}, Company: {self.name}"

emp = Employee("TechCorp", "IT", "Alice")


print(emp.get_details()) # Output: Employee: Alice, Department: IT,
Company: TechCorp

Example 5: Multilevel Inheritance with Init Method

class Base:
def __init__(self, name):
self.name = name
print("Base class constructor")

class Intermediate(Base):
def __init__(self, name, age):
super().__init__(name)
self.age = age
print("Intermediate class constructor")
class Derived(Intermediate):
def __init__(self, name, age, role):
super().__init__(name, age)
self.role = role
print("Derived class constructor")

obj = Derived("Alice", 30, "Developer")

Output:

Base class constructor

8. Ordered Dictionary

Example 1: Preserving Insertion Order

from collections import OrderedDict

# Creating an OrderedDict
order_dict = OrderedDict()

# Adding items
order_dict['apple'] = 2
order_dict['banana'] = 3
order_dict['orange'] = 1

# Iterating over the OrderedDict


for key, value in order_dict.items():
print(key, value)

Example 2: Comparing Two Dictionaries

from collections import OrderedDict

# Two OrderedDicts with different insertion orders


dict1 = OrderedDict([('apple', 2), ('banana', 3), ('orange', 1)])
dict2 = OrderedDict([('orange', 1), ('banana', 3), ('apple', 2)])

# Comparing them
print(dict1 == dict2) # False, order matters

Example 3: Move Elements to the End or Start

from collections import OrderedDict

# Creating an OrderedDict
order_dict = OrderedDict([('apple', 2), ('banana', 3), ('orange', 1)])
# Moving 'apple' to the end
order_dict.move_to_end('apple')

print(order_dict) # Output: OrderedDict([('banana', 3), ('orange', 1),


('apple', 2)])

Example 4: Implementing a Simple LRU Cache

from collections import OrderedDict

class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity

def get(self, key):


if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1

def put(self, key, value):


if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)

# Usage
lru = LRUCache(2)
lru.put(1, 1)
lru.put(2, 2)
print(lru.get(1)) # returns 1
lru.put(3, 3) # evicts key 2
print(lru.get(2)) # returns -1

Example 5: Maintaining a Sorted Dictionary

from collections import OrderedDict

# Dictionary with unsorted keys


unsorted_dict = {'banana': 3, 'apple': 2, 'orange': 1}

# Creating an OrderedDict sorted by keys


sorted_dict = OrderedDict(sorted(unsorted_dict.items()))

print(sorted_dict) # Output: OrderedDict([('apple', 2), ('banana', 3),


('orange', 1)])

9. Default Dictionary

Example 1: Counting Frequencies


from collections import defaultdict

# Creating a defaultdict for counting


freq = defaultdict(int)

# Counting frequencies
for char in "banana":
freq[char] += 1

print(freq) # Output: defaultdict(<class 'int'>, {'b': 1, 'a': 3, 'n': 2})

Example 2: Grouping Items

from collections import defaultdict

# Creating a defaultdict for grouping


grouped = defaultdict(list)

# Grouping items
items = [('apple', 2), ('banana', 3), ('apple', 5)]
for key, value in items:
grouped[key].append(value)

print(grouped) # Output: defaultdict(<class 'list'>, {'apple': [2, 5],


'banana': [3]})

Example 3: Building a Multi-Value Dictionary

from collections import defaultdict

# Creating a defaultdict
multi_dict = defaultdict(set)

# Adding multiple values to a key


multi_dict['fruit'].add('apple')
multi_dict['fruit'].add('banana')

print(multi_dict) # Output: defaultdict(<class 'set'>, {'fruit':


{'banana', 'apple'}})

Example 4: Missing Key Handling

from collections import defaultdict

# Creating a defaultdict with default value of 0


zero_dict = defaultdict(lambda: 0)

# Accessing a missing key


print(zero_dict['missing']) # Output: 0

Example 5: Accumulating Results


from collections import defaultdict

# Creating a defaultdict for accumulating results


accum = defaultdict(int)

# Simulating a series of operations


transactions = [("apple", 10), ("banana", 5), ("apple", -3)]
for fruit, amount in transactions:
accum[fruit] += amount

print(accum) # Output: defaultdict(<class 'int'>, {'apple': 7, 'banana':


5})

You might also like