0% found this document useful (0 votes)
4 views40 pages

Python Lab Manual

The document outlines various Python programming exercises across multiple weeks, including arithmetic operations, Pascal's triangle, while loops, functions, character counting, palindrome checking, substring searching, list manipulation, dictionary operations, set and tuple demonstrations. Each section includes an aim, algorithm, program code, and output examples. The exercises progressively cover fundamental programming concepts and data structures in Python.

Uploaded by

avinash.jai781
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)
4 views40 pages

Python Lab Manual

The document outlines various Python programming exercises across multiple weeks, including arithmetic operations, Pascal's triangle, while loops, functions, character counting, palindrome checking, substring searching, list manipulation, dictionary operations, set and tuple demonstrations. Each section includes an aim, algorithm, program code, and output examples. The exercises progressively cover fundamental programming concepts and data structures in Python.

Uploaded by

avinash.jai781
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

Week 2

Aim :
Write a python script to perform different arithmetic
operations on numeric data types in python (co1).

Algorithm :
1) Start
2) Initialize two variables a and b.
3) Perform arithmetic operations: addition, subtraction, multiplication,
division, floor division, modulus, and exponentiation using a and b.
4) Store the results of each operation.
5) Display the results of all arithmetic operations.
6) Stop.

Program :
# Variables
a = 15
b=4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)

Output :
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

Week 3

1)Aim :
Write a program to display Pascal’s triangle.

Algorithm :
1) Start
2) Input the number of rows n.

3) Use a loop from i = 0 to n to generate each row.

4) Initialize value num = 1 for each row.

5) Calculate and print the values of Pascal’s triangle using the formula
num = num * (i - j) / (j + 1).

6) Stop.

Program :
rows = int(input("Enter number of rows: "))
for i in range(rows):
num = 1
for j in range(rows - i):
print(" ", end="")
for j in range(i + 1):
print(num, end=" ")
num = num * (i - j) // (j + 1)
print()

Output :
1
11
121
1331
14641

2)Aim :
Write a python program that uses a while loop to add
up all the even numbers between 100 and 200.

Algorithm :
1) Start
2) Initialize sum = 0 and num = 100.
3) Repeat while num ≤ 200.
4) Check if num is even (num % 2 == 0), then add it to sum.
5) Increase num by 1 each time.
6) Display the value of sum and Stop.

Program :
sum = 0
num = 100
while num <= 200:
if num % 2 == 0:
sum = sum + num
num = num + 1

print("Sum of even numbers between 100 and 200 is:", sum)


Output :
Sum of even numbers between 100 and 200 is: 7650

Week 4

Aim :
Write a python Program to Demonstrate a Function with
and without Arguments.

Algorithm :
1) Start
2) Define a function greet() without arguments to display a message.
3) Define another function add(a, b) with arguments to calculate the sum
of two numbers.
4) Call the function greet() to display the message.
5) Call the function add(10, 20) to calculate and display the sum.
6) Stop

Program :
# Function without arguments
def greet():
print("Hello, Welcome to Python Programming")
# Function with arguments
def add(a, b):
c=a+b
print("Sum is:", c)
# Function calls
greet()
add(10, 20)

Output :
Hello, Welcome to Python Programming
Sum is: 30
Aim :
Demonstrate how functions return multiple values with
an example.

Algorithm :
1) Start
2) Define a function calculate(a, b) to perform arithmetic operations.
3) Compute sum, difference, and product of the numbers.
4) Return multiple values from the function.
5) Call the function and store returned values in variables.
6) Display the results and Stop.

Program :
# Function that returns multiple values
def calculate(a, b):
sum = a + b
diff = a - b
product = a * b
return sum, diff, product
# Function call
s, d, p = calculate(10, 5)
print("Sum:", s)
print("Difference:", d)
print("Product:", p)

Output :
Sum: 15
Difference: 5
Product: 50
Week 5

Aim :
Implement a program to count the occurences of each
character in a given string.

Algorithm :
1) Start
2) Input a string from the user.
3) Create an empty dictionary to store character counts.
4) Traverse each character in the string.
5) Check if the character already exists in the dictionary.
->If yes, increase its count.
->If no, add it with count = 1.
6) Display each character with its number of occurrences.
7) Stop

Program :
# Input string
text = input("Enter a string: ")
count = { }
for ch in text:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
print("Character occurrences:")
for ch in count:
print(ch, ":", count[ch])

Output :
Enter a string: hello
Character occurrences:
h:1,e:1,l:2,o:1

Aim :
Develop a program to check a given string is
palindrome.

Algorithm :
1) Start
2) Input a string from the user.
3) Reverse the string.
4) Compare the original string with the reversed string.
5) If both are equal, display "Palindrome", otherwise display "Not
Palindrome".
6) Stop

Program :
# Input string
text = input("Enter a string: ")
# Reverse the string
rev = text[::-1]
# Check palindrome
if text == rev:
print("The string is a Palindrome")
else:
print("The string is not a Palindrome")

Output :
Enter a string: madam
The string is a Palindrome

Aim :
Write a program to search for substring within a given
string and print its index.

Algorithm :
1) Start
2) Input the main string and the substring.
3) Use the find() function to locate the substring in the main string.
4) Store the index returned by the function.
5) If index ≠ -1, display the index of the substring; otherwise display
"Substring not found".
6) Stop

Program :
# Input string
text = input("Enter the main string: ")
sub = input("Enter the substring: ")
index = [Link](sub)
if index != -1:
print("Substring found at index:", index)
else:
print("Substring not found")

Output :
Enter the main string: hello world
Enter the substring: world
Substring found at index: 6

Aim :
Implement a program to find all occurences of a
specific pattern with a string.

Algorithm :
1) Start
2) Input the main string and the pattern to search.
3) Initialize index = 0.
4) Search for the pattern in the string using find() starting from index.
5) If pattern is found, print its position and continue searching from the
next index.
6) Repeat until no more occurrences are found.
7) Stop

Program :
# Input string and pattern
text = input("Enter the main string: ")
pattern = input("Enter the pattern to search: ")
index = 0
while index < len(text):
pos = [Link](pattern, index)
if pos == -1:
break
print("Pattern found at index:", pos)
index = pos + 1

Output :
Enter the main string: banana
Enter the pattern to search: an
Pattern found at index: 1
Pattern found at index: 3

Week 6

Aim :
Write a python program to create, append and remove
elements in a list in python.

Algorithm :
1) Start
2) Create a list with some elements.
3) Display the original list.
4) Append a new element to the list using append().
5) Remove an element from the list using remove().
6) Display the updated list and Stop.
Program :
# Create a list
numbers = [10, 20, 30, 40]
print("Original List:", numbers)
# Append element
[Link](50)
print("After Appending:", numbers)
# Remove element
[Link](20)
print("After Removing:", numbers)

Output :
Original List: [10, 20, 30, 40]
After Appending: [10, 20, 30, 40, 50]
After Removing: [10, 30, 40, 50]

Aim :
Write a program to create a list of numbers 1 to 100
that are either divisible by 5 or 6.

Algorithm :
1) Start
2) Create an empty list.
3) Use a loop from 1 to 100.
4) Check if the number is divisible by 5 or 6.
5) If true, add the number to the list.
6) Display the list.
7) Stop

Program :
# Create an empty list
numbers = []
for i in range(1, 101):
if i % 5 == 0 or i % 6 == 0:
[Link](i)
print("Numbers divisible by 5 or 6:")
print(numbers)

Output :
Numbers divisible by 5 or 6:
[5, 6, 10, 12, 15, 18, 20, 24, 25, 30, 35, 36, 40, 42, 45, 48, 50, 54, 55, 60, 65, 66,
70, 72, 75, 78, 80, 84, 85, 90, 95, 96, 100]

Week 7

Aim :
Write a python program to demonstrate working with
dictionaries in Python.

Algorithm :
1) Start
2) Create a dictionary with key–value pairs.
3) Display the original dictionary.
4) Add a new key–value pair to the dictionary.
5) Access and display a value using its key.
6) Delete an element from the dictionary.
7) Display the updated dictionary and Stop.

Program :
# Create a dictionary
student = {"name": "Rahul","age": 20, "course": "CSE"}
# Display dictionary
print("Original Dictionary:", student)
# Add a new element
student["grade"] = "A"
print("After Adding Element:", student)
# Access an element
print("Student Name:", student["name"])
# Remove an element
del student["age"]
print("After Deleting Element:", student)

Output :
Original Dictionary: {'name': 'Rahul', 'age': 20, 'course': 'CSE'}
After Adding Element: {'name': 'Rahul', 'age': 20, 'course': 'CSE', 'grade': 'A'}
Student Name: Rahul
After Deleting Element: {'name': 'Rahul', 'course': 'CSE', 'grade': 'A'}

Aim :
Write a program that has the dictionary of your friends’
names as keys and phone numbers as its values. Print
the dictionary in a sorted order. Prompt the user to
enter the name and check if it is present in the
dictionary. If the name is not present, then enter the
details in the dictionary.

Algorithm :
1) Start
2) Create a dictionary with friends' names as keys and phone numbers as
values.
3) Display the dictionary in sorted order of names.
4) Ask the user to enter a friend's name to search.
5) Check if the name exists in the dictionary.
6) If present, display the phone number.
7) If not present, ask for the phone number and add it to the dictionary.
8) Display the updated dictionary and Stop.

Program :
# Dictionary of friends and phone numbers
friends = {"Anil": "9876543210","Ravi": "9123456780","Sita": "9988776655"}
# Print dictionary in sorted order
print("Friends List (Sorted):")
for name in sorted(friends):
print(name, ":", friends[name])
# Ask user to enter a name
search = input("Enter friend's name to search: ")
if search in friends:
print("Phone number:", friends[search])
else:
number = input("Name not found. Enter phone number to add: ")
friends[search] = number
print("Updated Dictionary:", friends)

Output :
Friends List (Sorted):
Anil : 9876543210
Ravi : 9123456780
Sita : 9988776655
Enter friend's name to search: Kiran
Name not found. Enter phone number to add: 9012345678
Updated Dictionary: {'Anil': '9876543210', 'Ravi': '9123456780', 'Sita':
'9988776655', 'Kiran': '9012345678'}
Week 8
Aim :
Write a python program to demonstrate working with
Sets in Python.

Algorithm :
1) Start
2) Create a set with some elements.
3) Display the original set.
4) Add an element to the set using add().
5) Remove an element from the set using remove().
6) Perform set operations like union and intersection.
7) Display the results and Stop.

Program :
# creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Set 1:", set1)
print("Set 2:", set2)
# adding an element
[Link](10)
print("\nAfter adding 10 to Set1:", set1)
# removing an element
[Link](3)
print("After removing 3 from Set1:", set1)
# union
print("\nUnion of sets:", set1 | set2)
# intersection
print("Intersection of sets:", set1 & set2)
# difference
print("Difference (Set1 - Set2):", set1 - set2)
# symmetric difference
print("Symmetric Difference:", set1 ^ set2)
# checking membership
print("\nIs 5 present in Set1?", 5 in set1)
Output :
Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
After adding 10 to Set1: {1, 2, 3, 4, 5, 10}
After removing 3 from Set1: {1, 2, 4, 5, 10}
Union of sets: {1, 2, 4, 5, 6, 7, 8, 10}
Intersection of sets: {4, 5}
Difference (Set1 - Set2): {1, 2, 10}
Symmetric Difference: {1, 2, 6, 7, 8, 10}
Is 5 present in Set1? True

Aim :
Write a program to demonstrate working with tuples in
python.

Algorithm :
1) Start
2) Create a tuple with some elements.
3) Display the original tuple.
4) Access elements using index positions.
5) Use tuple functions like count() and index().
6) Display the results.
7) Stop.

Program :
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)
print("Original tuple:", my_tuple)
# Accessing elements
print("First element:", my_tuple[0]) # Indexing starts at 0
print("Last element:", my_tuple[-1]) # Negative indexing
# Slicing a tuple
print("Elements from index 1 to 3:", my_tuple[1:4])
# Tuple concatenation
tuple2 = (60, 70)
combined_tuple = my_tuple + tuple2
print("Concatenated tuple:", combined_tuple)
# Tuple repetition
print("Repeated tuple:", tuple2 * 3)
# Checking membership
print("Is 30 in tuple?", 30 in my_tuple)
print("Is 100 in tuple?", 100 in my_tuple)
# Tuple unpacking
a, b, c, d, e = my_tuple
print("Unpacked values:", a, b, c, d, e)
# Length of tuple
print("Length of tuple:", len(my_tuple))
# Nested tuple
nested_tuple = (1, 2, (3, 4), 5)
print("Nested tuple:", nested_tuple)
print("Access nested element:", nested_tuple[2][1])

Output :
Original tuple: (10, 20, 30, 40, 50)
First element: 10
Last element: 50
Elements from index 1 to 3: (20, 30, 40)
Concatenated tuple: (10, 20, 30, 40, 50, 60, 70)
Repeated tuple: (60, 70, 60, 70, 60, 70)
Is 30 in tuple? True
Is 100 in tuple? False
Unpacked values: 10 20 30 40 50
Length of tuple: 5
Nested tuple: (1, 2, (3, 4), 5)
Access nested element: 4

Aim :
Write a program that takes a range and creates a list of
tuples within that range with the first element as the
number and the second element as the square of the
number.

Algorithm :
1) Start
2) Input the start and end values of the range.
3) Create an empty list to store tuples.
4) Use a loop from start to end.
5) Create a tuple (number, square of number) and add it to the list.
6) Display the list of tuples.
7) Stop.
Program :
# Input range
start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))
result = []
for i in range(start, end + 1):
[Link]((i, i*i))
print("List of tuples:", result)

Output :
Enter start of range: 1
Enter end of range: 5
List of tuples: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Week 9

Aim :
Write a program to read a text file and count the
occurrences of a specific word.

Algorithm :
1) Start
2) Open the text file in read mode.
3) Read the contents of the file.
4) Input the word to search.
5) Count the occurrences of the word in the text.
6) Display the count.
7) Stop

Program :
# Open and read the file
file = open("[Link]", "r")
text = [Link]()
[Link]()
# Input word to search
word = input("Enter the word to count: ")
count = [Link](word)
print("The word appears", count, "times in the file.")

Output :
Enter the word to count: python
The word appears 3 times in the file.

Aim :
Implement a program to extract specific lines
containing a keyword from a text file and write them to
another file.

Algorithm :
1) Start
2) Open the input text file in read mode.
3) Open another file in write mode.
4) Input the keyword to search.
5) Read each line from the input file.
6) Check if the line contains the keyword.
7) If yes, write that line to the output file.
8) Close both files and Stop

Program :
# Open the input file
file1 = open("[Link]", "r")
# Open the output file
file2 = open("[Link]", "w")
# Keyword to search
keyword = input("Enter the keyword: ")
for line in file1:
if keyword in line:
[Link](line)
[Link]()
[Link]()
print("Lines containing the keyword are written to [Link]")

Output :
Enter the keyword: python
Lines containing the keyword are written to [Link]

Aim :
Develop a program to replace a specific word or phrase
in a text file with another word or phrase.

Algorithm :
1) Start
2) Open the text file in read mode.
3) Read the contents of the file.
4) Input the word/phrase to replace and the new word/phrase.
5) Replace the old word with the new word using the replace function.
6) Write the modified text back to the file.
7) Display a completion message and Stop.

Program :
# Open the file and read contents
file = open("[Link]", "r")
text = [Link]()
[Link]()
# Words to replace
old_word = input("Enter the word/phrase to replace: ")
new_word = input("Enter the new word/phrase: ")
# Replace the word
text = [Link](old_word, new_word)
# Write updated content back to file
file = open("[Link]", "w")
[Link](text)
[Link]()
print("Replacement completed successfully.")
Output :
Enter the word/phrase to replace: python
Enter the new word/phrase: Java
Replacement completed successfully.

Aim :
Create a program to encrypt and decrypt a text file
using a simple substitution cipher technique.

Algorithm :
1) Start
2) Define two strings: plain alphabet and cipher alphabet.
3) Create encryption function to replace each character using cipher
mapping.
4) Create decryption function to convert cipher text back to original text.
5) Read the input file (sales_2.txt).
6) Encrypt the text and store it in [Link].
7) Decrypt the encrypted file and store it in [Link].
8) Display success messages and Stop.

Program :
# substitution mapping
plain = "abcdefghijklmnopqrstuvwxyz"
cipher = "qwertyuiopasdfghjklzxcvbnm"
# encryption function
def encrypt(text):
result = ""
for ch in text:
if [Link]() in plain:
index = [Link]([Link]())
new_char = cipher[index]
# preserve uppercase
if [Link]():
new_char = new_char.upper()

result += new_char
else:
result += ch
return result
# decryption function
def decrypt(text):
result = ""
for ch in text:
if [Link]() in cipher:
index = [Link]([Link]())
new_char = plain[index]
if [Link]():
new_char = new_char.upper()
result += new_char
else:
result += ch
return result
# ----------- Encrypt File -----------
with open("sales_2.txt", "r") as f:
data = [Link]()
encrypted_text = encrypt(data)
with open("[Link]", "w") as f:
[Link](encrypted_text)
print("File Encrypted Successfully")
# ----------- Decrypt File -----------
with open("[Link]", "r") as f:
data = [Link]()
decrypted_text = decrypt(data)
with open("[Link]", "w") as f:
[Link](decrypted_text)
print("File Decrypted Successfully")

Output :
File Encrypted Successfully
File Decrypted Successfully

Aim :
Create a program to extract all words containing a
specific substring from a text document.

Algorithm :
1) Start
2) Open a file and write text into it.
3) Open the file in read mode and read its contents.
4) Split the text into words.
5) Input a substring from the user.
6) Check each word to see if it ends with the substring.
7) Display the matching words.
8) Stop.

Program :
# Write text to file
with open('sales_2.txt', 'w') as fp:
[Link]('The morning sunlight was shining brightly on the sparkling river '
'She was singing a beautiful song while walking along the winding path '
'Learning new things every day is an exciting journey '
'The ringing of the bells could be heard from a distance '
'Bringing joy to others is a fulfilling experience')
# Read the file
with open('sales_2.txt', 'r') as fp:
data = [Link]()
# Split into words
words = [Link](" ")
# Input substring
substring = input("Enter a substring: ")
# Print words ending with the substring
for i in words:
if [Link](substring):
print(i)

Output :
Enter a substring: ing
morning
shining
sparkling
singing
walking
winding
Learning
ringing
Bringing
Fulfilling

Week 10
Aim :
Write a Python program that utilizes regular
expressions to extract all email addresses from a given
text document.

Algorithm :
1) Start
2) Import the re module for regular expressions.
3) Create a string containing text with email addresses.
4) Use [Link]() with pattern \S+@\S+ to find email addresses.
5) Store the matched emails in a list.
6) Display the list of emails.
7) Stop.

Program :
import re
s = """Hello from sundar539@[Link] to [Link]@[Link] about the
meeting @2PM"""
# \S matches any non-whitespace character
# @ for email symbol
# + means one or more characters
lst = [Link](r'\S+@\S+', s)
# Printing the list of emails
print(lst)

Output :
['sundar539@[Link]', '[Link]@[Link]']

Aim :
Implement a program to extract all phone numbers
(including various formats) from a string using regular
expressions.

Algorithm :
1) Start
2) Import the re module for regular expressions.
3) Open the text file and read its contents.
4) Define a regex pattern to match phone numbers.
5) Use [Link]() to search for phone numbers in the text.
6) Display each phone number found in the file.
7) Stop.

Program :
import re
# open and read the file
file = open("[Link]", "r")
text = [Link]()
[Link]()
# regex pattern to capture various phone formats
pattern = r'(\+91[-\s]?)?[6-9]\d{9}|\(?\d{3,5}\)?[-\s]?\d{3,5}[-\s]?\d{4}'
# find all phone numbers
matches = [Link](pattern, text)
print("Phone Numbers Found:")
for match in matches:
print([Link]())

Text file :
Contact Details
Rahul: +91 9876543210
Sita: 9123456789
Office: 040-23456789
Manager: (0863) 2233445
Customer Care: 9988776655

Output :
Phone Numbers Found:
+91 9876543210
9123456789
040-23456789
(0863) 2233445
9988776655
Week 11

Aim :
Create a class called library with data attributes like
publisher, acc_number, title and author . The methods
of the class should include .
a) read( ) – acc_number, title, author.
b) compute ( ) - to accept the number of days late,
calculate and display the fine charged at the rate
of $ 1.50 per day.
c) Display the data.

Algorithm :
1) Start
2) Create a class Library with methods read(), compute(), and display().
3) Read book details such as accession number, title, author, and
publisher.
4) Input the number of days late and calculate the fine (fine = days ×
1.50).
5) Display the fine amount.
6) Display the book details.
7) Stop.

Program :
class Library:
def read(self):
self.acc_number = input("Enter Accession Number: ")
[Link] = input("Enter Title: ")
[Link] = input("Enter Author: ")
[Link] = input("Enter Publisher: ")
def compute(self):
days = int(input("Enter number of days late: "))
fine = days * 1.50
print("Fine to be paid: $", fine)
def display(self):
print("\nLibrary Book Details")
print("Accession Number:", self.acc_number)
print("Title:", [Link])
print("Author:", [Link])
print("Publisher:", [Link])
# Create object
b1 = Library()
# Call methods
[Link]()
[Link]()
[Link]()

Output :
Enter Accession Number: 101
Enter Title: Python Programming
Enter Author: John Smith
Enter Publisher: ABC Publications
Enter number of days late: 4
Fine to be paid: $ 6.0

Library Book Details


Accession Number: 101
Title: Python Programming
Author: John Smith
Publisher: ABC Publications
Aim :
Define a car with attributes, such as make, model and
color, along with methods for displaying information
and changing attributes.

Algorithm :
1) Start
2) Create a class Car with attributes make, model, and color.
3) Define constructor __init__() to initialize values.
4) Define method show() to display car details.
5) Define method update() to modify attributes.
6) Create object c1.
7) Display original details, update attributes, and display updated details.
8) Stop

Program :
class Car:
def __init__(self, make, model, color):
[Link] = make
[Link] = model
[Link] = color

def show(self):
print("Make :", [Link])
print("Model:", [Link])
print("Color:", [Link])

def update(self, make=None, model=None, color=None):


if make:
[Link] = make
if model:
[Link] = model
if color:
[Link] = color

# Create object
c1 = Car("Honda", "City", "White")
print("Original Details:")
[Link]()
# Update attributes
[Link](color="Black", model="Amaze")
print("\nUpdated Details:")
[Link]()

Output :
Original Details:
Make : Honda
Model: City
Color: White
Updated Details:
Make : Honda
Model: Amaze
Color: Black

Aim :
Create a vehicle base class with common attributes and
method, and then derive car and motor cycle.

Algorithm :
1) Start
2) Create base class Vehicle with attributes brand and speed.
3) Define method display() to show vehicle details.
4) Create derived class Car inheriting from Vehicle.
5) Create derived class Motorcycle inheriting from Vehicle.
6) Create objects of both classes.
7) Display car and motorcycle details.
8) Stop

Program :
# Base class
class Vehicle:
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed
def display(self):
print("Brand:", [Link])
print("Speed:", [Link])
# Derived class - Car
class Car(Vehicle):
def __init__(self, brand, speed, doors):
super().__init__(brand, speed)
[Link] = doors
def show_car(self):
[Link]()
print("Doors:", [Link])
# Derived class - Motorcycle
class Motorcycle(Vehicle):
def __init__(self, brand, speed, type):
super().__init__(brand, speed)
[Link] = type
def show_bike(self):
[Link]()
print("Type:", [Link])
# Creating objects
c1 = Car("Toyota", 180, 4)
m1 = Motorcycle("Yamaha", 150, "Sport")
print("Car Details:")
c1.show_car()
print("\nMotorcycle Details:")
m1.show_bike()

Output :
Car Details:
Brand: Toyota
Speed: 180
Doors: 4
Motorcycle Details:
Brand: Yamaha
Speed: 150
Type: Sport

Aim :
Write a program to add two polynomials using classes.

Algorithm :
1) Start
2) Create a class Polynomial with a list of coefficients.
3) Define method add() to add two polynomials term by term.
4) Create two polynomial objects with given coefficients.
5) Add the polynomials and store the result in another object.
6) Display the original polynomials and their sum.
7) Stop.

Program :
# Class to represent a Polynomial
class Polynomial:
def __init__(self, coeffs):
[Link] = coeffs # list of coefficients
def add(self, p):
result = []
length = max(len([Link]), len([Link]))
for i in range(length):
a = [Link][i] if i < len([Link]) else 0
b = [Link][i] if i < len([Link]) else 0
[Link](a + b)
return Polynomial(result)
def display(self):
for i, c in enumerate([Link]):
if c != 0:
print(f"{c}x^{i}", end=" + ")
print("0")
# Creating two polynomial objects
p1 = Polynomial([5, 2, 3]) # 5 + 2x + 3x²
p2 = Polynomial([1, 4, 2]) # 1 + 4x + 2x²
print("Polynomial 1:")
[Link]()
print("Polynomial 2:")
[Link]()
# Add the polynomials
p3 = [Link](p2)
print("Sum of Polynomials:")
[Link]()

Output :

Polynomial 1:
5x^0 + 2x^1 + 3x^2 + 0
Polynomial 2:
1x^0 + 4x^1 + 2x^2 + 0
Sum of Polynomials:
6x^0 + 6x^1 + 5x^2 + 0
Week 12
Aim :
Implement a shape base class with common attributes
and methods, and then create sub classes like
rectangle, circle, and triangle.

Algorithm :
1) Start
2) Create a base class Shape with a method area().
3) Create derived classes Rectangle, Circle, and Triangle that inherit from
Shape.
4) Override the area() method in each derived class to calculate its
specific area.
5) Create objects of each class.
6) Call the area() method for each object.
7) Stop.

Program :
# Base class
class Shape:
def area(self):
print("Area not defined for generic shape")
# Rectangle class
class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
print("Rectangle Area:", [Link] * [Link])
# Circle class
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
print("Circle Area:", 3.14 * [Link] * [Link])
# Triangle class
class Triangle(Shape):
def __init__(self, base, height):
[Link] = base
[Link] = height
def area(self):
print("Triangle Area:", 0.5 * [Link] * [Link])
# Creating objects
r = Rectangle(5, 4)
c = Circle(3)
t = Triangle(6, 2)
# Calling area methods
[Link]()
[Link]()
[Link]()

Output :
Rectangle Area: 20
Circle Area: 28.26
Triangle Area: 6.0

Aim :
Define a class called student. Display the marks details
of top five students using inheritance .

Algorithm :
1) Start
2) Create a base class Student with attributes name and marks.
3) Create a derived class TopStudents that inherits from Student.
4) Define a method display() to print the student details.
5) Create student objects and store them in a list.
6) Create an object of TopStudents.
7) Call the display method to show top five students.
8) Stop.

Program :
# Base class
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
# Derived class
class TopStudents(Student):
def display(self, students):
print("Top Five Students Marks:")
for s in students:
print("Name:", [Link], "Marks:", [Link])
# Creating student objects
s1 = Student("Ravi", 95)
s2 = Student("Sita", 92)
s3 = Student("Arjun", 90)
s4 = Student("Priya", 88)
s5 = Student("Kiran", 85)
students = [s1, s2, s3, s4, s5]
# Using derived class
top = TopStudents("", 0)
[Link](students)

Output :
Top Five Students Marks:
Name: Ravi Marks: 95
Name: Sita Marks: 92
Name: Arjun Marks: 90
Name: Priya Marks: 88
Name: Kiran Marks: 85

Aim :
Utilize polymorphism to create a function that takes
objects of different sub classes and calls their common
methods.

Algorithm :
1) Start
2) Create a base class Animal with a method sound().
3) Create subclasses Dog, Cat, and Cow that override the sound() method.
4) Define a function make_sound() that calls the sound() method.
5) Create objects of each subclass.
6) Call the same function with different objects to demonstrate
polymorphism.
7) Stop.

Program :
# Base class
class Animal:
def sound(self):
pass
# Subclass 1
class Dog(Animal):
def sound(self):
print("Dog barks")
# Subclass 2
class Cat(Animal):
def sound(self):
print("Cat meows")
# Subclass 3
class Cow(Animal):
def sound(self):
print("Cow moos")
# Polymorphic function
def make_sound(animal):
[Link]()
# Creating objects
d = Dog()
c = Cat()
cw = Cow()
# Calling same function with different objects
make_sound(d)
make_sound(c)
make_sound(cw)

Output :
Dog barks
Cat meows
Cow moos

Week 13
Aim :
Write a python program to calculate the sum of every
column in a NumPy array.

Algorithm :
1) Start
2) Import the NumPy library.
3) Create a 2D NumPy array using [Link]().
4) Calculate the sum of each column using [Link](arr, axis=0).
5) Display the array.
6) Display the sum of each column.
7) Stop.
Program :
import numpy as np
# Creating a 2D NumPy array
arr = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Calculating sum of each column
colsum = [Link](arr, axis=0)
print("Array:")
print(arr)
print("\nSum of each column:")
print(colsum)

Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]

Sum of each column:


[12 15 18]

Aim :
NumPy integer indexing, array indexing, Boolean array
indexing and slicing with examples.

Algorithm :
1) Start
2) Import the NumPy library.
3) Create a 1D array and a 2D array using [Link]().
4) Demonstrate integer indexing to access specific elements.
5) Demonstrate fancy indexing using multiple indices.
6) Demonstrate boolean indexing to filter elements.
7) Demonstrate slicing to extract parts of arrays.
8) Display the results.
9) Stop.

Program :
import numpy as np
# Creating 1D and 2D arrays
arr1 = [Link]([10, 20, 30, 40, 50])
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("Original 1D Array:", arr1)
print("Original 2D Array:\n", arr2)
print("\n1. Integer Indexing")
print("arr1[2] =", arr1[2]) # 30
print("arr2[0,1] =", arr2[0,1]) #2
print("\n2. Fancy Indexing")
print("arr1[[0,2,4]] =", arr1[[0,2,4]])
print("arr2[[0,1],[1,2]] =", arr2[[0,1],[1,2]])
print("\n3. Boolean Indexing")
print("Elements greater than 25:", arr1[arr1 > 25])
print("\n4. Slicing")
print("arr1[1:4] =", arr1[1:4])
print("arr2[0:2,1:3] =\n", arr2[0:2,1:3])

Output :
Original 1D Array: [10 20 30 40 50]
Original 2D Array:
[[1 2 3]
[4 5 6]]
1. Integer Indexing
arr1[2] = 30
arr2[0,1] = 2
2. Fancy Indexing
arr1[[0,2,4]] = [10 30 50]
arr2[[0,1],[1,2]] = [2 6]
3. Boolean Indexing
Elements greater than 25: [30 40 50]
4. Slicing
arr1[1:4] = [20 30 40]
arr2[0:2,1:3] =
[[2 3]
[5 6]]

You might also like