Python Programming Laboratory Manual
Python Programming Laboratory Manual
Academic Year
2024-2025
SAPTHAGIRI NPS UNIVERSITY, BENGALURU-57
SCHOOL OF COMUTER SCIENCE AND
ENGINEERING
LABORATORY CERTIFICATE
Date :
Python Programming Laboratory
Exp. Date Experiment Title
No.
1. Write simple Python program to display message on screen.
2. Write simple Python program using operators:
a) Arithmetic Operators b) Logical Operators c) Bitwise Operators
3. Write Python program to perform following operations on Tuples:
a) Create Set b) Access Set elements c) Update Set d) Delete Set
4. Develop user defined Python function for given problem:
a) Function with minimum 2 arguments
b) Function returning values
5. Write a program to double a given number and add two numbers using
lambda()?
6. Write a program for map() function to double all the items in the list?
7. Demonstrate a python code to implement abnormal termination?
8. Write a python program to write the content “hi python programming” for the
existing file.
9. Write a python program to display a particular month of a year using calendar
module.
10. Write a Regular Expression to represent all 10-digit mobile numbers. Rules: 1.
Every number should contain exactly 10 digits. 2. The first digit should be 7 or
8 or 9 Write a Python Program to check whether the given number is valid
mobile no. or not?
11. Write a Regular Expression to represent all RGM language (Your own language)
identifiers.
Rules: 1. The allowed characters are a-z, A-Z, 0-9, #. 2. The first character
should be a lowercase alphabet symbol from a to k. 3. The second character
should be a digit divisible by 3. 4. The length of identifier should be at least 2.
Write a python program to check whether the given string is RGM language
identifier or not?
12. Implement the following Searching and Sorting techniques in Python by using
functions.
i) Linear Search ii) Binary Search iii) Selection Sort iv) Bubble Sort v) Insertion
vi) Merge Sort viii) Quick Sort
13. Write a Python program to return multiple values at a time using a return
statement.
14. Write a program in Python to demonstrate following operations:
a) Method overloading b) Method overriding
15. Write a program in Python to handle user defined exception for given problem.
Problem: You want to check the strength of a password. If the password is too
short (less than 6 characters), raise a WeakPasswordError. If the password does
not meet the necessary criteria (e.g., missing numbers or special characters),
raise another user-defined exception.
1. Write simple Python program to display message on screen.
# This program prints Message
print('Hello, world!')
print('Sapthagiri NPS university')
Output:
Hello, world!
Sapthagiri NPS university
a) Arithmetic Operators
a=7
b=2
print ('Sum: ', a + b)
print ('Subtraction: ', a - b)
print ('Multiplication: ', a * b)
print ('Division: ', a / b)
print ('Floor Division: ', a // b)
print ('Modulo: ', a % b)
print ('Power: ', a ** b)
OUTPUT:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
b) Logical Operators
a=5
b=6
print((a > 2) and (b >= 6))
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
OUTPUT:
True
True
False
True
False
C) Bitwise operator
x=10
y=4
a1= x & y #Bitwise AND
a2= x | y #Bitwise OR
a3= ~x #Bitwise NOT
a4=x ^ y # Bitwise XOR
a5=x >> 2 # >> Bitwise right shift
a6=x<<2 #<<Bitwise left shift
print( "bitwise AND=",a1)
print( "bitwise OR=",a2)
print( "bitwise NOT=",a3)
print( "bitwise XOR=",a4)
print( "bitwise Right shift=",a5)
print( "bitwise Left shift=",a6)
OUTPUT:
bitwise AND= 0
bitwise OR= 14
bitwise NOT= -11
bitwise XOR= 14
bitwise Right shift= 2
bitwise Left shift= 40
2. Write Python program to perform following operations on Tuples:
a) Create Set b) Access Set elements c) Update Set d) Delete Set
a) Create Set
my_set = {1, 2, 3, 4, 5}
print("Original Set:", my_set)
# c) Update Set
# Adding an element
my_set.add(6)
print("Set after adding 6:", my_set)
# d) Delete Set
# Clearing all elements from the set
my_set.clear()
print("Set after clearing all elements:", my_set)
OUTPUT:
Original Set: {1, 2, 3, 4, 5}
Element: 1
Element: 2
Element: 3
Element: 4
Element: 5
Is 3 in the set? True
Set after adding 6: {1, 2, 3, 4, 5, 6}
Set after adding [7, 8, 9]: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Set after discarding 2: {1, 3, 4, 5, 6, 7, 8, 9}
Set after clearing all elements: set()
# Example usage
length = 5
width = 3
area, perimeter = calculate_rectangle_properties(length, width)
print(f"Area: {area}, Perimeter: {perimeter}")
OUTPUT:
Area: 15, Perimeter: 16
Note:
1. f-string: The f before the string denotes an f-string (formatted string literal). F-
strings provide a way to embed expressions inside string literals, using curly braces
{}.
2. Expressions inside braces: Inside the curly braces, Python expressions can be
evaluated and their values inserted into the string.
4. Write a program to double a given number and add two numbers
using lambda()?
Program:
double = lambda x:2*x
print(double(5))
add = lambda x,y:x+y
print(add(5,4))
OUTPUT:
6. Write a program for map() function to double all the items in the list?
# Function to double a number
def double(num):
return num * 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
OUTPUT:
OUTPUT:
# Open the file in append mode to add content without erasing existing data
with open(file_path, "a") as file:
file.write("hi python programming\n")
OUTPUT:
import calendar
OUTPUT:
def is_valid_mobile_number(number):
# Regular expression to check the mobile number
pattern = r"^[789]\d{9}$"
11. Write a Regular Expression to represent all RGM language (Your own
language) identifiers.
Rules: 1. The allowed characters are a-z, A-Z, 0-9, #.
2. The first character should be a lowercase alphabet symbol from a to k.
3. The second character should be a digit divisible by 3.
4. The length of identifier should be at least 2.
Write a python program to check whether the given string is RGM
language identifier or not?
Explanation:
import re
def is_rgm_identifier(identifier):
# Regular Expression for the RGM language identifier
pattern = r'^[a-k][0369].*'
OUTPUT:
12. Write a Regular Expression to represent all RGM language (Your own
language) identifiers.
Rules: 1. The allowed characters are a-z, A-Z, 0-9,
2. The first character should be a lowercase alphabet symbol from a to k.
3. The second character should be a digit divisible by 3.
4. The length of identifier should be at least 2.
Write a python program to check whether the given string is RGM
language identifier or not?
Explanation:
import re
def is_rgm_identifier(identifier):
# Regular Expression for the RGM language identifier
pattern = r'^[a-k][0369].*'
OUTPUT:
i)Linear Search
Explanation:
Program:
if arr[mid] == target:
return mid # Target found
elif arr[mid] < target:
left = mid + 1 # Search in the right half
else:
right = mid - 1 # Search in the left half
# Example usage
arr = [1, 3, 5, 7, 9, 11, 13, 15]
target = 7
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
OUTPUT:
Explanation:
Selection Sort is a simple sorting algorithm that works by repeatedly finding the smallest
element from the unsorted part of the list and moving it to the beginning.
Steps:
Program:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i] # Swap elements
# Example usage
arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print("Sorted array:", arr)
OUTPUT:
def bubble_sort(arr):
"""Performs bubble sort on an array."""
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap elements
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)
OUTPUT:
v) Insertion Sort
Algorithm Steps
1. Start with the second element (index = 1), considering the first element as sorted.
2. Pick the current element (key) and compare it with elements in the sorted portion (to
its left).
3. Shift elements greater than key one position to the right.
4. Insert key in its correct position.
5. Repeat this process for all elements until the list is sorted.
Example Walkthrough
Program:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Example usage
arr = [64, 25, 12, 22, 11]
insertion_sort(arr)
print("Sorted array (Insertion Sort):", arr)
OUTPUT:
Merge Sort is a divide-and-conquer algorithm that works by recursively breaking down the
input array into smaller sub-arrays, sorting them, and then merging them back together.
Here's a detailed breakdown of how it works:
The array is recursively divided into two halves until each sub-array contains only one
element (since a single element is inherently sorted).
For example:
Given the array [38, 27, 43, 3, 9, 82, 10], it is split into two halves:
o Left half: [38, 27, 43]
o Right half: [3, 9, 82, 10]
This process continues recursively, breaking each half into smaller parts, until we
reach sub-arrays of size 1. For instance:
o [38, 27, 43] becomes [38], [27], [43]
o [3, 9, 82, 10] becomes [3], [9], [82], [10]
After the array has been broken down into smaller arrays, the algorithm merges them back
together, but in sorted order. This is where the "merge" function comes into play.
The two halves are compared element by element, and the smaller element is placed
into the sorted array. This continues until all elements from both halves are merged
into a single sorted array.
If there are leftover elements in either half, they are appended directly to the result
since they are already sorted.
Example of Merging:
For the sub-arrays [38], [27], and [43], merge them as follows:
Compare 38 and 27. Since 27 is smaller, it goes into the sorted array.
Now compare 38 and 43. Since 38 is smaller, it goes into the sorted array.
The remaining element 43 is added to the sorted array, and the result is [27, 38,
43].
Similarly, the merge process occurs for other parts of the array, eventually combining all the
sorted sub-arrays into one sorted array.
return sorted_array
# Example usage:
arr = [38, 27, 43, 3, 9, 82, 10]
print("Original Array:", arr)
sorted_arr = merge_sort(arr)
print("Sorted Array:", sorted_arr)
OUTPUT:
pivot = array[high]
i = low - 1
# traverse through all elements
i=i+1
return i + 1
quickSort(array, low, pi - 1)
# recursive call on the right of pivot
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
OUTPUT:
Unsorted Array
[8, 7, 2, 1, 0, 9, 6]
Sorted Array in Ascending Order:
[0, 1, 2, 6, 7, 8, 9]
13. Write a Python program to return multiple values at a time using a return
statement.
def calculate_values(a, b):
sum_val = a + b
product_val = a * b
return sum_val, product_val
print("Sum:", result1)
print("Product:", result2)
OUTPUT:
Sum: 8
Product: 15
a) Method Overloading
# First product method.
# Takes two argument and print their
# product
OUTPUT:
100
b)Method overriding
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
# Driver's code
obj = Child()
obj.show()
OUTPUT:
Inside Parent
Inside Child
import re
class PasswordMissingCriteriaError(Exception):
"""Exception raised for passwords that are missing required criteria (numbers or
special characters)."""
def __init__(self, message="Password must contain at least one number and one
special character."):
self.message = message
super().__init__(self.message)
# Check if the password contains at least one number and one special character
if not re.search(r'\d', password) or not re.search(r'[\W_]', password):
raise PasswordMissingCriteriaError("Password must contain at least one number
and one special character.")
print("Password is strong!")
OUTPUT:
Case 1: Password too short
Enter your password: abc
Error: Password is too short. Must be at least 6 characters long.