PYTHON LAB MANUAL-2024 (Autonomous)
PYTHON LAB MANUAL-2024 (Autonomous)
Compiled by:
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.
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
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.
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
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")
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
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
Source code:
def anagrams(s1, s2):
# Remove any spaces and convert both strings to lowercase
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
# 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
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")
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.")
else:
print("Invalid choice, please try again.")
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.
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")
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
}
Output:
enter key to be checked a
Key 'a' exists in the dictionary.
The sum of all items in the dictionary is: 100
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
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()
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 = [];
#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];
output:
Most repeated word: hello
def isphonenumber_without_regex(phone_number):
# Split the phone number into parts
parts = phone_number.split('-')
return False
# Example usage
phone_number = '415-555-4242'
print(isphonenumber_without_regex(phone_number))
Output: True
import re
def isphonenumber_with_regex(phone_number):
# Define the regex pattern for the phone number
pattern = r'^\d{3}-\d{3}-\d{4}$'
# 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()
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):
# 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()
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
# 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
import math
class Shape:
def area(self):
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
Output:
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):
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()
Output:
Source code:
# Lambda Function
add_lambda = lambda x, y: x + y
output:
Source code:
# Lambda function to find the maximum of two numbers
max_value = lambda x, y: x if x > y else y
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:
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]
Source code:
output:
# 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)
Output:
Combinations of length 2 from [1, 2, 3, 4]:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)