PYTHON LAB MANUAL
EXPERIMENT 01
Q. Introduction to python programming and python data types. (CO1)
SOLUTION:
1. Introduction to Python Programming
Python is a high-level, interpreted, general-purpose programming language
created by Guido van Rossum and first released in 1991. Python is widely used
because of its simple syntax, readability, and versatility.
It is commonly used in:
Web development
Data science and machine learning
Automation and scripting
Artificial intelligence
Scientific computing
Software development
Features of Python
1. Easy to learn and read – simple English-like syntax
2. Interpreted language – code runs line by line without compilation
3. Portable – runs on Windows, Linux, and macOS
4. Open source – freely available
5. Large standard library – many built-in modules
6. Object-oriented – supports OOP concepts
Example of a Python Program
print("Hello, World!")
PYTHON LAB MANUAL 1
Output:
Hello, World!
Python Data Types
A data type specifies the type of value a variable can hold.
Example:
x = 10
Here x is an integer type.
Python automatically determines the data type, so it is called dynamically
typed.
Main Python Data Types
1. Numeric Data Types
Used to store numerical values.
Data Type Description Example
int Integer numbers 10, -5, 200
float Decimal numbers 3.14, 5.6
complex Complex numbers 3+4j
Example:
a = 10 # int
b = 3.5 # float
c = 2 + 3j # complex
2. Sequence Data Types
String (str)
Stores text data.
PYTHON LAB MANUAL 2
Example:
name = "Python"
Example operations:
print(name[0]) # first character
print(len(name)) # length
List
A mutable (changeable) ordered collection.
Example:
numbers = [10, 20, 30, 40]
Characteristics:
Ordered
Mutable
Allows duplicates
Tuple
An immutable ordered collection.
Example:
coordinates = (10, 20)
Characteristics:
Ordered
Cannot be modified
Faster than lists
3. Set
An unordered collection of unique elements.
PYTHON LAB MANUAL 3
Example:
fruits = {"apple", "banana", "mango"}
Characteristics:
No duplicates
Unordered
Mutable
4. Dictionary
Stores data in key-value pairs.
Example:
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
Access value:
print(student["name"])
5. Boolean Data Type
Represents True or False values.
Example:
x = True
y = False
Used in conditions and decision making.
Example:
print(5 > 3) # True
PYTHON LAB MANUAL 4
Summary
Data Type Example
int 10
float 3.14
complex 2+3j
str "Python"
list [1,2,3]
tuple (1,2,3)
set {1,2,3}
dict {"name":"Aman"}
bool True
Q1. What is Python?
Ans: Python is a high-level, interpreted, general-purpose programming
language known for its simple syntax and readability.
Q2. Who developed Python?
Ans: Python was developed by Guido van Rossum in 1991.
Q3. What are Python data types?
Ans: Data types define the type of data stored in a variable. Examples include
int , float , str , list , tuple , set , dictionary , and bool .
EXPERIMENT 02
Q. Python program to find the union of two lists.(CO1)
SOLUTION:
The union of two lists means combining the elements of both lists while
removing duplicate values.
Python Program
PYTHON LAB MANUAL 5
# Define two lists
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Find union using set
union_list = list(set(list1) | set(list2))
# Display result
print("List 1:", list1)
print("List 2:", list2)
print("Union of the two lists:", union_list)
Output
List 1: [1, 2, 3, 4]
List 2: [3, 4, 5, 6]
Union of the two lists: [1, 2, 3, 4, 5, 6]
Q1. What is union in lists?
Ans: Union combines elements of two lists and removes duplicate values.
Q2. Which data structure removes duplicates automatically?
Ans: The set data structure.
Q3. Which operator is used for union of sets?
Ans: The | operator.
EXPERIMENT 03
Q.3. Python program to find the intersection of two lists.(CO1)
SOLUTION:
The intersection of two lists means finding the common elements that appear
in both lists.
Python Program
PYTHON LAB MANUAL 6
# Define two lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# Find intersection using set
intersection_list = list(set(list1) & set(list2))
# Display the result
print("List 1:", list1)
print("List 2:", list2)
print("Intersection of the two lists:", intersection_list)
Output
List 1: [1, 2, 3, 4, 5]
List 2: [3, 4, 5, 6, 7]
Intersection of the two lists: [3, 4, 5]
Q1. What is intersection?
Ans: Intersection returns elements that are common in both lists.
Q2. Which operator is used for intersection in sets?
Ans: The & operator.
Q3. Why do we convert lists into sets for intersection?
Ans: Because sets support mathematical operations like intersection.
EXPERIMENT 04
Q. Python program to remove the “i” th occurrence of the given word in a list
where words repeat. (CO2)
SOLUTION:
This program removes the i-th occurrence of a specified word from a list
where words may repeat.
PYTHON LAB MANUAL 7
Python Program
# Function to remove the i-th occurrence of a word
def remove_ith_occurrence(lst, word, i):
count = 0
for index in range(len(lst)):
if lst[index] == word:
count += 1
if count == i:
[Link](index)
return lst
return lst
# List with repeating words
words = ["apple", "banana", "apple", "orange", "apple", "ba
nana"]
# Word and occurrence to remove
word = "apple"
i = 2
# Function call
result = remove_ith_occurrence(words, word, i)
print("Updated List:", result)
Output
Updated List: ['apple', 'banana', 'orange', 'apple', 'banan
a']
Q1. What does occurrence mean?
Ans: Occurrence refers to how many times an element appears in a list.
Q2. Which function removes an element by index?
Ans: pop() .
Q3. What is the purpose of a counter in this program?
PYTHON LAB MANUAL 8
Ans: To track the number of times the word appears.
EXPERIMENT 05
Q. Python program to count the occurrences of each word in a given string
sentence. (CO2)
SOLUTION:
This program counts how many times each word appears in a given sentence.
Python Program
# Input sentence
sentence = "python is easy and python is powerful"
# Split sentence into words
words = [Link]()
# Create empty dictionary
word_count = {}
# Count occurrences
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# Display result
print("Word occurrences:")
for word, count in word_count.items():
print(word, ":", count)
Output
Word occurrences:
python : 2
PYTHON LAB MANUAL 9
is : 2
easy : 1
and : 1
powerful : 1
Q1. Which function converts a sentence into a list of words?
Ans: split() .
Q2. Which data structure is used to store word frequency?
Ans: Dictionary.
Q3. What is word frequency?
Ans: The number of times a word appears in a sentence.
EXPERIMENT 06
Q. Python program to check if a substring is present in a given string. (CO2)
SOLUTION:
This program checks whether a substring exists inside a given string.
Python Program
# Given string
string = "Python programming is easy"
# Substring to check
substring = "programming"
# Check if substring exists
if substring in string:
print("Substring is present in the string")
else:
print("Substring is not present in the string")
Output
PYTHON LAB MANUAL 10
Substring is present in the string
Q1. What is a substring?
Ans: A substring is a smaller string inside another string.
Q2. Which operator checks substring presence?
Ans: in operator.
Q3. What will the program return if substring is not found?
Ans: It prints that the substring is not present.
EXPERIMENT 07
Q. Python program to map two lists into a dictionary. (CO3)
SOLUTION :
This program maps two lists into a dictionary, where one list contains keys
and the other contains values.
Python Program
# First list (keys)
keys = ["name", "age", "course"]
# Second list (values)
values = ["Rahul", 20, "Python"]
# Map two lists into dictionary
result = dict(zip(keys, values))
# Display dictionary
print("Dictionary:", result)
Output
PYTHON LAB MANUAL 11
Dictionary: {'name': 'Rahul', 'age': 20, 'course': 'Pytho
n'}
Q1. What is a dictionary in Python?
Ans: A collection of key-value pairs.
Q2. Which function combines two lists into pairs?
Ans: zip() .
Q3. How do we convert zipped pairs into a dictionary?
Ans: Using dict() .
EXPERIMENT 08
Q. Python program to count the frequency of words appearing in a string using
a dictionary.(CO3)
SOLUTION:
This program counts how many times each word appears in a given string
using a dictionary.
Python Program
# Input string
string = "python is easy and python is powerful"
# Split the string into words
words = [Link]()
# Create an empty dictionary
frequency = {}
# Count word frequency
for word in words:
if word in frequency:
frequency[word] += 1
else:
PYTHON LAB MANUAL 12
frequency[word] = 1
# Display the result
print("Word Frequency:")
for key, value in [Link]():
print(key, ":", value)
Output
Word Frequency:
python : 2
is : 2
easy : 1
and : 1
powerful : 1
Q1. What is the key in the dictionary for this program?
Ans: The word itself.
Q2. What is the value stored in the dictionary?
Ans: The number of occurrences of the word.
Q3. Why is dictionary suitable for frequency counting?
Ans: Because it stores unique keys with associated values.
EXPERIMENT 09
Q. Python program to create a dictionary with key as first character and value
as words starting With that character. (CO3)
SOLUTION:
This program creates a dictionary where the key is the first letter of a word
and the value is the list of words starting with that letter.
Python Program
PYTHON LAB MANUAL 13
# List of words
words = ["apple", "banana", "apricot", "cherry", "blueberr
y", "avocado"]
# Empty dictionary
result = {}
# Loop through words
for word in words:
key = word[0] # first character of the word
if key in result:
result[key].append(word)
else:
result[key] = [word]
# Print the dictionary
print("Dictionary:", result)
Output
Dictionary: {
'a': ['apple', 'apricot', 'avocado'],
'b': ['banana', 'blueberry'],
'c': ['cherry']
}
Q1. What is the key used in this dictionary?
Ans: The first character of the word.
Q2. How do we access the first character of a string?
Ans: Using indexing like word[0] .
Q3. What type of value is stored in the dictionary?
Ans: A list of words starting with the same character.
PYTHON LAB MANUAL 14
EXPERIMENT 10
Q. Python Program to Find the Length of a List Using Recursion (CO4)
SOLUTION:
Recursion is a technique where a function calls itself to solve a problem.
This program finds the length of a list recursively.
Python Program
# Recursive function to find length of list
def list_length(lst):
if lst == []: # Base case
return 0
else:
return 1 + list_length(lst[1:]) # Recursive case
# Example list
my_list = [10, 20, 30, 40, 50]
# Function call
length = list_length(my_list)
print("Length of the list:", length)
Output
Length of the list: 5
Q1. What is recursion?
Ans: Recursion is when a function calls itself.
Q2. What is the base case in recursion?
Ans: The condition that stops recursion.
Q3. What happens if there is no base case?
Ans: The program may run infinitely and cause an error.
PYTHON LAB MANUAL 15
EXPERIMENT 11
Q. Python program to read a file and capitalize the first letter of every word in
the file.(CO4)
SOLUTION:
This program reads the content of a file and capitalizes the first letter of each
word.
Python Program
# Open the file in read mode
file = open("[Link]", "r")
# Read the content of the file
content = [Link]()
# Close the file
[Link]()
# Capitalize the first letter of every word
capitalized_content = [Link]()
# Print the result
print("Content after capitalization:")
print(capitalized_content)
Example File Content ([Link])
python programming is very useful
it is easy to learn
Output
Content after capitalization:
Python Programming Is Very Useful
PYTHON LAB MANUAL 16
It Is Easy To Learn
Q1. Which function reads file content?
Ans: read() .
Q2. Which string function capitalizes words?
Ans: title() .
Q3. What is file handling?
Ans: The process of reading, writing, and managing files.
EXPERIMENT 12
Q. Python program to read the contents of a file in reverse order .(CO4)
SOLUTION:
This program reads a file and prints its content in reverse order.
Python Program
# Open the file in read mode
file = open("[Link]", "r")
# Read the file content
content = [Link]()
# Close the file
[Link]()
# Reverse the content
reverse_content = content[::-1]
# Display the reversed content
print("Content in reverse order:")
print(reverse_content)
Example File Content ([Link])
PYTHON LAB MANUAL 17
Python programming is fun
Output
Content in reverse order:
nuf si gnimmargorp nohtyP
Q1. What is slicing in Python?
Ans: A method to access parts of a sequence.
Q2. Which slicing syntax reverses a string?
Ans: [::-1] .
Q3. Why do we close files after reading?
Ans: To free system resources.
EXPERIMENT 13
Q. Python program to create a class in which one method accepts a string from
the user and another prints it. .(CO5)
SOLUTION:
This program creates a class with two methods:
One method to accept a string from the user.
Another method to print the string.
Python Program
# Create a class
class MyString:
# Method to accept string from user
def getString(self):
[Link] = input("Enter a string: ")
# Method to print the string
PYTHON LAB MANUAL 18
def printString(self):
print("The entered string is:", [Link])
# Create object of the class
obj = MyString()
# Call methods
[Link]()
[Link]()
Example Output
Enter a string: Python Programming
The entered string is: Python Programming
Q1. What is a class?
Ans: A blueprint for creating objects.
Q2. What is an object?
Ans: An instance of a class.
Q3. What is the purpose of self in Python classes?
Ans: It refers to the current object of the class.
EXPERIMENT 14
Q. Study and Implementation of Database, Structured Query Language and
database connectivity.(CO5)
SOLUTION:
1. Database
A Database is an organized collection of data that can be easily accessed,
managed, and updated. Databases help store large amounts of information
efficiently.
Example:
PYTHON LAB MANUAL 19
Student records
Employee information
Bank accounts
Library management data
A software used to manage databases is called a DBMS (Database
Management System) such as MySQL, Oracle Database, and SQLite.
2. Structured Query Language (SQL)
Structured Query Language (SQL) is a standard language used to create,
manage, and manipulate databases.
Types of SQL Commands
Type Description Example
DDL Data Definition Language CREATE, ALTER, DROP
DML Data Manipulation Language INSERT, UPDATE, DELETE
DQL Data Query Language SELECT
DCL Data Control Language GRANT, REVOKE
Example SQL Commands
Create Table:
CREATE TABLE Student(
id INT,
name VARCHAR(50),
age INT
);
Insert Data:
INSERT INTO Student VALUES(1,'Rahul',20);
Retrieve Data:
PYTHON LAB MANUAL 20
SELECT * FROM Student;
3. Database Connectivity
Database connectivity allows a program to connect and interact with a
database using a programming language.
For example, Python can connect to databases using libraries such as:
sqlite3
mysql-connector
psycopg2
Example: Python Program for Database Connectivity
(Using SQLite)
import sqlite3
# Connect to database
conn = [Link]("[Link]")
# Create cursor object
cursor = [Link]()
# Create table
[Link]("CREATE TABLE IF NOT EXISTS Student(id INT,
name TEXT, age INT)")
# Insert data
[Link]("INSERT INTO Student VALUES(1,'Rahul',20)")
# Display data
[Link]("SELECT * FROM Student")
rows = [Link]()
for row in rows:
print(row)
PYTHON LAB MANUAL 21
# Save changes
[Link]()
# Close connection
[Link]()
Output
(1, 'Rahul', 20)
Q1. What is a database?
Ans: A structured collection of data stored electronically.
Q2. What is SQL?
Ans: SQL (Structured Query Language) is used to manage and manipulate
databases.
Q3. Which Python module is commonly used for SQLite database
connectivity?
Ans: sqlite3 .
PYTHON LAB MANUAL 22