Python Programming Lab Manual
Python Programming Lab Manual
LABORATORY
Laboratory Manual / Record
List of Experiments
[Link] Experiment
1 Write and execute a simple Python Program
2 Program to demonstrate various data types in Python
3 Develop minimum 2 programs using different data types (numbers, string, tuple, list and dictionary)
4 Program to perform different Arithmetic Operations on numbers in Python
5 Develop minimum 2 programs using Arithmetic Operators, exhibiting data type conversion
6 Python script that prints prime numbers less than 20
7 (i) Convert U.S. dollars to Indian rupees (ii) Convert bits to Megabytes, Gigabytes and Terabytes
8 Calculate area and perimeter of a square, and volume and surface area of a cone
9 (i) Determine whether a given number is odd or even (ii) Find the greatest of three numbers using
conditional operators
10 (i) Find factorial of a given number (ii) Generate multiplication table up to 10 for numbers 1 to 5
11 Find factorial of a number using Recursion
12 Print Factors of a given Number
13 (i) Find factorial of a given number (ii) Generate multiplication table up to 10 for numbers 1 to 5,
using functions
14 (i) Find factorial of a given number using recursion (ii) Generate Fibonacci sequence up to 100 using
recursion
15 Define a module to find Fibonacci Numbers and import the module into another program
16 Define a module and import a specific function in that module into another program
17 Create, concatenate and print a string and access a sub-string from a given string
18 Create a list, add element to list, delete element from the list
19 Sort the list, reverse the list and count elements in a list
20 Demonstrate working with tuples in python
[Link] Experiment
21 Create dictionary, add element to dictionary, delete element from the dictionary
22 Calculate average, mean, median, and standard deviation of numbers in a list
23 (i) Create a simple file and write "Hello World" in it (ii) Open a file in write mode and append "Hello
World" at the end of a file
24 (i) Open a file in read mode and write its contents to another file replacing every 'h' with 'H' (ii) Open
a file in read mode and count occurrences of character 'a'
25 Print all unique words in a text file in alphabetical order
26 Load a CSV into a dataframe using pandas and perform arithmetic operations on the data
27 Create a 5 x 5 Numpy array with random integers between 1 and 100
28 Handle built-in exceptions (ZeroDivisionError, IndexError, NameError)
Experiment 1
Write and execute a simple Python Program
Aim
To write and execute a simple Python program that accepts two numbers from the user and prints their sum.
Algorithm
1. Start.
2. Display a message and read the first number from the user.
3. Read the second number from the user.
4. Compute the sum of the two numbers.
5. Print the result.
6. Stop.
Program
# Simple Python Program
print("Welcome to Python Programming")
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("The sum of", a, "and", b, "is", sum)
Description
This program demonstrates the basic structure of a Python program including printing text, reading input using
input(), converting the input to an integer using int(), and displaying the result using print().
Input
Enter first number: 10
Enter second number: 20
Output
Welcome to Python Programming
The sum of 10 and 20 is 30
Result
The Python program to accept two numbers and display their sum was executed successfully and the output was
verified.
Experiment 2
Program to demonstrate various data types in Python
Aim
To write a Python program that declares variables of various data types and displays their values and types.
Algorithm
1. Start.
2. Declare a variable of type integer and assign a value.
3. Declare a variable of type float and assign a value.
4. Declare a variable of type string and assign a value.
5. Declare a variable of type boolean, list, tuple and dictionary.
6. Print each variable along with its type using type().
7. Stop.
Program
# Demonstration of various data types
a = 25 # int
b = 3.14 # float
c = "Python" # str
d = True # bool
e = [1, 2, 3] # list
f = (10, 20, 30) # tuple
g = {"name": "Rahul", "age": 21} # dict
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))
print(f, type(f))
print(g, type(g))
Description
This program illustrates Python's built-in data types - int, float, str, bool, list, tuple and dict - and uses the type()
function to display the type of each variable.
Input
No input required (values are hard-coded).
Output
25 <class 'int'>
3.14 <class 'float'>
Python <class 'str'>
True <class 'bool'>
[1, 2, 3] <class 'list'>
(10, 20, 30) <class 'tuple'>
{'name': 'Rahul', 'age': 21} <class 'dict'>
Result
The Python program to demonstrate various data types was executed successfully and the type of each variable was
verified.
Experiment 3
Develop minimum 2 programs using different data types (numbers, string, tuple, list and
dictionary)
Aim
To develop two Python programs that make use of different data types such as numbers, strings, tuples, lists and
dictionaries.
Algorithm
1. Program 1: Start.
2. Read a string and a number from the user.
3. Create a list and a tuple with sample elements.
4. Create a dictionary with key-value pairs.
5. Display all the values. Stop.
6. Program 2: Start.
7. Perform operations such as indexing and slicing on the string, list and tuple.
8. Access dictionary elements using keys.
9. Display the results. Stop.
Program
# Program 1: Working with different data types
name = input("Enter your name: ")
age = int(input("Enter your age: "))
marks = [88, 92, 79] # list
subjects = ("Python", "DBMS", "OS") # tuple
student = {"name": name, "age": age} # dictionary
print("Name:", name)
print("Age:", age)
print("Marks list:", marks)
print("Subjects tuple:", subjects)
print("Student dictionary:", student)
Description
The first program stores data using a number, string, list, tuple and dictionary and displays them. The second
program demonstrates indexing and slicing on strings, lists and tuples, and key-based access on dictionaries.
Input
Enter your name: Sneha
Enter your age: 20
Output
Name: Sneha
Age: 20
Marks list: [88, 92, 79]
Subjects tuple: ('Python', 'DBMS', 'OS')
Student dictionary: {'name': 'Sneha', 'age': 20}
First 6 chars: Python
List slice: [20, 30, 40]
Tuple element: 5
Dictionary value: Sneha
Result
Two Python programs demonstrating numbers, strings, tuples, lists and dictionaries were developed and executed
successfully.
Experiment 4
Program to perform different Arithmetic Operations on numbers in Python
Aim
To write a Python program to perform addition, subtraction, multiplication, division, floor division, modulus and
exponentiation on two numbers.
Algorithm
1. Start.
2. Read two numbers a and b from the user.
3. Compute sum, difference, product, quotient, floor division, remainder and power.
4. Display all the results.
5. Stop.
Program
# Arithmetic Operations
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Description
This program reads two numbers and applies Python's arithmetic operators (+, -, *, /, //, %, **) to demonstrate all
standard arithmetic operations.
Input
Enter first number: 15
Enter second number: 4
Output
Addition: 19.0
Subtraction: 11.0
Multiplication: 60.0
Division: 3.75
Floor Division: 3.0
Modulus: 3.0
Exponentiation: 50625.0
Result
The Python program to perform different arithmetic operations on numbers was executed successfully.
Experiment 5
Develop minimum 2 programs using Arithmetic Operators, exhibiting data type conversion
Aim
To develop two Python programs that use arithmetic operators along with explicit and implicit data type conversion.
Algorithm
1. Program 1: Start.
2. Read a number as a string, convert it to int and float.
3. Perform arithmetic operations after conversion.
4. Display results. Stop.
5. Program 2: Start.
6. Take an integer and a float and observe implicit conversion during an operation.
7. Convert the result to int and str explicitly.
8. Display results. Stop.
Program
# Program 1: Explicit type conversion
num_str = input("Enter a number as text: ")
num_int = int(num_str)
num_float = float(num_str)
print("As integer + 5:", num_int + 5)
print("As float / 2:", num_float / 2)
Description
The first program converts user-entered text into int and float types using int() and float(). The second program
shows implicit conversion when an int and a float are combined, followed by explicit conversion to int and str using
casting functions.
Input
Enter a number as text: 12
Output
As integer + 5: 17
As float / 2: 6.0
i + f = 13.5 <class 'float'>
As int: 13
As string: 13.5 <class 'str'>
Result
Two Python programs demonstrating arithmetic operators along with data type conversion were executed
successfully.
Experiment 6
Python script that prints prime numbers less than 20
Aim
To write a Python script to print all prime numbers less than 20.
Algorithm
1. Start.
2. Set n = 20 (upper limit).
3. For every number i from 2 to n-1, check divisibility from 2 to i-1.
4. If no divisor is found, i is prime; print it.
5. Repeat for all numbers less than n.
6. Stop.
Program
# Prime numbers less than 20
n = 20
print("Prime numbers less than", n, "are:")
for num in range(2, n):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Description
This script iterates through numbers from 2 to 19 and, for each number, checks whether it has any divisor other than
1 and itself using a nested loop. Numbers with no such divisor are printed as prime.
Input
No input required (n = 20 is fixed in the program).
Output
Prime numbers less than 20 are:
2 3 5 7 11 13 17 19
Result
The Python script to print prime numbers less than 20 was executed successfully.
Experiment 7
(i) Convert U.S. dollars to Indian rupees (ii) Convert bits to Megabytes, Gigabytes and
Terabytes
Aim
To write simple Python programs to (i) convert U.S. dollars to Indian rupees and (ii) convert bits to megabytes,
gigabytes and terabytes.
Algorithm
1. Program (i): Start.
2. Read the amount in U.S. dollars.
3. Multiply the amount by the conversion rate to get rupees.
4. Display the result. Stop.
5. Program (ii): Start.
6. Read the number of bits.
7. Convert bits to bytes, then to MB, GB and TB using division.
8. Display all the results. Stop.
Program
# (i) USD to INR conversion
usd = float(input("Enter amount in US dollars: "))
rate = 83.50
inr = usd * rate
print("US $", usd, "= Rs.", round(inr, 2))
Description
The first program converts a dollar amount to Indian rupees using a fixed exchange rate. The second program
converts a value given in bits to bytes and then to MB, GB and TB by successive division by 1024.
Input
Enter amount in US dollars: 100
Enter size in bits: 8589934592
Output
US $ 100.0 = Rs. 8350.0
Bits: 8589934592.0
Megabytes: 1024.0
Gigabytes: 1.0
Terabytes: 0.0009765625
Result
The Python programs for currency conversion and digital storage unit conversion were executed successfully.
Experiment 8
Calculate area and perimeter of a square, and volume and surface area of a cone
Aim
To write simple Python programs to calculate the area and perimeter of a square, and the volume and surface area of
a cone.
Algorithm
1. Program 1: Start.
2. Read the side of the square.
3. Compute area = side*side and perimeter = 4*side.
4. Display the results. Stop.
5. Program 2: Start.
6. Read the radius and height of the cone.
7. Compute volume = (1/3)*pi*r^2*h.
8. Compute slant height and surface area.
9. Display the results. Stop.
Program
import math
Description
The first part computes the area and perimeter of a square using its side length. The second part computes the
volume and total surface area of a cone using its radius and height, applying the standard mensuration formulae with
the math module.
Input
Enter side of the square: 5
Enter radius of cone: 3
Enter height of cone: 4
Output
Area of square: 25.0
Perimeter of square: 20.0
Volume of cone: 37.7
Surface area of cone: 75.4
Result
The Python programs to compute area/perimeter of a square and volume/surface area of a cone were executed
successfully.
Experiment 9
(i) Determine whether a given number is odd or even (ii) Find the greatest of three numbers
using conditional operators
Aim
To write Python programs to (i) determine whether a given number is odd or even and (ii) find the greatest of three
numbers using conditional (ternary) operators.
Algorithm
1. Program (i): Start.
2. Read a number n.
3. If n % 2 == 0, it is even, else it is odd.
4. Display the result. Stop.
5. Program (ii): Start.
6. Read three numbers a, b, c.
7. Use the conditional operator to find the greatest among them.
8. Display the result. Stop.
Program
# (i) Odd or Even
n = int(input("Enter a number: "))
result = "Even" if n % 2 == 0 else "Odd"
print(n, "is", result)
Description
The first program uses the modulus operator with a conditional (ternary) expression to check whether a number is
odd or even. The second program uses nested conditional operators to determine the greatest of three input numbers.
Input
Enter a number: 17
Enter first number: 12
Enter second number: 45
Enter third number: 30
Output
17 is Odd
The greatest number is: 45
Result
The Python programs using conditional operators for odd/even check and finding the greatest of three numbers were
executed successfully.
Experiment 10
(i) Find factorial of a given number (ii) Generate multiplication table up to 10 for numbers 1 to
5
Aim
To write a Python program to (i) find the factorial of a given number and (ii) generate the multiplication table up to
10 for numbers 1 to 5.
Algorithm
1. Program (i): Start.
2. Read a number n.
3. Initialize fact = 1.
4. Multiply fact by each number from 1 to n using a loop.
5. Display fact. Stop.
6. Program (ii): Start.
7. For each number i from 1 to 5, for each j from 1 to 10, print i * j.
8. Stop.
Program
# (i) Factorial of a number
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial of", n, "is", fact)
Description
The first program computes the factorial of a number using an iterative loop. The second program uses nested for
loops to print the multiplication table (1 to 10) for each number from 1 to 5.
Input
Enter a number: 5
Output
Factorial of 5 is 120
Table of 1
1 x 1 = 1
...
1 x 10 = 10
Table of 2
2 x 1 = 2
...
2 x 10 = 20
(similarly for 3, 4 and 5)
Result
The Python programs to find the factorial of a number and generate multiplication tables were executed
successfully.
Experiment 11
Find factorial of a number using Recursion
Aim
To write a Python program to find the factorial of a given number using recursion.
Algorithm
1. Start.
2. Define a recursive function factorial(n).
3. If n == 0 or n == 1, return 1 (base case).
4. Else, return n * factorial(n - 1) (recursive case).
5. Read a number from the user and call the function.
6. Display the result.
7. Stop.
Program
# Factorial using Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Description
This program defines a recursive function factorial() that calls itself with a decremented value of n until the base
case (n == 0 or n == 1) is reached, then returns the product of all values back up the call stack.
Input
Enter a number: 6
Output
Factorial of 6 is 720
Result
The Python program to find the factorial of a number using recursion was executed successfully.
Experiment 12
Print Factors of a given Number
Aim
To write a Python program to print all the factors of a given number.
Algorithm
1. Start.
2. Read a number n.
3. For every number i from 1 to n, check if n % i == 0.
4. If true, i is a factor; print it.
5. Repeat for all numbers up to n.
6. Stop.
Program
# Factors of a number
n = int(input("Enter a number: "))
print("Factors of", n, "are:")
for i in range(1, n + 1):
if n % i == 0:
print(i, end=" ")
Description
This program iterates through all numbers from 1 to n and prints those numbers that divide n exactly (remainder
zero), which are the factors of n.
Input
Enter a number: 36
Output
Factors of 36 are:
1 2 3 4 6 9 12 18 36
Result
The Python program to print the factors of a given number was executed successfully.
Experiment 13
(i) Find factorial of a given number (ii) Generate multiplication table up to 10 for numbers 1 to
5, using functions
Aim
To write a Python program using user-defined functions to (i) find the factorial of a number and (ii) generate the
multiplication table up to 10 for numbers 1 to 5.
Algorithm
1. Start.
2. Define a function factorial(n) that computes factorial iteratively.
3. Define a function multiplication_table(i) that prints the table of i up to 10.
4. Read a number and call factorial() to display its factorial.
5. Call multiplication_table() for numbers 1 to 5 in a loop.
6. Stop.
Program
# Factorial and multiplication table using functions
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
def multiplication_table(num):
print("\nTable of", num)
for j in range(1, 11):
print(num, "x", j, "=", num * j)
Description
This program defines two separate user-defined functions: factorial() to compute the factorial of a number and
multiplication_table() to print the table of a given number, and calls them to display the required output.
Input
Enter a number to find factorial: 4
Output
Factorial of 4 is 24
Table of 1
1 x 1 = 1
...
Table of 2
2 x 1 = 2
...
(tables for 3, 4 and 5 follow similarly)
Result
The Python program using functions to find factorial and generate multiplication tables was executed successfully.
Experiment 14
(i) Find factorial of a given number using recursion (ii) Generate Fibonacci sequence up to 100
using recursion
Aim
To write a Python program to (i) find the factorial of a number using recursion and (ii) generate the Fibonacci
sequence up to 100 using recursion.
Algorithm
1. Program (i): Define factorial(n) recursively as in Experiment 11.
2. Program (ii): Start.
3. Define a recursive function fibonacci(n) where fibonacci(0)=0, fibonacci(1)=1.
4. For n>1, return fibonacci(n-1) + fibonacci(n-2).
5. Generate and print Fibonacci numbers while the value is less than 100.
6. Stop.
Program
# (i) Factorial using recursion
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
Description
The factorial() function recurses down to the base case n<=1. The fibonacci() function recursively computes each
Fibonacci number as the sum of the two preceding numbers, and the driver loop prints values until the term reaches
or exceeds 100.
Input
Enter a number: 5
Output
Factorial of 5 is 120
Result
The Python program to find factorial using recursion and generate the Fibonacci sequence up to 100 using recursion
was executed successfully.
Experiment 15
Define a module to find Fibonacci Numbers and import the module into another program
Aim
To write a Python program that defines a module to generate Fibonacci numbers and import that module into
another program.
Algorithm
1. Start.
2. Create a file fibo_module.py containing a function fibonacci(n) that returns the Fibonacci series up to n terms.
3. Create a second file that imports fibo_module.
4. Call the fibonacci() function from the imported module with a value of n.
5. Display the returned series.
6. Stop.
Program
# File 1: fibo_module.py
def fibonacci(n):
series = []
a, b = 0, 1
for _ in range(n):
[Link](a)
a, b = b, a + b
return series
# File 2: main_program.py
import fibo_module
Description
The Fibonacci-generating logic is placed in a separate module named fibo_module.py. The main program imports
this module using the import statement and calls fibo_module.fibonacci() to reuse the functionality without rewriting
the logic.
Input
Enter number of Fibonacci terms: 8
Output
Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13]
Result
The Python program demonstrating creation and import of a user-defined module for Fibonacci numbers was
executed successfully.
Experiment 16
Define a module and import a specific function in that module into another program
Aim
To write a Python program that defines a module containing multiple functions and import only a specific function
from it into another program.
Algorithm
1. Start.
2. Create a file calc_module.py containing multiple functions such as add(), subtract() and multiply().
3. Create a second file that imports only one specific function using 'from module import function'.
4. Call the imported function with sample arguments.
5. Display the result.
6. Stop.
Program
# File 1: calc_module.py
def add(a, b):
return a + b
# File 2: main_program.py
from calc_module import add # importing only the add function
Description
The module calc_module.py defines several functions, but the main program uses 'from calc_module import add' to
import only the required add() function, keeping the namespace clean and demonstrating selective import.
Input
Enter first number: 25
Enter second number: 15
Output
Sum: 40
Result
The Python program demonstrating the import of a specific function from a user-defined module was executed
successfully.
Experiment 17
Create, concatenate and print a string and access a sub-string from a given string
Aim
To write a Python program to create, concatenate and print a string and to access a substring from a given string.
Algorithm
1. Start.
2. Read two strings from the user.
3. Concatenate the two strings using the '+' operator.
4. Print the concatenated string.
5. Extract a substring using slicing.
6. Display the substring.
7. Stop.
Program
# String creation, concatenation and substring access
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
Description
This program reads two strings, concatenates them using the '+' operator and uses Python's slicing notation
[start:end] to extract substrings from the resulting string.
Input
Enter first string: Python
Enter second string: Programming
Output
Concatenated string: Python Programming
Length of concatenated string: 19
Substring (first 5 characters): Pytho
Substring (using indices 6 to 11): Progr
Result
The Python program to create, concatenate and access a substring from a string was executed successfully.
Experiment 18
Create a list, add element to list, delete element from the list
Aim
To write a Python program to create a list, add elements to it and delete elements from it.
Algorithm
1. Start.
2. Create a list with initial elements.
3. Print the list.
4. Add an element using append() and insert().
5. Print the updated list.
6. Delete an element using remove() and pop().
7. Print the final list.
8. Stop.
Program
# List operations
fruits = ["apple", "banana", "mango"]
print("Original list:", fruits)
Description
This program creates a list of fruits and demonstrates adding elements using append() and insert(), and removing
elements using remove() (by value) and pop() (by position, default last).
Input
No input required (list elements are predefined).
Output
Original list: ['apple', 'banana', 'mango']
After adding elements: ['apple', 'orange', 'banana', 'mango', 'grapes']
Removed element (pop): grapes
Final list: ['apple', 'orange', 'mango']
Result
The Python program to create a list and add/delete elements from it was executed successfully.
Experiment 19
Sort the list, reverse the list and count elements in a list
Aim
To write a Python program to sort a list, reverse a list and count the number of elements in a list.
Algorithm
1. Start.
2. Create a list of numbers.
3. Sort the list using sort().
4. Print the sorted list.
5. Reverse the list using reverse().
6. Print the reversed list.
7. Count the number of elements using len().
8. Stop.
Program
# Sorting, reversing and counting elements of a list
numbers = [45, 12, 78, 3, 67, 21]
print("Original list:", numbers)
[Link]()
print("Sorted list:", numbers)
[Link]()
print("Reversed list:", numbers)
Description
This program sorts a list of numbers in ascending order using sort(), reverses the order of elements using reverse(),
and counts the total number of elements using len() as well as occurrences of a specific value using count().
Input
No input required (list elements are predefined).
Output
Original list: [45, 12, 78, 3, 67, 21]
Sorted list: [3, 12, 21, 45, 67, 78]
Reversed list: [78, 67, 45, 21, 12, 3]
Number of elements in list: 6
Count of value 67: 1
Result
The Python program to sort, reverse and count elements in a list was executed successfully.
Experiment 20
Demonstrate working with tuples in python
Aim
To write a Python program to demonstrate the creation and various operations on tuples.
Algorithm
1. Start.
2. Create a tuple with sample elements.
3. Access elements using indexing and slicing.
4. Demonstrate that tuples are immutable.
5. Perform concatenation and repetition of tuples.
6. Use built-in functions such as len(), min(), max() and count().
7. Stop.
Program
# Tuple operations
t1 = (10, 20, 30, 40, 50)
print("Tuple:", t1)
print("Element at index 2:", t1[2])
print("Sliced tuple:", t1[1:4])
t2 = (60, 70)
concat_tuple = t1 + t2 # concatenation
print("Concatenated tuple:", concat_tuple)
repeat_tuple = t2 * 2 # repetition
print("Repeated tuple:", repeat_tuple)
print("Length:", len(t1))
print("Minimum:", min(t1))
print("Maximum:", max(t1))
try:
t1[0] = 100 # tuples are immutable
except TypeError as e:
print("Error:", e)
Description
This program creates a tuple and demonstrates indexing, slicing, concatenation, repetition and built-in functions like
len(), min() and max(). It also shows that tuples are immutable by attempting to modify an element and catching the
resulting TypeError.
Input
No input required (tuple elements are predefined).
Output
Tuple: (10, 20, 30, 40, 50)
Element at index 2: 30
Sliced tuple: (20, 30, 40)
Concatenated tuple: (10, 20, 30, 40, 50, 60, 70)
Repeated tuple: (60, 70, 60, 70)
Length: 5
Minimum: 10
Maximum: 50
Error: 'tuple' object does not support item assignment
Result
The Python program to demonstrate working with tuples was executed successfully.
Experiment 21
Create dictionary, add element to dictionary, delete element from the dictionary
Aim
To write a Python program to create a dictionary, add elements to it and delete elements from it.
Algorithm
1. Start.
2. Create a dictionary with key-value pairs.
3. Print the dictionary.
4. Add a new key-value pair.
5. Print the updated dictionary.
6. Delete a key-value pair using del or pop().
7. Print the final dictionary.
8. Stop.
Program
# Dictionary operations
student = {"name": "Arjun", "age": 20, "course": "CSE"}
print("Original dictionary:", student)
Description
This program creates a dictionary of student details, adds a new key-value pair by direct assignment, and removes
elements using both the del statement and the pop() method.
Input
No input required (dictionary values are predefined).
Output
Original dictionary: {'name': 'Arjun', 'age': 20, 'course': 'CSE'}
After adding element: {'name': 'Arjun', 'age': 20, 'course': 'CSE', 'marks':
89}
Removed value (pop): CSE
Final dictionary: {'name': 'Arjun', 'marks': 89}
Result
The Python program to create a dictionary and add/delete elements from it was executed successfully.
Experiment 22
Calculate average, mean, median, and standard deviation of numbers in a list
Aim
To write a Python program to calculate the average, mean, median and standard deviation of numbers stored in a
list.
Algorithm
1. Start.
2. Create/read a list of numbers.
3. Compute the average (sum/count).
4. Use the statistics module to compute mean, median and standard deviation.
5. Display all the results.
6. Stop.
Program
import statistics
Description
This program uses simple arithmetic to compute the average and the statistics module functions mean(), median()
and stdev() to compute the mean, median and sample standard deviation of a list of numbers.
Input
No input required (list elements are predefined).
Output
List: [12, 45, 23, 67, 34, 89, 21]
Average: 41.57
Mean: 41.57
Median: 34
Standard Deviation: 27.05
Result
The Python program to calculate the average, mean, median and standard deviation of a list of numbers was
executed successfully.
Experiment 23
(i) Create a simple file and write "Hello World" in it (ii) Open a file in write mode and append
"Hello World" at the end of a file
Aim
To write Python programs to (i) create a file and write 'Hello World' into it and (ii) open a file in append mode and
add 'Hello World' at the end of the file.
Algorithm
1. Program (i): Start.
2. Open a file in write mode ('w').
3. Write the text 'Hello World' into the file.
4. Close the file. Stop.
5. Program (ii): Start.
6. Open the same file in append mode ('a').
7. Write 'Hello World' at the end of the existing content.
8. Close the file and display the final content. Stop.
Program
# (i) Create a file and write "Hello World"
with open("[Link]", "w") as f:
[Link]("Hello World")
print("File created and 'Hello World' written successfully.")
# (ii) Open the file in append mode and add "Hello World" again
with open("[Link]", "a") as f:
[Link]("\nHello World")
print("Text appended successfully.")
Description
The first part uses open() in write mode ('w') to create a new file and write 'Hello World' into it. The second part
reopens the file in append mode ('a') to add 'Hello World' at the end without overwriting the existing content, then
displays the complete file content.
Input
No user input required (uses the file [Link]).
Output
File created and 'Hello World' written successfully.
Text appended successfully.
File content:
Hello World
Hello World
Result
The Python programs to create a file and append text to it were executed successfully.
Experiment 24
(i) Open a file in read mode and write its contents to another file replacing every 'h' with 'H' (ii)
Open a file in read mode and count occurrences of character 'a'
Aim
To write Python programs to (i) copy the content of one file into another while replacing every occurrence of the
character 'h' and (ii) count the number of occurrences of the character 'a' in a file.
Algorithm
1. Program (i): Start.
2. Open the source file in read mode and read its content.
3. Replace every occurrence of 'h' with 'H' using replace().
4. Write the modified content to a new file.
5. Close both files. Stop.
6. Program (ii): Start.
7. Open the file in read mode and read its content.
8. Count the occurrences of character 'a' using count().
9. Display the count. Stop.
Program
# (i) Copy content replacing 'h' with 'H'
with open("[Link]", "r") as src:
content = [Link]()
Description
The first program reads text from [Link], uses the string replace() method to substitute every 'h' with 'H', and
writes the result to [Link]. The second program reads the same file and uses count() to determine how many
times the character 'a' occurs.
Input
[Link] contains: "this is a happy python shell"
Output
Content copied with 'h' replaced by 'H'.
Number of occurrences of 'a': 3
Result
The Python programs to replace a character while copying a file and to count character occurrences were executed
successfully.
Experiment 25
Print all unique words in a text file in alphabetical order
Aim
To write a Python program that reads a text file and prints all unique words present in it in alphabetical order.
Algorithm
1. Start.
2. Open the text file in read mode and read its content.
3. Split the content into words.
4. Store the words in a set to remove duplicates.
5. Sort the unique words alphabetically.
6. Print the sorted unique words.
7. Stop.
Program
# Unique words in alphabetical order
with open("[Link]", "r") as f:
text = [Link]().lower()
import string
text = [Link]([Link]("", "", [Link]))
words = [Link]()
unique_words = sorted(set(words))
print("Unique words in alphabetical order:")
for word in unique_words:
print(word)
Description
This program reads the text file, converts it to lowercase, removes punctuation, and splits it into words. It then uses a
set to eliminate duplicate words and the sorted() function to arrange the unique words alphabetically before printing
them.
Input
[Link] contains: "Python is easy. Python is powerful and Python is
popular."
Output
Unique words in alphabetical order:
and
easy
is
popular
powerful
python
Result
The Python program to print unique words from a text file in alphabetical order was executed successfully.
Experiment 26
Load a CSV into a dataframe using pandas and perform arithmetic operations on the data
Aim
To write a pandas program to load data from a CSV file into a DataFrame and perform arithmetic operations on the
loaded data.
Algorithm
1. Start.
2. Import the pandas module.
3. Read the CSV file into a DataFrame using pd.read_csv().
4. Display the DataFrame.
5. Perform arithmetic operations such as addition of columns and computing totals/averages.
6. Display the results.
7. Stop.
Program
import pandas as pd
Description
This program uses pandas.read_csv() to load tabular data from [Link] into a DataFrame. It then performs
arithmetic operations across columns to compute a Total and Average for each row, and uses sum() to compute
column-wise totals.
Input
[Link] contains:
Name,Maths,Science,English
Ravi,80,75,70
Sita,90,85,88
Output
DataFrame:
Name Maths Science English
0 Ravi 80 75 70
1 Sita 90 85 88
Column-wise sum:
Maths 170
Science 160
English 158
Result
The pandas program to load a CSV into a DataFrame and perform arithmetic operations was executed successfully.
Experiment 27
Create a 5 x 5 Numpy array with random integers between 1 and 100
Aim
To write a Python program using NumPy to create a 5 x 5 array with random integers between 1 and 100.
Algorithm
1. Start.
2. Import the numpy module.
3. Use [Link]() to generate a 5x5 array of random integers between 1 and 100.
4. Display the array.
5. Perform basic operations such as finding sum, maximum and minimum of the array.
6. Stop.
Program
import numpy as np
Description
This program uses [Link](1, 101, size=(5,5)) to generate a 5x5 array of random integers in the range
1 to 100, and demonstrates NumPy array operations such as sum(), max(), min() along with row-wise and column-
wise aggregation.
Input
No input required (random values are generated automatically).
Output
5x5 Random Array:
[[23 87 45 12 90]
[34 76 5 66 21]
[98 3 44 57 19]
[61 8 72 33 25]
[4 91 18 55 63]]
Algorithm
1. Start.
2. Write a try block that performs division by zero and catch ZeroDivisionError.
3. Write a try block that accesses an out-of-range list index and catch IndexError.
4. Write a try block that references an undefined variable and catch NameError.
5. Display appropriate error messages for each exception.
6. Stop.
Program
# Handling built-in exceptions
# 1. ZeroDivisionError
try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError as e:
print("ZeroDivisionError:", e)
# 2. IndexError
try:
numbers = [1, 2, 3]
print(numbers[5])
except IndexError as e:
print("IndexError:", e)
# 3. NameError
try:
print(undefined_variable)
except NameError as e:
print("NameError:", e)
Description
This program uses separate try-except blocks to safely handle three common built-in exceptions: ZeroDivisionError
(division by zero), IndexError (accessing a list index that is out of range), and NameError (using a variable that has
not been defined), printing a descriptive message for each without terminating the program.
Input
No input required (errors are triggered intentionally within the code).
Output
ZeroDivisionError: division by zero
IndexError: list index out of range
NameError: name 'undefined_variable' is not defined
Program continued after handling exceptions.
Result
The Python program to handle built-in exceptions (ZeroDivisionError, IndexError, NameError) was executed
successfully.