Python Programs All concepts
Python Programs All concepts
import math
x, y = y, x
4. Factorial of a Number
o Question: Write a program to find the factorial of a number.
o Answer:
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:
Operators
1. Arithmetic Operations
o Question: Write a program to perform basic arithmetic operations: addition,
subtraction, multiplication, and division.
o Answer:
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b if b != 0 else "undefined"
2. Relational Operators
o Question: Write a program to compare two numbers using relational
operators.
o Answer:
a = True
b = False
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
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:
3. If-Elif-Else Statement
o Question: Write a program to check if a number is positive, negative, or zero.
o Answer:
4. Nested If Statement
o Question: Write a program to determine the largest of three numbers using
nested if statements.
o Answer:
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}")
Loops
1. For Loop
o Question: Write a program to print the first 10 natural numbers using a for
loop.
o Answer:
While Loop
i = 1
while i <= 5:
print(i)
i += 1
while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
print(f"You entered: {num}")
Type Casting
str_num = "100"
int_num = int(str_num)
print(f"String to integer: {int_num}")
int_num = 25
float_num = float(int_num)
print(f"Integer to float: {float_num}")
float_num = 50.75
str_num = str(float_num)
print(f"Float to string: {str_num}")
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(f"List to tuple: {my_tuple}")
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:
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}")
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)
4. Tuple Indexing
o Question: Write a program to access elements from a tuple using positive and
negative indexing.
o Answer:
Dictionary Operations
2. Dictionary Insertion
o Question: Write a program to add a new key-value pair to an existing
dictionary.
o Answer:
3. Dictionary Deletion
o Question: Write a program to delete a key-value pair from a dictionary.
o Answer:
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
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}")
set1 = {1, 2, 3}
set2 = {2, 3, 4}
sym_diff = set1.symmetric_difference(set2)
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)
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}")
def greet(name="World"):
print(f"Hello, {name}!")
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}")
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:
2. File Write
o Question: Write a program to write a string to a text file.
o Answer:
try:
with open('non_existent_file
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
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 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
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()}")
class Parent1:
def function1(self):
return "Function 1"
class Parent2:
def function2(self):
return "Function 2"
child = Child()
print(child.function1())
print(child.function2())
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())
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())
class Base1:
def base1_function(self):
return "Base1 Function"
class Base2:
def base2_function(self):
return "Base2 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
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Output: Bark
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
class Penguin(Bird):
def fly(self):
return "Cannot fly"
penguin = Penguin()
print(penguin.fly()) # Output: Cannot fly
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
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
class SavingsAccount(Account):
def add_interest(self, rate):
self.balance += self.balance * rate
return self.balance
2. Multiple Inheritance
class Father:
def tall(self):
return "Tall"
class Mother:
def beautiful(self):
return "Beautiful"
child = Child()
print(child.tall()) # Output: Tall
print(child.beautiful()) # Output: Beautiful
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B"
class C(A):
def method(self):
return "C"
d = D()
print(d.method()) # Output: B
print(D.mro()) # Output: [D, B, C, A, object]
class Writer:
def write(self):
return "Writing"
class Painter:
def paint(self):
return "Painting"
artist = Artist()
print(artist.write()) # Output: Writing
print(artist.paint()) # Output: Painting
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")
d = D()
Output:
csharp
class Electrician:
def work(self):
return "Fixing electrical issues"
class Plumber:
def work(self):
return "Fixing plumbing issues"
handyman = Handyman()
print(handyman.work()) # Output: Fixing electrical issues, Fixing plumbing
issues
3. 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
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
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
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
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
4. Hybrid 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
class X:
def x_method(self):
return "Method from X"
class Y:
def y_method(self):
return "Method from Y"
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
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 E(D):
def method_E(self):
return "E"
e = E()
print(e.method_A()) # Output: A
print(e.method_B()) # Output: B
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 Engine:
def engine_type(self):
return "V8"
class Car(Engine):
def wheels(self):
return 4
class Boat(Engine):
def propeller(self):
return 1
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
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
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
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
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"
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
now = datetime.now()
print("Current Date and Time:", now)
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date and Time:", formatted_date)
now = datetime.now()
future_date = now + timedelta(days=10)
print("Current Date:", now)
print("Date 10 Days Later:", future_date)
7. Iterator
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
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
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
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
8. Generator
def simple_generator():
yield 1
yield 2
yield 3
for value in simple_generator():
print(value)
Output:
1
2
3
def fibonacci(max_value):
a, b = 0, 1
while a <= max_value:
yield a
a, b = b, a + b
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
Output:
0
1
4
9
16
9. 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
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
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"
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
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
d = deque()
d.append(1)
d.append(2)
d.appendleft(3)
d.pop()
d.popleft()
d = deque([1, 2, 3, 4, 5])
d.rotate(2)
d.rotate(-1)
d = deque(maxlen=3)
d.append(1)
d.append(2)
d.append(3)
d.append(4)
print(d) # Output: deque([2, 3, 4], maxlen=3)
class BrowserHistory:
def __init__(self, capacity=5):
self.history = deque(maxlen=capacity)
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
class Queue:
def __init__(self):
self.queue = deque()
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
print(p.x) # Output: 1
print(p.y) # Output: 2
x, y, z = p
print(x, y, z) # Output: 1 2 3
point1 = Coordinate(3, 4, 5)
point2 = Coordinate(-1, 2, -3)
12. ChainMap
print(chain['a']) # Output: 1
print(chain['b']) # Output: 2 (from dict1, since it appears first)
print(chain['c']) # Output: 4
chain['a'] = 10
chain['c'] = 40
print(chain['d']) # Output: 5
print(chain['b']) # Output: 2 (from dict1, since it appears first)
print(merged) # Output: {'x': 10, 'y': 20, 'z': 40, 'w': 60}
13. Counter
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(data)
text = "the quick brown fox jumps over the lazy dog the quick brown fox"
words = text.split()
counter = Counter(words)
inventory.subtract(sold)
print(inventory) # Output: Counter({'apples': 6, 'oranges': 4, 'bananas':
1})
14. OrderedDict
od = OrderedDict()
od['one'] = 1
od['two'] = 2
od['three'] = 3
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
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)
15. defaultdict
d = defaultdict(list)
d['fruits'].append('apple')
d['fruits'].append('banana')
word_count = defaultdict(int)
text = "hello world hello hello world"
def default_factory():
return "Unknown"
city_country = defaultdict(default_factory)
city_country['Paris'] = 'France'
city_country['Berlin'] = 'Germany'
current_datetime = datetime.now()
print(current_datetime) # Output: e.g., 2024-08-31 14:25:32.123456
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
now = datetime.now()
future_date = now + timedelta(days=5)
difference = future_date - now
start_date = "2024-08-31"
print(calculate_deadline(start_date, 7)) # Output: 2024-09-07
17. 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
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
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)
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
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
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
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:
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}"
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")
Output:
8. Ordered Dictionary
# Creating an OrderedDict
order_dict = OrderedDict()
# Adding items
order_dict['apple'] = 2
order_dict['banana'] = 3
order_dict['orange'] = 1
# Comparing them
print(dict1 == dict2) # False, order matters
# Creating an OrderedDict
order_dict = OrderedDict([('apple', 2), ('banana', 3), ('orange', 1)])
# Moving 'apple' to the end
order_dict.move_to_end('apple')
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
# 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
9. Default Dictionary
# Counting frequencies
for char in "banana":
freq[char] += 1
# Grouping items
items = [('apple', 2), ('banana', 3), ('apple', 5)]
for key, value in items:
grouped[key].append(value)
# Creating a defaultdict
multi_dict = defaultdict(set)