Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Python Programming Final Lab Notes - Jupyter Notebook

Uploaded by

21x01a6261
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Python Programming Final Lab Notes - Jupyter Notebook

Uploaded by

21x01a6261
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

Python Programming Practicals


1. Temperature conversion
2. Display Fibonacci series up to a limit
3. Find factorial of a number
4. Program to display the information-name, full address, mobile number, college name,
course, subjects.
5. Program to find the largest number among n given numbers
6. Program to find the sum of all prime numbers between 1-1000
7. Program that reads set of integers and displays first and second large numbers.
8. Program to print the sum of first n natural numbers.
9. Program to find the product of two matrices.
10. Program to find roots of a quadratic equation.
11. Write both recursive and non-recursive functions for the following: to find GCD of two
integers, to find the
factorial of a positive integer, to print Fibonacci sequence up to a given number.
12. Program that accepts a string as an argument and returns the number of vowel and
consonants the string
contains
13. Program that accepts two strings S1, S2 and find whether they are equal or not
14. Program to count the number of occurrences of character in a given string
15. Program to find whether a given string is palindrome or not.
16. Program to find all duplicates in the list.
17. WAP that combine list L1 and L2 int a dictionary
18. Program to read the list of numbers as L1 print the lists in reverse order without using
reverse functions.
19. Program to implement the inheritance
20. Program to implement the polymorphism.

1. Write a python Program for Temperature


Conversion

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 1/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [1]: def celsius_to_fahrenheit(celsius):


return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9

def celsius_to_kelvin(celsius):
return celsius + 273.15

#Kelvin is the base unit for temperature in the International System of Uni
def kelvin_to_celsius(kelvin):
return kelvin - 273.15

def fahrenheit_to_kelvin(fahrenheit):
celsius = fahrenheit_to_celsius(fahrenheit)
return celsius_to_kelvin(celsius)

def kelvin_to_fahrenheit(kelvin):
celsius = kelvin_to_celsius(kelvin)
return celsius_to_fahrenheit(celsius)

def main():
print("Temperature Conversion Menu")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Celsius to Kelvin")
print("4. Kelvin to Celsius")
print("5. Fahrenheit to Kelvin")
print("6. Kelvin to Fahrenheit")

choice = input("Enter your choice (1-6): ")

if choice in ['1', '2', '3', '4', '5', '6']:
temp = float(input("Enter the temperature: "))
if choice == '1':
result = celsius_to_fahrenheit(temp)
print(f"{temp}°C is equal to {result:.2f}°F")
elif choice == '2':
result = fahrenheit_to_celsius(temp)
print(f"{temp}°F is equal to {result:.2f}°C")
elif choice == '3':
result = celsius_to_kelvin(temp)
print(f"{temp}°C is equal to {result:.2f}K")
elif choice == '4':
result = kelvin_to_celsius(temp)
print(f"{temp}K is equal to {result:.2f}°C")
elif choice == '5':
result = fahrenheit_to_kelvin(temp)
print(f"{temp}°F is equal to {result:.2f}K")
elif choice == '6':
result = kelvin_to_fahrenheit(temp)
print(f"{temp}K is equal to {result:.2f}°F")
else:
print("Invalid choice. Please select a number between 1 and 6.")

if __name__ == "__main__":
main()

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 2/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

Temperature Conversion Menu


1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Celsius to Kelvin
4. Kelvin to Celsius
5. Fahrenheit to Kelvin
6. Kelvin to Fahrenheit
Enter your choice (1-6): 5
Enter the temperature: 35
35.0°F is equal to 274.82K

Breaking Down the Calculation


celsius * 9/5:

celsius: This is the input temperature in Celsius.

9/5: This is a constant ratio used in the conversion formula. In decimal form, it equals 1.8.

When you multiply the Celsius temperature by 9/5, you scale it to fit the Fahrenheit
temperature scale.

This step adjusts the size of the temperature difference to match Fahrenheit degrees.

+ 32:

After scaling the Celsius temperature, you add 32.

This adjustment aligns the scaled temperature with the Fahrenheit scale.

The Fahrenheit scale starts at a different point than the Celsius scale.

Adding 32 shifts the temperature to the correct position on the Fahrenheit scale.

2. Write a Python Program to Display


Fibonacci series up to a limit

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 3/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [2]: def fibonacci_series(limit):


# Initialize the first two Fibonacci numbers
a, b = 0, 1

# List to hold the Fibonacci sequence
series = []

# Continue generating Fibonacci numbers until the limit is reached
while a <= limit:
series.append(a)
a, b = b, a + b # Update values of a and b to the next Fibonacci n

return series

def main():
# Ask the user for the upper limit
limit = int(input("Enter the upper limit for the Fibonacci series: "))

# Get the Fibonacci series up to the limit
series = fibonacci_series(limit)

# Print the series
print("Fibonacci series up to", limit, "is:")
print(series)

if __name__ == "__main__":
main()

Enter the upper limit for the Fibonacci series: 55


Fibonacci series up to 55 is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The Fibonacci series is a sequence of numbers where each


number is the sum of the two preceding ones, usually starting
with 0 and 1. The sequence begins like this:
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, \ldots ]

Key Points:
1.Starting Values:

The series typically starts with 0 and 1. These two numbers are the first two terms.

2.Recursive Rule:

Each subsequent number in the series is the sum of the two previous numbers.
Mathematically, the nth term ( F_n ) can be defined as: [ F_n = F_{n-1} + F_{n-2} ]
With initial values: [ F_0 = 0 ] [ F_1 = 1 ]

3.Examples:

For ( n = 2 ): [ F_2 = F_1 + F_0 = 1 + 0 = 1 ]


For ( n = 3 ): [ F_3 = F_2 + F_1 = 1 + 1 = 2 ]
For ( n = 4 ): [ F_4 = F_3 + F_2 = 2 + 1 = 3 ]

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 4/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

How It Appears in Nature and Mathematics:


1. Nature:

Fibonacci numbers appear in various natural phenomena, such as the


arrangement of leaves on a stem, the branching of trees, the arrangement of a
pine cone, and the pattern of seeds in a sunflower.
2. Mathematics:

The Fibonacci series is used in various mathematical problems and algorithms,


including those related to sequences and recursive functions.

Simple Example:
Here’s a simple Fibonacci sequence:

Start with 0 and 1 .


Next number: ( 0 + 1 = 1 ).
Next number: ( 1 + 1 = 2 ).
Next number: ( 1 + 2 = 3 ).
Next number: ( 2 + 3 = 5 ).
And so on.

So, the beginning of the Fibonacci series is:0,1,1,2,3,5,8,13,…

3. Write a python program to Find factorial of


a number
In [3]: def factorial_iterative(n):
if n < 0:
return "Factorial is not defined for negative numbers."
result = 1
for i in range(2, n + 1):
result *= i
return result

# Get user input for the number
try:
number = int(input("Enter a non-negative integer to find its factorial:
factorial = factorial_iterative(number)
print(f"The factorial of {number} is: {factorial}")
except ValueError:
print("Please enter a valid integer.")

Enter a non-negative integer to find its factorial: 3


The factorial of 3 is: 6

4. Program to display the information-name,


full address, mobile number, college name,
course, subjects.

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 5/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [4]: def display_information():


# Collect user information
name = input("Enter your name: ")
address = input("Enter your full address: ")
mobile_number = input("Enter your mobile number: ")
college_name = input("Enter your college name: ")
course = input("Enter your course: ")
subjects = input("Enter your subjects (comma-separated): ")

# Display the information
print("\n--- Information ---")
print(f"Name: {name}")
print(f"Address: {address}")
print(f"Mobile Number: {mobile_number}")
print(f"College Name: {college_name}")
print(f"Course: {course}")
print(f"Subjects: {subjects}")

# Call the function
display_information()

Enter your name: Ajay


Enter your full address: Alwal
Enter your mobile number: 9876543210
Enter your college name: Loyola
Enter your course: EPCA
Enter your subjects (comma-separated): Python, DBMS

--- Information ---


Name: Ajay
Address: Alwal
Mobile Number: 9876543210
College Name: Loyola
Course: EPCA
Subjects: Python, DBMS

5. Program to find the largest number among


n given numbers

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 6/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [5]: def find_largest_number():


try:
# Get the number of inputs
n = int(input("Enter the number of elements: "))
if n <= 0:
print("Please enter a positive integer.")
return

# Initialize a list to store the numbers


numbers = []

# Input numbers from the user


for i in range(n):
number = float(input(f"Enter number {i + 1}: "))
numbers.append(number)

# Find the largest number


largest_number = max(numbers)

# Display the largest number


print(f"The largest number among the entered numbers is: {largest_n

except ValueError:
print("Please enter valid numbers.")

# Call the function
find_largest_number()

Enter the number of elements: 5


Enter number 1: 88
Enter number 2: 55
Enter number 3: 74
Enter number 4: 95
Enter number 5: 65
The largest number among the entered numbers is: 95.0

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 7/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

6. write a python Program to find the sum of all prime


numbers between 1-1000
In [6]: def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

def sum_of_primes(limit):
total = 0
for num in range(2, limit + 1):
if is_prime(num):
total += num
return total

# Finding the sum of all prime numbers between 1 and 1000
result = sum_of_primes(1000)
print(f"The sum of all prime numbers between 1 and 1000 is: {result}")

The sum of all prime numbers between 1 and 1000 is: 76127

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 8/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

7. write a python Program that reads set of integers


and displays first and second large numbers
In [7]: def find_largest_and_second_largest(numbers):
if len(numbers) < 2:
return "Please enter at least two numbers."

# Initialize first and second largest to very small values
largest = second_largest = float('-inf')

for num in numbers:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num

return largest, second_largest

# Input: set of integers
numbers = list(map(int, input("Enter a set of integers separated by space:

# Finding the largest and second largest numbers
largest, second_largest = find_largest_and_second_largest(numbers)

print(f"The largest number is: {largest}")
print(f"The second largest number is: {second_largest}")

Enter a set of integers separated by space: 95 85 65 25 35


The largest number is: 95
The second largest number is: 85

8. write a python Program to print the sum of first n


natural numbers.
In [8]: def sum_of_natural_numbers(n):
# Formula for sum of first n natural numbers: n * (n + 1) / 2
return n * (n + 1) // 2

# Input: value of n
n = int(input("Enter a positive integer: "))

if n > 0:
result = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {result}")
else:
print("Please enter a positive integer.")

Enter a positive integer: 4


The sum of the first 4 natural numbers is: 10

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 9/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

9. write a python Program to find the product of two


matrices.
In [9]: # Function to multiply two matrices
def multiply_matrices(A, B):
# Get dimensions of the matrices
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])

# Ensure matrices can be multiplied (number of columns in A must equal


if cols_A != rows_B:
return "Matrices cannot be multiplied."

# Initialize the result matrix with zeros
result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]

# Perform matrix multiplication
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]

return result

# Input matrices A and B
A = [
[1, 2, 3],
[4, 5, 6]
]

B = [
[7, 8],
[9, 10],
[11, 12]
]

# Multiplying the matrices
product = multiply_matrices(A, B)

# Display the result
print("Product of the matrices:")
for row in product:
print(row)

Product of the matrices:


[58, 64]
[139, 154]

Explanation:

The program multiplies two matrices A and 𝐵

Matrix multiplication is only possible when the number of columns in matrix A equals the
number of rows in matrix 𝐵

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 10/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

The program performs matrix multiplication by calculating the dot product of rows from
matrix

A with columns from matrix B

10. write a python Program to find roots of a quadratic


equation.
In [11]: import math

def find_roots(a, b, c):
# Calculate the discriminant
discriminant = b**2 - 4*a*c

# Check if discriminant is positive, zero, or negative
if discriminant > 0:
# Two real and distinct roots
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
return f"Two real and distinct roots: {root1}, {root2}"
elif discriminant == 0:
# One real and repeated root
root = -b / (2*a)
return f"One real and repeated root: {root}"
else:
# Complex roots
real_part = -b / (2*a)
imaginary_part = math.sqrt(-discriminant) / (2*a)
return f"Two complex roots: {real_part} + {imaginary_part}i, {real_

# Input coefficients a, b, and c
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

# Checking if it is a quadratic equation (a != 0)
if a == 0:
print("This is not a quadratic equation.")
else:
# Find and display the roots
result = find_roots(a, b, c)
print(result)

Enter coefficient a: 55
Enter coefficient b: 65
Enter coefficient c: 75
Two complex roots: -0.5909090909090909 + 1.007205445734561i, -0.5909090909
090909 - 1.007205445734561i

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 11/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

11. Write both recursive and non-recursive functions for the


following: to find GCD of two integers, to find the factorial of a
positive integer, to print Fibonacci sequence up to a given
number.

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 12/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [12]: # GCD of two integers



# Recursive function to find GCD
def gcd_recursive(a, b):
if b == 0:
return a
else:
return gcd_recursive(b, a % b)

# Non-recursive function to find GCD
def gcd_non_recursive(a, b):
while b:
a, b = b, a % b
return a


# Factorial of a positive integer

# Recursive function to find factorial
def factorial_recursive(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)

# Non-recursive function to find factorial
def factorial_non_recursive(n):
result = 1
for i in range(2, n + 1):
result *= i
return result


# Fibonacci sequence

# Recursive function to get Fibonacci number
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

# Function to print Fibonacci sequence recursively
def print_fibonacci_recursive(terms):
for i in range(terms):
print(fibonacci_recursive(i), end=" ")

# Non-recursive function to print Fibonacci sequence
def fibonacci_non_recursive(terms):
a, b = 0, 1
for _ in range(terms):
print(a, end=" ")
a, b = b, a + b


# Main function to test all the functions
def main():
# GCD of two integers
a = 56
b = 98
print(f"GCD (Recursive) of {a} and {b} is:", gcd_recursive(a, b))
localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 13/21
10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook
print(f"GCD (Non-Recursive) of {a} and {b} is:", gcd_non_recursive(a, b

# Factorial of a positive integer
n = 5
print(f"\nFactorial (Recursive) of {n} is:", factorial_recursive(n))
print(f"Factorial (Non-Recursive) of {n} is:", factorial_non_recursive(

# Fibonacci sequence up to a given number of terms
terms = 10
print(f"\nFibonacci Sequence (Recursive) up to {terms} terms:")
print_fibonacci_recursive(terms)

print(f"\nFibonacci Sequence (Non-Recursive) up to {terms} terms:")


fibonacci_non_recursive(terms)


# Call the main function
if __name__ == "__main__":
main()

GCD (Recursive) of 56 and 98 is: 14


GCD (Non-Recursive) of 56 and 98 is: 14

Factorial (Recursive) of 5 is: 120


Factorial (Non-Recursive) of 5 is: 120

Fibonacci Sequence (Recursive) up to 10 terms:


0 1 1 2 3 5 8 13 21 34
Fibonacci Sequence (Non-Recursive) up to 10 terms:
0 1 1 2 3 5 8 13 21 34

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 14/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

12. Program that accepts a string as an argument and returns the


number of vowel and consonants the string contains

In [13]: # Function to count vowels and consonants in a string


def count_vowels_and_consonants(input_string):
# Initialize counters
vowels = 0
consonants = 0

# Define vowel characters


vowel_set = "aeiouAEIOU"

# Loop through each character in the string


for char in input_string:
if char.isalpha(): # Check if the character is a letter
if char in vowel_set: # Check if the character is a vowel
vowels += 1
else: # If it's a letter but not a vowel, it's a consonant
consonants += 1

return vowels, consonants



# Example usage
input_string = "Hello World"
vowel_count, consonant_count = count_vowels_and_consonants(input_string)

print(f"String: '{input_string}'")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

String: 'Hello World'


Vowels: 3
Consonants: 7

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 15/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

13. Program that accepts two strings S1, S2 and find whether they
are equal or not

In [14]: # Function to check if two strings are equal


def check_strings_equal(S1, S2):
if S1 == S2:
return True
else:
return False

# Example usage
S1 = input("Enter first string (S1): ")
S2 = input("Enter second string (S2): ")

# Check if the strings are equal
if check_strings_equal(S1, S2):
print("The strings are equal.")
else:
print("The strings are not equal.")

Enter first string (S1): Python


Enter second string (S2): Programming
The strings are not equal.

14. Program to count the number of occurrences of character in a


given string

In [15]: # Function to count the occurrences of a character in a string


def count_character_occurrences(input_string, character):
count = 0
for char in input_string:
if char == character:
count += 1
return count

# Example usage
input_string = input("Enter the string: ")
character = input("Enter the character to count: ")

# Count the occurrences of the character
occurrences = count_character_occurrences(input_string, character)

print(f"The character '{character}' occurs {occurrences} times in the strin

Enter the string: Loyola


Enter the character to count: o
The character 'o' occurs 2 times in the string.

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 16/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

15. Program to find whether a given string is palindrome or


not.

In [17]: # Function to check if a string is a palindrome


def is_palindrome(input_string):
# Remove any spaces and convert to lowercase to handle case insensitivi
cleaned_string = input_string.replace(" ", "").lower()

# Compare the cleaned string with its reverse


if cleaned_string == cleaned_string[::-1]:
return True
else:
return False

# Example usage
input_string = input("Enter the string: ")

# Check if the string is a palindrome
if is_palindrome(input_string):
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")

Enter the string: radar


'radar' is a palindrome.

16. Program to find all duplicates in the list.

In [18]: # Function to find duplicates in a list


def find_duplicates(input_list):
duplicates = []
unique_elements = set()

for element in input_list:


if element in unique_elements:
if element not in duplicates:
duplicates.append(element)
else:
unique_elements.add(element)

return duplicates

# Example usage
input_list = [1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 6, 9, 5]

# Find duplicates
duplicates = find_duplicates(input_list)

print(f"The duplicate elements in the list are: {duplicates}")

The duplicate elements in the list are: [3, 2, 6, 5]

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 17/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

17. Write a program that combine list L1 and L2 int a dictionary

In [19]: # Function to combine two lists into a dictionary


def combine_lists_into_dict(L1, L2):
# Use zip to combine the two lists into key-value pairs
return dict(zip(L1, L2))

# Example usage
L1 = ['a', 'b', 'c', 'd']
L2 = [1, 2, 3, 4]

# Combine L1 and L2 into a dictionary
combined_dict = combine_lists_into_dict(L1, L2)

print(f"The combined dictionary is: {combined_dict}")

The combined dictionary is: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

18. Program to read the list of numbers as L1 print the lists in


reverse order without using reverse functions.

In [20]: # Function to print the list in reverse order


def print_reverse_list(L1):
# Loop through the list starting from the last element
for i in range(len(L1) - 1, -1, -1):
print(L1[i], end=" ")

# Example usage
L1 = [10, 20, 30, 40, 50]

print("Original List:", L1)
print("Reversed List:", end=" ")
print_reverse_list(L1)

Original List: [10, 20, 30, 40, 50]


Reversed List: 50 40 30 20 10

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 18/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

19. Program to implement the inheritance

In [21]: # Base class (Parent)


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

def speak(self):
return f"{self.name} makes a sound."


# Derived class (Child)
class Dog(Animal):
def __init__(self, name, breed):
# Call the parent class constructor
super().__init__(name)
self.breed = breed

def speak(self):
return f"{self.name} barks."


# Another Derived class (Child)
class Cat(Animal):
def __init__(self, name, color):
# Call the parent class constructor
super().__init__(name)
self.color = color

def speak(self):
return f"{self.name} meows."


# Example usage
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Black")

print(dog.speak()) # Output: Buddy barks.
print(cat.speak()) # Output: Whiskers meows.

Buddy barks.
Whiskers meows.

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 19/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

20. Program to implement the polymorphism.

In [22]: # Base class


class Shape:
def area(self):
pass # This method will be overridden in derived classes


# Derived class for Circle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius * self.radius # Area of a circle


# Derived class for Rectangle
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width # Area of a rectangle


# Derived class for Triangle
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height

def area(self):
return 0.5 * self.base * self.height # Area of a triangle


# Example usage
shapes = [
Circle(5), # Circle with radius 5
Rectangle(4, 6), # Rectangle with length 4 and width 6
Triangle(3, 4) # Triangle with base 3 and height 4
]

# Print the area of each shape
for shape in shapes:
print(f"The area of the shape is: {shape.area()}")

The area of the shape is: 78.5


The area of the shape is: 24
The area of the shape is: 6.0

In [ ]: ​

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 20/21


10/15/24, 10:09 PM Python Programming Final Lab Notes - Jupyter Notebook

In [ ]: ​

localhost:8888/notebooks/Loyola/Untitled Folder/Python Programming Final Lab Notes.ipynb# 21/21

You might also like