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.
# Demonstrating Variables and Data Types
num1 = 10 # Integer
decimal = 3.14 # Float
name = “Python” # String
complex_num = 2 + 3j # Complex number
# Printing types of variables
print(“Type of num1:”, type(num1))
print(“Type of decimal:”, type(decimal))
print(“Type of name:”, type(name))
print(“Type of complex_num:”, type(complex_num))
# 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.
# Conditional Statements and Loops
number = int(input(“Enter a number: ”))
# If-Else condition
if number > 0:
print(“Positive number”)
elif number < 0:
print(“Negative number”)
else:
print(“Zero”)
# Looping through a range
print(“Counting from 1 to 5 using for loop:”)
for i in range(1, 6):
print(i)
# While loop example
print(“Counting from 5 to 1 using while loop:”)
count = 5
while count > 0:
print(count)
count = 1
Output:
Enter a number: 3
Positive number
Counting from 1 to 5 using for loop:
1
2
3
4
5
Counting from 5 to 1 using while loop:
5
4
3
2
1
Experiment – 4
Create a Python program with user-defined functions and implement a recursive
function to compute factorial.
# Function to compute factorial using recursion
def factorial(n):
“““Function to calculate factorial using recursion”””
if n = = 0 or n = = 1:
return 1
else:
return n * factorial(n - 1)
# Taking user input
num = int(input(“Enter a number: ”))
# Checking for negative input
if num < 0:
print(“Factorial is not defined for negative numbers.”)
else:
result = factorial(num)
print(f “Factorial of {num} is {result}”)
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}”)
# Creating an object of Student class
student1 = Student(“Alice”, 20, “A”)
# Calling the method to display student information
print(“Student Details:”)
student1.display_info()
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”
# Child class inheriting from Animal
class Dog(Animal):
def sound(self):
return “Dog barks”
# Another child class inheriting from Animal
class Cat(Animal):
def sound(self):
return “Cat meows”
# Multiple Inheritance Example
class Hybrid(Animal, Dog):
pass # Inherits properties from both classes
# 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}
# Union - Combines all unique elements from both sets
union_set = set_a | set_b
print(“Union:”, union_set)
# Intersection - Elements common in both sets
intersection_set = set_a & set_b
print(“Intersection:”, intersection_set)
# Difference - Elements in set_a but not in set_b
difference_set = set_a - set_b
print(“Difference (A - B):”, difference_set)
# 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)
# Adding a new key-value pair
dict_students[“David”] = 88
print(“After Adding David:”, dict_students)
# Updating an existing value
dict_students[“Alice”] = 95
print(“After Updating Alice's Score:”, dict_students)
# Deleting a key-value pair
del dict_students[“Charlie”]
print(“After Deleting Charlie:”, dict_students)
# Sorting dictionary by keys
sorted_keys = sorted(dict_students.keys())
print(“Sorted Keys:”, sorted_keys)
# Sorting dictionary by values
sorted_values = sorted(dict_students.items(), key=lambda item: item[1])
print(“Sorted by Values:”, sorted_values)
Output:
Original Dictionary: {'Alice': 85, 'Bob': 90, 'Charlie': 78}
After Adding David: {'Alice': 85, 'Bob': 90, 'Charlie': 78, 'David': 88}
After Updating Alice's Score: {'Alice': 95, 'Bob': 90, 'Charlie': 78, 'David': 88}
After Deleting Charlie: {'Alice': 95, 'Bob': 90, 'David': 88}
Sorted Keys: ['Alice', 'Bob', 'David']
Sorted by Values: [('David', 88), ('Bob', 90), ('Alice', 95)]
Experiment – 10
Develop a program that reads a file, counts the frequency of words, and writes the
output to a new file.
from collections import Counter
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)
# File reading and writing
input_filename = “sample.txt”
word_count = count_words(input_filename)
# Writing output to a new file
output_filename = “word_count_output.txt”
with open(output_filename, ‘w’) as file:
for word, count in word_count.items():
file.write(f “{word}: {count}\n”)
print(“Word frequency count written to”, output_filename)
Output (in output file word_count_output.txt):
Python: 3
is: 2
fun: 1
Experiment – 11
Create a Python script that accepts command-line arguments and performs arithmetic
operations based on input.
import sys
def arithmetic_operations(a, b):
print(“Addition:”, a + b)
print(“Subtraction:”, a - b)
print(“Multiplication:”, a * b)
print(“Division:”, a / b)
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
# Taking user input
email = input(“Enter an email: ”)
phone = input(“Enter a phone number: ”)
# 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: [email protected]
Enter a phone number: 9785850534
Valid Email
Valid Phone Number
Experiment – 13
Implement a program that demonstrates try-except blocks and custom exceptions.
# Custom Exception Class
class NegativeNumberError(Exception):
“““Custom Exception for negative numbers”””
pass
def divide(a, b):
try:
if a < 0 or b < 0:
raise NegativeNumberError(“Negative numbers are not allowed”)
result = a / b
print(“Division Result:”, result)
except ZeroDivisionError:
print(“Error: Division by zero is not allowed”)
except NegativeNumberError as e:
print(“Error:”, e)
# Taking user input
try:
num1 = int(input(“Enter numerator: ”))
num2 = int(input(“Enter denominator: ”))
divide(num1, num2)
except ValueError:
print(“Invalid input! Please enter numeric values.”)
Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed
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 push(self, item):
“““Adds an item to the stack”””
self.stack.append(item)
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 enqueue(self, item):
“““Adds an item to the queue”””
self.queue.append(item)
def dequeue(self):
“““Removes the first item from the queue”””
return self.queue.pop(0) if self.queue else “Queue is empty”
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
# Connecting to SQLite database
conn = sqlite3.connect(“students.db”)
cursor = conn.cursor()
# 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)