Python Lab Manual
Python Lab Manual
1. Write a Python program to demonstrate variables, data types, and basic arithmetic
operations.
2. Develop a program to perform various string operations: slicing, concatenation, reversal,
and searching.
3. Write a Python script to demonstrate the use of if-else, elif, while, and for loops with
examples.
4. Create a Python program with user-defined functions and implement a recursive function
to compute factorial.
5. Write a Python program to create a class, instantiate an object, and demonstrate class
variables and instance methods.
6. Develop a Python program that demonstrates single and multiple inheritances along with
method overriding.
7. Write a program to perform insertion, deletion, sorting, and searching on a list and tuple.
8. Implement a Python script that demonstrates union, intersection, difference, and subset
operations on sets.
9. Write a Python script to create a dictionary, update, delete, and perform sorting on keys
and values.
10. Develop a program that reads a file, counts the frequency of words, and writes the output
to a new file.
11. Create a Python script that accepts command-line arguments and performs arithmetic
operations based on input.
12. Write a Python program using the re module to validate an email ID and phone number.
13. Implement a program that demonstrates try-except blocks and custom exceptions.
14. Write a Python script to implement a stack and queue using lists.
15. Develop a Python program to connect to a database using SQLite, create tables, insert
data, and perform queries.
Experiment – 1
Write a Python program to demonstrate the use of variables, different data types, and
perform arithmetic operations.
# Arithmetic Operations
sum_result = num1 + decimal
product = num1 * decimal
division = num1 / 2
modulo = num1 % 3
power = num1 ** 2
# Displaying results
print(“Integer Value:”, num1)
print(“Float Value:”, decimal)
print(“Complex Number:”, complex_num)
print(“Sum:”, sum_result)
print(“Product:”, product)
print(“Division:”, division)
print(“Modulo:”, modulo)
print(“Power:”, power)
Output:
Type of num1: <class ‘int’>
Type of decimal: <class ‘float’>
Type of name: <class ‘str’>
Type of complex_num: <class ‘complex’>
Integer Value: 10
Float Value: 3.14
Complex Number: (2+3j)
Sum: 13.14
Product: 31.4
Division: 5.0
Modulo: 1
Power: 100
Experiment – 2
Develop a program to perform various string operations: slicing, concatenation,
reversal, and searching.
# String Operations
text = “Hello, Python!”
# Slicing
first_five = text[:5]
last_five = text[-5:]
# Concatenation
new_text = text + “Welcome to programming!”
# Reversal
reversed_text = text[::-1]
# Searching
search_word = “Python”
found_index = text.find(search_word)
# Displaying results
print(“Original Text:”, text)
print(“First 5 characters:”, first_five)
print(“Last 5 characters:”, last_five)
print(“Concatenated String:”, new_text)
print(“Reversed String:”, reversed_text)
print(f‘ “{search_word}” found at index:’, found_index if found_index != -1 else “Not
found”)
Output:
Original Text: Hello, Python!
First 5 characters: Hello
Last 5 characters: thon!
Concatenated String: Hello, Python! Welcome to programming!
Reversed String: !nohtyP ,olleH
“Python” found at index: 7
Experiment – 3
Write a Python script to demonstrate the use of if-else, elif, while, and for loops with
examples.
# If-Else condition
if number > 0:
print(“Positive number”)
elif number < 0:
print(“Negative number”)
else:
print(“Zero”)
Output:
Enter a number: 5
Factorial of 5 is 120
Experiment – 5
Write a Python program to create a class, instantiate an object, and demonstrate class
variables and instance methods.
# Defining a class
class Student:
“““Class to represent a student”””
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def display_info(self):
“““Method to display student information”””
print(f “Student Name: {self.name}”)
print(f “Age: {self.age}”)
print(f “Grade: {self.grade}”)
Output:
Student Details:
Student Name: Alice
Age: 20
Grade: A
Experiment – 6
Develop a Python program that demonstrates single and multiple inheritances along
with method overriding.
# Parent class
class Animal:
def sound(self):
return “Animals make different sounds”
# Creating objects
animal = Animal()
dog = Dog()
cat = Cat()
hybrid = Hybrid()
# Displaying sounds
print(“Animal Sound:”, animal.sound())
print(“Dog Sound:”, dog.sound())
print(“Cat Sound:”, cat.sound())
print(“Hybrid Sound:”, hybrid.sound())
Output:
Animal Sound: Animals make different sounds
Dog Sound: Dog barks
Cat Sound: Cat meows
Hybrid Sound: Dog barks
Experiment – 7
Write a program to perform insertion, deletion, sorting, and searching on a list and
tuple.
# List operations
numbers = [5, 2, 9, 1, 5]
print(“Original List:”, numbers)
# Insertion
numbers.append(10)
print(“After Insertion:”, numbers)
# Deletion
numbers.remove(2)
print(“After Deletion:”, numbers)
# Sorting
numbers.sort()
print(“After Sorting:”, numbers)
# Searching
search_item = 5
if search_item in numbers:
print(f “{search_item} found at index {numbers.index(search_item)}”)
else:
print(f “{search_item} not found”)
# Tuple operations
tuple_numbers = (3, 6, 1, 9)
print(“Tuple:”, tuple_numbers)
# Searching in tuple
found = 6 in tuple_numbers
print(“Is 6 present in tuple?”, found)
Output:
Original List: [5, 2, 9, 1, 5]
After Insertion: [5, 2, 9, 1, 5, 10]
After Deletion: [5, 9, 1, 5, 10]
After Sorting: [1, 5, 5, 9, 10]
5 found at index 1
Tuple: (3, 6, 1, 9)
Is 6 present in tuple?: True
Experiment – 8
Implement a Python script that demonstrates union, intersection, difference, and subset
operations on sets.
# Defining sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
# Subset Check
subset_check = {1, 2}.issubset(set_a)
print(“Is {1, 2} a subset of set_a?:”, subset_check)
Output:
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Is {1, 2} a subset of set_a?: True
Experiment – 9
Write a Python script to create a dictionary, update, delete, and perform sorting on keys
and values.
# Creating a dictionary
dict_students = {“Alice”: 85, “Bob”: 90, “Charlie”: 78}
print(“Original Dictionary:”, dict_students)
def count_words(filename):
“““Function to count word occurrences in a file”””
with open(filename, ‘r’) as file:
words = file.read().split()
return Counter(words)
import sys
if len(sys.argv) != 3:
print(“Usage: python script.py <num1> <num2>”)
else:
num1, num2 = map(int, sys.argv[1:3])
arithmetic_operations(num1, num2)
Output:
python script.py 10 5
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Experiment – 12
Write a Python program using the re module to validate an email ID and phone number.
import re
def validate_email(email):
“““Function to validate an email address using regex”””
pattern = r‘^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$’
if re.match(pattern, email):
return True
return False
def validate_phone(phone):
“““Function to validate a phone number with 10 digits”””
pattern = r‘^\d{10}$’
if re.match(pattern, phone):
return True
return False
# Validating inputs
if validate_email(email):
print(“Valid Email”)
else:
print(“Invalid Email”)
if validate_phone(phone):
print(“Valid Phone Number”)
else:
print(“Invalid Phone Number”)
Output:
Enter an email: test@example.com
Enter a phone number: 9785850534
Valid Email
Valid Phone Number
Experiment – 13
Implement a program that demonstrates try-except blocks and custom exceptions.
Or
Enter numerator: -5
Enter denominator: 2
Error: Negative numbers are not allowed
Or
Enter numerator: 10
Enter denominator: 2
Division Result: 5.0
Experiment – 14
Write a Python script to implement a stack and queue using lists.
class Stack:
“““Class to implement stack operations”””
def __init__(self):
self.stack = []
def pop(self):
“““Removes the last item from the stack”””
return self.stack.pop() if self.stack else “Stack is empty”
def display(self):
“““Displays the current stack”””
print(“Stack:”, self.stack)
class Queue:
“““Class to implement queue operations”””
def __init__(self):
self.queue = []
def display(self):
“““Displays the current queue”””
print(“Queue:”, self.queue)
# Testing Stack
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
print(“Popped from Stack:”, stack.pop())
stack.display()
# Testing Queue
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.display()
print(“Dequeued from Queue:”, queue.dequeue())
queue.display()
Output:
Stack: [10, 20, 30]
Popped from Stack: 30
Stack: [10, 20]
Queue: [1, 2, 3]
Dequeued from Queue: 1
Queue: [2, 3]
Experiment – 15
Develop a Python program to connect to a database using SQLite, create tables, insert
data, and perform queries.
import sqlite3
# Creating a table
cursor.execute(“““
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)
”””)
# Inserting records
cursor.execute(“INSERT INTO students (name, age) VALUES (‘Alice’, 22)”)
cursor.execute(“INSERT INTO students (name, age) VALUES (‘Bob’, 25)”)
conn.commit()
# Fetching records
cursor.execute(“SELECT * FROM students”)
records = cursor.fetchall()
print(“Students in Database:”)
for record in records:
print(record)
# Closing connection
conn.close()
Output:
Students in Database:
(1, ‘Alice’, 22)
(2, ‘Bob’, 25)