Python B2 Practical

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

# Function with exception handling

def divide_numbers(a, b):


try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
return None

# Base class with inheritance


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

def make_sound(self):
pass

# Derived class inheriting from Animal


class Dog(Animal):
def make_sound(self):
return "Woof!"

# Derived class inheriting from Animal


class Cat(Animal):
def make_sound(self):
return "Meow!"

# Demonstrate functions, objects, and exception handling


def main():
# Function and exception handling
result = divide_numbers(10, 2)
if result is not None:
print(f"Division result: {result}")

result = divide_numbers(10, 0)

# Classes and objects


my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")

# Inheritance and polymorphism


animals = [my_dog, my_cat]

for animal in animals:


print(f"{animal.name} says: {animal.make_sound()}")

if __name__ == "__main__":
main()

You might also like