0% found this document useful (0 votes)
210 views33 pages

PYTHON LAB MANUAL-2024 (Autonomous)

Uploaded by

deekshahl.ckm
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)
210 views33 pages

PYTHON LAB MANUAL-2024 (Autonomous)

Uploaded by

deekshahl.ckm
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/ 33

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND MANAGEMENT

Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082


(Affliated to VTU, Belagavi, Approved by AICTE, New Delhi)
Accredited by NBA and NAAC ( A+)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING 2024


PYTHON PROGRAMMING LAB MANUAL (23CSE37)

Compiled by:

Prof. Keerthana shankar


Prof.Manasa Sandeep
Prof.Shylaja B
Prof. G Yamini

Dr. Kavitha C Dr. M Ravishankar


HOD, CSE, DSATM Principal, DSATM
DAYANANDA SAGAR ACADEMY OF Approved by AICTE
TECHNOLOGY &MANAGEMENT Accredited by NAAC with A+ Grade
6 Programs Accredited by NBA
(CSE, ISE, ECE, EEE, MECH, CIVIL)

INSTITUTION VISION AND MISSION

Vision of the Institution

To strive at creating the institution a center of highest caliber of learning, so as to create an overall
intellectual atmosphere with each deriving strength from the other to be the best of engineers, scientists
with management &design skills.

Mission of the Institution:

 To serve its region, state, the nation and globally by preparing students to make
 meaningful contributions in an increasing complex global society challenge.
 To encourage, reflection on and evaluation of emerging needs and priorities with state of art
infrastructure at institution.
 To support research and services establishing enhancements in technical, health, economic, human and
cultural development.
 To establish inter disciplinary center of excellence, supporting/ promoting student’s implementation.
 To increase the number of Doctorate holders to promote research culture on campus.
 To establish IIPC, IPR, EDC, innovation cells with functional MOU’s supporting student’s quality
growth.
DAYANANDA SAGAR ACADEMY OF Approved by AICTE
Accredited by NAAC with A+ Grade
TECHNOLOGY &MANAGEMENT
6 Programs Accredited by NBA
(CSE, ISE, ECE, EEE, MECH,CIVIL)

QUALITY POLICY

Dayananda Sagar Academy of Technology and Management aims at achieving academic


excellence through continuous improvement in all spheres of Technical and Management
education. In pursuit of excellence cutting-edge and contemporary skills are imparted to the
utmost satisfaction of the students and the concerned stakeholders

OBJECTIVES & GOALS

 Creating an academic environment to nurture and develop competent


entrepreneurs, leaders and professionals who are socially sensitive and
environmentally conscious.
 Integration of Outcome Based Education and cognitive teaching and
learning strategies to enhance learning effectiveness.
 Developing necessary infrastructure to cater to the changing needs of Business
and Society.
 Optimum utilization of the infrastructure and resources to achieve excellence in
all areas of relevance.
 Adopting learning beyond curriculum through outbound activities and
creative assignments.
 Imparting contemporary and emerging techno-managerial skills to keep pace with
the changing global trends.
 Facilitating greater Industry-Institute Interaction for skill development
and employability enhancement.
 Establishing systems and processes to facilitate research, innovation and
entrepreneurship for holistic development of students.
 Implementation of Quality Assurance System in all Institutional processes
DAYANANDA SAGAR ACADEMY OF Approved by AICTE
TECHNOLOGY &MANAGEMENT Accredited by NAAC with A+ Grade
6 Programs Accredited by NBA
(CSE, ISE, ECE, EEE, MECH,CIVIL)

Department of Computer Science and Engineering


Vision and Mission of the Department

Department Vision
Epitomize CSE graduate to carve a niche globally in the field of computer science to excel in the world of
information technology and automation by imparting knowledge to sustain skills for the changing trends
in the society and industry.
Department Mission
M1: To educate students to become excellent engineers in a confident and creative environment through
world-class pedagogy.
M2: Enhancing the knowledge in the changing technology trends by giving hands-on experience through
continuous education and by making them to organize & participate in various events.
M3: Impart skills in the field of IT and its related areas with a focus on developing the required
competencies and virtues to meet the industry expectations.
M4: Ensure quality research and innovations to fulfill industry, government & social needs.
M5: Impart entrepreneurship and consultancy skills to students to develop self-sustaining life skills in
multi-disciplinary areas.

Programme Educational Objectives

PEO 1: Engage in professional practice to promote the development of innovative systems and optimized
solutions for Computer Science and Engineering.
PEO 2: Adapt to different roles and responsibilities in interdisciplinary working environment by
respecting professionalism and ethical practices within organization and society at national and
international level.
PEO 3: Graduates will engage in life-long learning and professional development to acclimate the rapidly
changing work environment and develop entrepreneurship skills.
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding of
the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
PSO 1: Foundation of Mathematical Concepts: Ability to use mathematical methodologies to crack
problem using suitable mathematical analysis, data structure and suitable algorithm.
PSO 2: Foundation of Computer System: Ability to interpret the fundamental concepts and methodology
of computer systems. Students can understand the functionality of hardware and software
aspects of computer systems.
PSO 3: Foundations of Software Development: Ability to grasp the software development lifecycle and
methodologies of software systems. Possess competent skills and knowledge of software design
process. Familiarity and practical proficiency with a broad area of programming concepts and
provide new ideas and innovations towards research.
PSO 4: Foundations of Multi-Disciplinary Work: Ability to acquire leadership skills to perform
professional activities with social responsibilities, through excellent flexibility to function in
multi- disciplinary work environment with self-learning skills.
List of Programs:

Warmup Programs:
 Develop a simple python Program to
o Print the sentence “Welcome to CSE, DSATM!!!”
o Read input number from user and check if the number is positive, negative
or 0
o First N Natural numbers using for and while loop
Sl. Experiments/Programs COs
No.
1 Functions: CO1
Create using Python
 A Simple calculator.
 A program to define a function with multiple return values
2 Strings: CO1
Build python program to
 Find the length of the string without using any library functions.
 Check if two strings are anagrams or not.
3 Lists and Tuples: CO1
Develop a python program to
 Perform the given operations on a
list:
i. Add ii. Insert iii. Slicing
 Get a list of the even numbers from a given list of numbers.
 Create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated
tuples
4 Dictionaries: CO2
Develop a python program to
 Check if a given key exists in a dictionary or not & to sum all the
items in a given dictionary
 Convert Roman Numbers in to integer values using dictionaries
5 Files: CO1
Build python program to
 Sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper case words from
source must be lowered.
 Find the most frequent words in a text. (read from a text file).
6 Pattern Recognition & Regular Expressions CO2
 Write a function called isphonenumber () to recognize a pattern
415-555- 4242 without using regular expression and also write
the code to recognize the same pattern using regular expression.
 Develop a python program that could search the text in a file for
phone numbers (+919900889977) and email addresses
([email protected])
7 Classes CO2
 Write a Python class named Circle constructed by a radius and
two methods which will compute the area and the perimeter of a
circle.
 Develop a program that uses class Student which prompts the
user to enter
marks in three subjects and calculates total marks, percentage
and displays the score card details.
[Use list to store the marks in three subjects and total marks. Use init()
method to initialize name, USN and the lists to store marks and total, Use
getMarks() method
to read marks into the list, and display() method to display the score card
details.]
8 Polymorphism and Inheritance CO2
 By using the concept of inheritance write a python program to
find the area of triangle,
circle and rectangle
 Write a python program to find the whether the given input is
palindrome or not (for both string and integer) using the concept
of polymorphism and inheritance.
9 lambda and filter functions CO2
 Develop a python program to differentiate between Lambda
functions and def defined function
 Develop a python program to find maximum of two numbers
using lambda function
 Create a list of numbers. Separate the odd numbers of the list
using filter() and lambda function
10 map and itertools CO3
 Write a python program to Multiply all elements of a list by 2
using lambda and map() function
Write a Python program to generate combinations of a given length of
a given
iterable
Open ended Programs
1 Develop a python program to print half pyramid, inverted half pyramid CO1
of numbers
and Pascal's Triangle
2 Develop a Python program to check whether a given number is CO2
palindrome or not
and also count the number of occurrences of each digit in the input
number
3 Develop a program to backing Up a given Folder (Folder in a current CO3
working
directory) into a ZIP File by using relevant modules and suitable methods.
4 Develop a python program to demonstrate Exception Handling CO3
5 Develop a python program to transform all elements of a list to upper CO3
case using
lambda and map() function
Warmup Programs:
Develop a simple python Program to
 Print the sentence “Welcome to CSE, DSATM!!!”
 Read input number from user and check if the number is positive, negative or 0
 First N Natural numbers using for and while loop

a)Print the sentence “Welcome to CSE, DSATM!!!”

name = "Welcome to CSE,DSATM!!!"


print(name)

b)input number from user and check if the number is positive, negative or 0

# Prompt the user to input a number, and convert the input to a floating-point number.
num = float(input("Input a number: "))
# Check if the number is greater than zero.
if num > 0:
# If true, print that it is a positive number.
print("It is a positive number")
# Check if the number is equal to zero.
elif num == 0:
# If true, print that it is zero.
print("It is zero")
else:
# If the above conditions are not met, print that it is a negative number.
print("It is a negative number")

c)Python Program to Print Natural Numbers from 1 to N

number = int(input("Please Enter any Number: "))

print("The List of Natural Numbers from 1 to {0} are".format(number))

for i in range(1, number + 1):


print (i, end = ' ')
Using while loop:
i=1
n=int(input("enter an integer"))
while i<=n:
print(i)
i=i+1

Sl. Experiments/Programs COs


No.
1 Functions: CO1
Create using Python
 A Simple calculator.
 A program to define a function with multiple return values
Solution:
A Simple calculator
# Function to add two numbers
def add(num1, num2):
return num1 + num2

# Function to subtract two numbers


def subtract(num1, num2):
return num1 - num2

# Function to multiply two numbers


def multiply(num1, num2):
return num1 * num2

# Function to divide two numbers


def divide(num1, num2):
return num1 / num2

print("Please select operation -\n" \


"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
while True:
# Take input from the user
select = int(input("Select operations form 1, 2, 3, 4 :"))
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))

if select == 1:
print(number_1, "+", number_2, "=",
add(number_1, number_2))

elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))

elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))

elif select == 4:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
elif :
print("Invalid input")

Output:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide

Select operations form 1, 2, 3, 4 :1


Enter first number: 2
Enter second number: 3
2+3=5
Select operations form 1, 2, 3, 4 :2
Enter first number: 4
Enter second number: 3
4-3=1
Select operations form 1, 2, 3, 4 :
A program to define a function with multiple return values

def calculate(x, y):


sum= x + y
difference = x - y
product = x * y
return sum, difference, product

# Calling the function


result_sum, result_difference, result_product = calculate(10, 5)

print(f"Sum: {result_sum}")
print(f"Difference: {result_difference}")
print(f"Product: {result_product}")

output:
Sum: 15
Difference: 5
Product: 50

2 Strings: CO1
Build python program to
 Find the length of the string without using any library functions.

Source code:
def length(string):
count = 0
for char in string:
count += 1
return count

# Example usage
string = "Hello_Python!"
length = length(string)
print(f"The length of the string is: {length}")

Output:
The length of the string is: 13

Check if two strings are anagrams or not.


Anagrams are words or phrases formed by rearranging the letters of another word or
phrase. To be considered an anagram, both words or phrases must contain the same
letters with the same frequency, though arranged in a different order.
For example:
 "listen" and "silent" are anagrams because they use the same letters.

Source code:
def anagrams(s1, s2):
# Remove any spaces and convert both strings to lowercase
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()

# Compare the sorted versions of the strings


return sorted(s1) == sorted(s2)

# Example usage
s1=input("enter first string")
s2=input("enter second string")

if anagrams(s1, s2):
print(f'"{s1}" and "{s2}" are anagrams.')
else:
print(f'"{s1}" and "{s2}" are not anagrams.')

Output

enter first string listen


enter second string silent
"listen" and "silent" are anagrams.

3 Lists and Tuples: CO1


Develop a python program to
 Perform the given operations on a list:
i. Add ii. Insert iii. Slicing

Source code:

def operations():
my_list = [] # Start with an empty list
while True:
print("\nCurrent List:", my_list)
print("Choose an operation:")
print("1. Add an element to the list")
print("2. Insert an element at a specific
index")
print("3. Slice the list")
print("4. Exit")

choice = input("Enter your choice


(1/2/3/4): ")

if choice == '1':
# Add element to the list
element = input("Enter the element to
add: ")
my_list.append(element)
print(f"{element} added to the list.")

elif choice == '2':


# Insert element at a specific index
element = input("Enter the element to
insert: ")
index = int(input(f"Enter the index to
insert {element} at: "))
if 0 <= index <= len(my_list):
my_list.insert(index, element)
print(f"{element} inserted at index
{index}.")
else:
print(f"Invalid index. Please enter a
value between 0 and {len(my_list)}.")

elif choice == '3':


# Slice the list
try:
start = int(input("Enter the starting
index of the slice: "))
end = int(input("Enter the ending
index of the slice: "))
if 0 <= start <= len(my_list) and 0 <=
end <= len(my_list):
sliced_list = my_list[start:end]
print(f"Sliced list from index
{start} to {end}: {sliced_list}")
else:
print(f"Invalid slice indices. Please
enter values between 0 and {len(my_list)}.")
except ValueError:
print("Please enter valid integers for
slicing.")

elif choice == '4':


print("Exiting the program.")
break

else:
print("Invalid choice, please try again.")

# Run the program


operations()

Output:

Current List: []
Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 1
Enter the element to add: 2
2 added to the list.

Current List: ['2']


Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 3
Enter the starting index of the slice: 2
Enter the ending index of the slice: 3
Invalid slice indices. Please enter values
between 0 and 1.

Current List: ['2']


Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 1
Enter the element to add: 3
3 added to the list.

Current List: ['2', '3']


Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 2
Enter the element to insert: 3
Enter the index to insert 3 at: 2
3 inserted at index 2.

Current List: ['2', '3', '3']


Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 3
Enter the starting index of the slice: 0
Enter the ending index of the slice: 1
Sliced list from index 0 to 1: ['2']

Current List: ['2', '3', '3']


Choose an operation:
1. Add an element to the list
2. Insert an element at a specific index
3. Slice the list
4. Exit
Enter your choice (1/2/3/4): 4
Exiting the program.

Get a list of the even numbers from a given list of numbers.

Source code:

def even_numbers(numbers):
# List comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
return even_numbers

# Example usage
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = even_numbers(numbers_list)
print("Even numbers:", even_numbers)
Output:
Even numbers: [2, 4, 6, 8, 10]

Create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples

Source code:
# Define tuples for members
member1 = ("Srilatha", 22, "1st main JP NAGAR", "DSATM")
member2 = ("Boby", 25, "2nd main ,Uttarahalli", "DSATM")

# Concatenate the tuples


all_members = member1 + member2

# Print the concatenated tuples


print("Concatenated tuples:", all_members)
Output:
Concatenated tuples: ('Srilatha', 22, '1st main JP NAGAR', 'DSATM', 'Boby', 25,
'2nd main ,Uttarahalli', 'DSATM')

4 Dictionaries: CO2
Develop a python program to
 Check if a given key exists in a dictionary or not & to sum all the
items in a given dictionary
Source code:
def check_key_exists(dictionary, key):
return key in dictionary

def sum_all_items(dictionary):
return sum(dictionary.values())

# Example dictionary
my_dict = {
'a': 10,
'b': 20,
'c': 30,
'd': 40
}

# Check if a key exists


key_to_check = input("enter key to be chekced")
if check_key_exists(my_dict, key_to_check):
print(f"Key '{key_to_check}' exists in the dictionary.")
else:
print(f"Key '{key_to_check}' does not exist in the dictionary.")

# Sum all items in the dictionary


total_sum = sum_all_items(my_dict)
print(f"The sum of all items in the dictionary is: {total_sum}")

Output:
enter key to be checked a
Key 'a' exists in the dictionary.
The sum of all items in the dictionary is: 100

Convert Roman Numbers in to integer values using dictionaries


Source code:

def roman_to_int(roman):
# Dictionary mapping Roman numerals to integer values
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}

total = 0
prev_value = 0

# Iterate through the Roman numeral string from left to right


for char in roman:
value = roman_dict[char]
# If the current value is greater than the previous value, subtract twice the
previous value
if value > prev_value:
total += value - 2 * prev_value
else:
total += value
prev_value = value

return total
# Example usage
roman_numeral = input("enter string")
integer_value = roman_to_int(roman_numeral)
print(f"The integer value of Roman numeral '{roman_numeral}' is: {integer_value}")

Output:
enter string II
The integer value of Roman numeral 'II' is: 2
5 Files: CO1
Build python program to
 Sort words in a file and put them in another file. The output file should
have only lower-case words, so any uppercase words from source must
be lowered.

Source code:
def sort_words_in_file(source_file, output_file):
try:
# Read words from the source file
with open(source_file, 'r') as file:
words = file.read().split()
# Convert words to lowercase and sort them
words = [word.lower() for word in words]
words.sort()

# Write sorted words to the output file


with open(output_file, 'w') as file:
for word in words:
file.write(word + '\n')

print(f"Words from '{source_file}' have been sorted and written to


'{output_file}'.")

except FileNotFoundError:
print(f"Error: The file '{source_file}' does not exist.")
except IOError as e:
print(f"Error: {e}")

# Example usage
source_file = 'source.txt'
output_file = 'sorted_words.txt'
sort_words_in_file(source_file, output_file)
Note:
Create a text file with the name source.txt with some words in it.
Output:
Words from 'source.txt' have been sorted and written to 'destination.txt'.

Find the most frequent words in a text. (read from a text file).
Note: create data.txt file with some words
Source code:
count = 0;
word = "";
maxCount = 0;
words = [];

#Opens a file in read mode


file = open("data.txt", "r")

#Gets each line till end of file is reached


for line in file:
#Splits each line into words
string = line.lower().replace(',','').replace('.','').split(" ");
#Adding all words generated in previous step into words
for s in string:
words.append(s);

#Determine the most repeated word in a file


for i in range(0, len(words)):
count = 1;
#Count each word in the file and store it in variable count
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;

#If maxCount is less than count then store value of count in maxCount
#and corresponding word to variable word
if(count > maxCount):
maxCount = count;
word = words[i];

print("Most repeated word: " + word);


file.close();

output:
Most repeated word: hello

6 Pattern Recognition & Regular Expressions CO2


 Write a function called isphonenumber () to recognize a pattern 415-
555- 4242 without using regular expression and also write the code to
recognize the same pattern using regular expression.

Without using Regular Expression:

def isphonenumber_without_regex(phone_number):
# Split the phone number into parts
parts = phone_number.split('-')

# Check if there are exactly 3 parts


if len(parts) != 3:
return False

# Check if each part has the correct length


area_code, prefix, line_number = parts
if len(area_code) == 3 and len(prefix) == 3 and len(line_number) == 4:
# Check if all parts are numeric
if area_code.isdigit() and prefix.isdigit() and line_number.isdigit():
return True

return False

# Example usage
phone_number = '415-555-4242'
print(isphonenumber_without_regex(phone_number))

Output: True

With Regular Expression:

import re

def isphonenumber_with_regex(phone_number):
# Define the regex pattern for the phone number
pattern = r'^\d{3}-\d{3}-\d{4}$'

# Use re.match to check if the pattern matches the phone number


if re.match(pattern, phone_number):
return True
return False

# Example usage
phone_number = '415-555-4242'
print(isphonenumber_with_regex(phone_number))

Output: True

Develop a python program that could search the text in a file for phone
numbers (+919900889977) and email addresses ([email protected])

Source code:

import re

def find_phone_numbers_and_emails(file_path):
# Define regex patterns for phone numbers and email addresses
phone_pattern = r'\+\d{12}' # Matches phone numbers like +919900889977
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' #
Matches email addresses

try:
# Read the text from the file
with open(file_path, 'r') as file:
text = file.read()

# Find all phone numbers and email addresses in the text


phone_numbers = re.findall(phone_pattern, text)
email_addresses = re.findall(email_pattern, text)

return phone_numbers, email_addresses

except FileNotFoundError:
print(f"Error: The file '{file_path}' does not exist.")
except IOError as e:
print(f"Error: {e}")

# Example usage
file_path = 'data.txt'
phone_numbers, email_addresses = find_phone_numbers_and_emails(file_path)

if phone_numbers:
print("Phone Numbers Found:")
for number in phone_numbers:
print(number)

if email_addresses:
print("Email Addresses Found:")
for email in email_addresses:
print(email)
Output:
Email Addresses Found:
[email protected]
7 Classes CO2
 Write a Python class named Circle constructed by a radius and two
methods which will compute the area and the perimeter of a circle.

import math

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * (self.radius ** 2)

def perimeter(self):

return 2 * math.pi * self.radius

# Example usage
circle = Circle(5) # Create a Circle object with radius 5

print(f"Radius: {circle.radius}")
print(f"Area: {circle.area():.3f}")
print(f"Perimeter: {circle.perimeter():.3f}")

Output:
Radius: 5
Area: 78.540
Perimeter: 31.416

Develop a program that uses class Student which prompts the user to enter
marks in three subjects and calculates total marks, percentage and displays
the score card details.

Source code:
class Student:
def __init__(self, name, usn):
"""Initialize the Student class with name, USN, and empty lists."""
self.name = name
self.usn = usn
self.marks = [0, 0, 0]
self.total = 0

def getMarks(self):
"""Prompt the user to enter marks for three subjects and store them in the list."""
try:
self.marks[0] = float(input("Enter marks for Subject 1: "))
self.marks[1] = float(input("Enter marks for Subject 2: "))
self.marks[2] = float(input("Enter marks for Subject 3: "))
except ValueError:
print("Invalid input. Please enter numeric values for marks.")
self.getMarks()

# Calculate total marks


self.total = sum(self.marks)

def display(self):
"""Display the scorecard details including name, USN, marks, total, and
percentage."""
percentage = (self.total / 300) * 100 # Assuming max marks for each subject is
100

print("\nScore Card Details:")


print(f"Name: {self.name}")
print(f"USN: {self.usn}")
print(f"Marks in Subject 1: {self.marks[0]}")
print(f"Marks in Subject 2: {self.marks[1]}")
print(f"Marks in Subject 3: {self.marks[2]}")
print(f"Total Marks: {self.total}")
print(f"Percentage: {percentage:.2f}%")

# Example usage
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
student = Student(name, usn)
student.getMarks()
student.display()
Output:
Enter marks for Subject 1: 34
Enter marks for Subject 2: 35
Enter marks for Subject 3: 35

Score Card Details:


Marks in Subject 1: 34.0
Marks in Subject 2: 35.0
Marks in Subject 3: 35.0
Total Marks: 104.0
Percentage: 34.67%
[Use list to store the marks in three subjects and total marks. Use init() method to
initialize name, USN and the lists to store marks and total, Use getMarks() method
to read marks into the list, and display() method to display the score card details.]
8 Polymorphism and Inheritance CO2
 By using the concept of inheritance write a python program to find the
area of triangle, circle and rectangle

import math

class Shape:
def area(self):

raise NotImplementedError("Subclasses must implement the area method.")

class Triangle(Shape):
def __init__(self, base, height):
"""Initialize the triangle with base and height."""
self.base = base
self.height = height

def area(self):
"""Calculate the area of the triangle."""
return 0.5 * self.base * self.height

class Circle(Shape):
def __init__(self, radius):
"""Initialize the circle with a radius."""
self.radius = radius

def area(self):
"""Calculate the area of the circle."""
return math.pi * (self.radius ** 2)

class Rectangle(Shape):
def __init__(self, width, height):

self.width = width
self.height = height

def area(self):
return self.width * self.height

# Input and calculate area for Triangle


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
triangle = Triangle(base, height)
print(f"Area of Triangle: {triangle.area():.2f}")

# Input and calculate area for Circle


radius = float(input("Enter the radius of the circle: "))
circle = Circle(radius)
print(f"Area of Circle: {circle.area():.2f}")

# Input and calculate area for Rectangle


width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
rectangle = Rectangle(width, height)
print(f"Area of Rectangle: {rectangle.area():.2f}")

Output:

Enter the base of the triangle: 5


Enter the height of the triangle: 8
Area of Triangle: 20.00
Enter the radius of the circle: 8
Area of Circle: 201.06
Enter the width of the rectangle: 9
Enter the height of the rectangle: 8
Area of Rectangle: 72.00

Write a python program to find the whether the given input is palindrome or
not (for both string and integer) using the concept of polymorphism and
inheritance.

class Palindrome:
def is_palindrome(self):

raise NotImplementedError("Subclasses must implement the is_palindrome


method.")
class StringPalindrome(Palindrome):
def __init__(self, text):

self.text = text

def is_palindrome(self):
"""Check if the string is a palindrome."""
cleaned_text = ''.join(e for e in self.text if e.isalnum()).lower()
return cleaned_text == cleaned_text[::-1]

class IntegerPalindrome(Palindrome):
def __init__(self, number):

self.number = number

def is_palindrome(self):

str_num = str(self.number)
return str_num == str_num[::-1]

# Example usage:
def check_palindrome(input_value):
if isinstance(input_value, str):
palindrome_checker = StringPalindrome(input_value)
elif isinstance(input_value, int):
palindrome_checker = IntegerPalindrome(input_value)
else:
raise TypeError("Input must be a string or integer.")

return palindrome_checker.is_palindrome()

# Get input from the user


input_string = input("Enter a string to check if it's a palindrome: ")
input_integer = int(input("Enter an integer to check if it's a palindrome: "))

print(f"string '{input_string}' a palindrome:{check_palindrome(input_string)}")


print(f"integer {input_integer} a palindrome: {check_palindrome(input_integer)}")

Output:

Enter a string to check if it's a palindrome: y


Enter an integer to check if it's a palindrome: 6
string 'y' a palindrome:True
integer 6 a palindrome: True

9 lambda and filter functions CO2


 Develop a python program to differentiate between Lambda functions and
def defined function

Source code:

# Lambda Function
add_lambda = lambda x, y: x + y

# Def Defined Function


def add_def(x, y):
"""Add two numbers using a named function."""
result = x + y
return result

# Test the functions


x, y = 5, 3

# Using the lambda function


lambda_result = add_lambda(x, y)
print(f"Result of lambda function: {lambda_result}")

# Using the def defined function


def_result = add_def(x, y)
print(f"Result of def defined function: {def_result}")

output:

Result of lambda function: 8


Result of def defined function: 8
Develop a python program to find maximum of two numbers using lambda
function

Source code:
# Lambda function to find the maximum of two numbers
max_value = lambda x, y: x if x > y else y

# Test the lambda function


a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# Find and print the maximum using the lambda function


max_value = max_value(a, b)
print(f"The maximum of {a} and {b} is: {max_value}")

output:
Enter the first number: 4
Enter the second number: 3
The maximum of 4.0 and 3.0 is: 4.0

:
Create a list of numbers. Separate the odd numbers of the list using filter() and
lambda function

Source code:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20]

# Use filter() with a lambda function to separate odd numbers


odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))

# Print the result


print("list:", numbers)
print("Odd numbers:", odd_numbers)

Output:
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

10 map and itertools CO3


 Write a python program to Multiply all elements of a list by 2 using
lambda and map() function

Source code:

# Create a list of numbers


numbers = [1, 2, 3, 4, 5]

# Use map() with a lambda function to multiply each element by 2


doubled_numbers = list(map(lambda x: x * 2, numbers))

# Print the result


print("listof numbers", numbers)
print("List after multiplying each element by 2:", doubled_numbers)

output:

list of numbers [1, 2, 3, 4, 5]


List after multiplying each element by 2: [2, 4, 6, 8, 10]

Write a Python program to generate combinations of a given length of a given


Iterable:
Source code:

from itertools import combinations

def generate_combinations(iterable, length):

return list(combinations(iterable, length))

# Example usage
if __name__ == "__main__":
# Define the iterable and the combination length
iterable = [1, 2, 3, 4]
length = 2

# Generate combinations
result = generate_combinations(iterable, length)

# Print the result


print(f"Combinations of length {length} from {iterable}:")
for i in result:
print(i)

Output:
Combinations of length 2 from [1, 2, 3, 4]:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

You might also like