PYTHON PROGRAMMING LABORATORY
Common to CIVIL and MECHANICAL ENGINEERING
3 i) Write a program to calculate compound interest when principal, rate and number of periods
are given.
# Compound Interest Calculation
P = float(input("Enter Principal Amount: "))
R = float(input("Enter Rate of Interest (%): "))
T = int(input("Enter Time Period (years): "))
A = P * (1 + R / 100) ** T
CI = A - P
print(f"Compound Interest: {CI:.2f}")
NOTE:
f-string (formatted string literal)in Python, introduced in Python 3.6.
f"" → Marks the string as an f-string, allowing inline variable substitution.
{CI:.2f} → Inserts the value of CI into the string and formats it:
:.2f → Formats CI as a floating-point number with 2 decimal places.
3 ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
Method 1:
# Python Program to Calculate Distance
# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))
NOTE:
Formatted print statement:
'Distance = %f' → A string containing a format specifier (%f).
% Operator → Used for string formatting, replacing %f with the value of d.
(d) → The variable d, whose value replaces %f.
Method 2:
import math
# Read coordinates
x1, y1 = map(float, input("Enter coordinates of first point (x1 y1): ").split())
x2, y2 = map(float, input("Enter coordinates of second point (x2 y2): ").split())
# Calculate distance
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1)* * 2)
print(f"Distance between points: {distance:.2f}")
4. Read name, address, email and phone number of a person through keyboard and print the
details.
# Read person details
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")
# Print details
print("\n--- Person Details ---")
print("Name:", name)
print("Address:", address)
print("Email:", email)
print("Phone:", phone)
Week - 2:
1. Print the below triangle using for loop.
44
333
2222
11111
# Loop from 5 to 1
for i in range(5, 0, -1):
# Print 'i' i times
print((str(i) + " ") * (6 - i))
2. Write a program to check whether the given input is digit or lowercase character or uppercase
character or a special character (use 'if-else-if' ladder)
# Take input from the user
char = input("Enter a single character: ")
# Check if the input is a digit
if char.isdigit():
print(f"'{char}' is a Digit.")
# Check if the input is a lowercase letter
elifchar.islower():
print(f"'{char}' is a Lowercase Character.")
# Check if the input is an uppercase letter
elifchar.isupper():
print(f"'{char}' is an Uppercase Character.")
# If none of the above conditions match, it's a special character
else:
print(f"'{char}' is a Special Character.")
3. Python Program to Print the Fibonacci sequence using while loop
# Take user input for the number of terms
n = int(input("Enter the number of terms: "))
# Initialize the first two Fibonacci numbers
a, b = 0, 1
count = 0 # Counter to track the number of terms printed
# Check if the user entered a valid number
if n <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci Sequence:")
while count < n:
print(a, end=" ") # Print the current term
a, b = b, a + b # Update values (next Fibonacci number)
count += 1 # Increment the counter
4. Python program to print all prime numbers in a given interval (use break)
# Get user input for range
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))
print(f"Prime numbers between {start} and {end} are:")
# Loop through numbers in the given range
for num in range(start, end + 1):
if num > 1: # Prime numbers are greater than 1
for i in range(2, int(num ** 0.5) + 1): # Check divisibility up to sqrt(num)
if num % i == 0: # If divisible, it's not prime
break # Exit loop early
else:
print(num, end=" ") # Print prime number
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
i) Write a program to convert a list and tuple into arrays.
import numpy as np
my_list = [1, 2, 3, 4, 5]
my_tuple = (60, 70, 80, 90, 100)
# Convert list to array
list_array = np.array(my_list)
print("List converted to array:", list_array)
# Convert tuple to array
tuple_array = np.array(my_tuple)
print("Tuple converted to array:", tuple_array)
OUTPUT:
ii) Write a program to find common values between two arrays.
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([3, 4, 5, 6, 7])
common_values = np.intersect1d(arr1, arr2)
print("Common values between arrays:", common_values)
OUTPUT:
2. Write a function called gcd that takes parameters a and b and returns their greatest common
divisor.
def gcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"GCD of {num1} and {num2} is:", gcd(num1, num2))
OUTPUT:
3. Write a function called palindrome that takes a string argument and returns True if it is a
palindrome and False otherwise. Remember that you can use the built-in function len to check
the length of a string.
# Program to check if a string is a palindrome
def palindrome(s):
return s == s[::-1]
string = input("Enter a string: ")
if palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list
is sorted in ascending order and False otherwise.
def is_sorted(lst):
return lst == sorted(lst)
# Taking input from the user
user_input = input("Enter numbers separated by spaces: ")
num_list = list(map(int, user_input.split())) # Convert input string to a list of integers
# Check if the list is sorted
if is_sorted(num_list):
print("The list is sorted in ascending order.")
else:
print("The list is not sorted.")
2. Write a function called has_duplicates that takes a list and returns True if there is any
element
that appears more than once. It should not modify the original list.
Method 1:
def has_duplicates(lst):
seen = set() # Create an empty set to store seen elements
for item in lst:
if item in seen: # If item is already in set, there's a duplicate
return True
seen.add(item) # Add item to the set
return False # No duplicates found
# Example usage:
print(has_duplicates([1, 2, 3, 4, 5])) # False
print(has_duplicates([1, 2, 3, 4, 1])) # True
print(has_duplicates(['a', 'b', 'c', 'a'])) # True
print(has_duplicates([])) # False
i) Write a function called remove_duplicates that takes a list and returns a new list with
only the unique elements from the original. Hint: they don‟t have to be in the same
order.
def remove_duplicates(lst):
seen = set()
unique_list = []
for item in lst:
if item not in seen:
unique_list.append(item)
seen.add(item)
return unique_list
# Example usage:
print(remove_duplicates([1, 2, 3, 4, 1, 2, 5])) # Output: [1, 2, 3, 4, 5]
ii) The wordlist I provided, words.txt, doesn‟t contain single letter words. So you might
want to add “I”, “a”, and the empty string.
iii) Write a python code to read dictionary values from the user. Construct a function to
invert its content. i.e., keys should be values and values should be keys.
def invert_dict(d):
inverted = {}
for key, value in d.items():
if value in inverted:
inverted[value].append(key) # If value already exists, append key (handles
duplicates)
else:
inverted[value] = [key] # Store keys as a list to handle duplicate values
return inverted
# Taking dictionary input from the user
try:
user_input = input("Enter a dictionary (e.g., {'a': 1, 'b': 2, 'c': 1}): ")
import ast
user_dict = ast.literal_eval(user_input) # Safe parsing of input
if isinstance(user_dict, dict): # Ensure input is a dictionary
inverted_dict = invert_dict(user_dict)
print("Inverted dictionary:", inverted_dict)
else:
print("Invalid input! Please enter a valid dictionary.")
except:
print("Invalid input! Please enter a valid dictionary format.")
Week - 5
1. i) Write a python program that defines a matrix and prints
ii) Write a python program to perform addition of two square matrices
iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using different
geometrical shapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.
1. i) Write a python program that defines a matrix and prints
program 1:
# Define a matrix (2D list)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the matrix
print("The matrix is:")
for row in matrix:
print(row)
program 2 using numpy
import numpy as np
# Define a matrix using NumPy
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Print the matrix
print("The matrix is:")
print(matrix)
ii) Write a python program to perform addition of two square matrices
program
import numpy as np
# Define two square matrices
matrix1 = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
matrix2 = np.array([
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
])
# Perform matrix addition
result = matrix1 + matrix2
# Print the matrices and the result
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print("\nSum of Matrix 1 and Matrix 2:")
print(result)
iii) Write a python program to perform multiplication of two square matrices
import numpy as np
# Define two square matrices
matrix1 = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
matrix2 = np.array([
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
])
# Perform matrix multiplication
result = np.dot(matrix1, matrix2) # You can also use matrix1 @ matrix2
# Print the matrices and the result
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print("\nProduct of Matrix 1 and Matrix 2:")
print(result)
2. How do you make a module? Give an example of construction of a module using
different geometrical shapes and operations on them as its functions.
# geometry.py
import math
# Circle area and perimeter
def circle_area(radius):
return math.pi * radius ** 2
def circle_perimeter(radius):
return 2 * math.pi * radius
# Rectangle area and perimeter
def rectangle_area(length, width):
return length * width
def rectangle_perimeter(length, width):
return 2 * (length + width)
# Triangle area using Heron's formula
def triangle_area(a, b, c):
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def triangle_perimeter(a, b, c):
return a + b + c
# main.py
import geometry # Importing our custom module
# Circle
r=5
print("Circle Area:", geometry.circle_area(r))
print("Circle Perimeter:", geometry.circle_perimeter(r))
# Rectangle
l, w = 10, 4
print("\nRectangle Area:", geometry.rectangle_area(l, w))
print("Rectangle Perimeter:", geometry.rectangle_perimeter(l, w))
# Triangle
a, b, c = 3, 4, 5
print("\nTriangle Area:", geometry.triangle_area(a, b, c))
print("Triangle Perimeter:", geometry.triangle_perimeter(a, b, c))
3. Use the structure of exception handling all general purpose exceptions.
import math
def safe_circle_area(radius):
try:
area = math.pi * radius ** 2
return area
except TypeError:
print("Error: Radius must be a number.")
except Exception as e:
print("Unexpected error:", e)
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except TypeError:
print("Error: Inputs must be numbers.")
except Exception as e:
print("Unexpected error occurred:", e)
else:
print("Division successful.")
finally:
print("Exiting division function.")
def safe_triangle_area(a, b, c):
try:
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
if area <= 0:
raise ValueError("Invalid triangle dimensions.")
return area
except ValueError as ve:
print("Value Error:", ve)
except TypeError:
print("Error: All sides must be numbers.")
except Exception as e:
print("Unexpected error:", e)
# Test all
print("Circle Area:", safe_circle_area(5))
print("Division:", safe_division(10, 0)) # Will raise division error
print("Triangle Area:", safe_triangle_area(1, 2, 10)) # Invalid triangle
WEEK – 6
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as
arguments and draws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that it uses the color attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments
and draws a representation of the Point on the Canvas.
d. Define a new class called Circle with appropriate attributes and instantiate a few
Circle
objects. Write a function called draw_circle that draws circles on the canvas.
Method – 1 for google colabs
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Create figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, 400)
ax.set_ylim(0, 400)
ax.set_aspect('equal')
ax.set_facecolor("white")
# Function to draw a rectangle
def draw_rectangle(x, y, width, height, color):
rect = patches.Rectangle((x, y), width, height, linewidth=1, edgecolor='black',
facecolor=color)
ax.add_patch(rect)
# Function to draw a point
def draw_point(x, y, size=4, color='black'):
circle = patches.Circle((x, y), radius=size, color=color)
ax.add_patch(circle)
# Function to draw a circle
def draw_circle(x, y, radius, color):
circle = patches.Circle((x, y), radius=radius, edgecolor='black', facecolor=color)
ax.add_patch(circle)
# Sample drawings
draw_rectangle(50, 50, 100, 80, "lightgreen")
draw_rectangle(200, 50, 120, 100, "skyblue")
draw_point(150, 200)
draw_point(300, 300)
draw_circle(100, 300, 40, "pink")
draw_circle(250, 150, 60, "orange")
plt.gca().invert_yaxis() # To match tkinter's top-left origin
plt.axis('off') # Hide axis
plt.show()
OUTPUT:
Method – 2 – for vs code and pycharm
import tkinter as tk
# Define a Point class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Define a Rectangle class
class Rectangle:
def __init__(self, x, y, width, height, color="blue"):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
# Define a Circle class
class Circle:
def __init__(self, x, y, radius, color="red"):
self.x = x
self.y = y
self.radius = radius
self.color = color
# Function to draw a rectangle on canvas
def draw_rectangle(canvas, rect):
x1 = rect.x
y1 = rect.y
x2 = rect.x + rect.width
y2 = rect.y + rect.height
canvas.create_rectangle(x1, y1, x2, y2, fill=rect.color, outline="black")
# Function to draw a point on canvas
def draw_point(canvas, point, size=4):
x, y = point.x, point.y
canvas.create_oval(x-size, y-size, x+size, y+size, fill="black")
# Function to draw a circle on canvas
def draw_circle(canvas, circle):
x1 = circle.x - circle.radius
y1 = circle.y - circle.radius
x2 = circle.x + circle.radius
y2 = circle.y + circle.radius
canvas.create_oval(x1, y1, x2, y2, fill=circle.color, outline="black")
# Create Tkinter window and canvas
root = tk.Tk()
root.title("Canvas Drawing")
canvas = tk.Canvas(root, width=400, height=400, bg="white")
canvas.pack()
# Sample shapes
rect1 = Rectangle(50, 50, 100, 80, color="lightgreen")
rect2 = Rectangle(200, 50, 120, 100, color="skyblue")
draw_rectangle(canvas, rect1)
draw_rectangle(canvas, rect2)
point1 = Point(150, 200)
point2 = Point(300, 300)
draw_point(canvas, point1)
draw_point(canvas, point2)
circle1 = Circle(100, 300, 40, color="pink")
circle2 = Circle(250, 150, 60, color="orange")
draw_circle(canvas, circle1)
draw_circle(canvas, circle2)
# Launch the GUI window
root.mainloop()
2. Write a Python program to demonstrate the usage of Method Resolution Order
(MRO) in multiple levels of Inheritances.
class A:
def greet(self):
print("Hello from A")
class B(A):
def greet(self):
print("Namaste from B")
super().greet() # Calls greet() from A
class C(A):
def greet(self):
print("Marhaba from C")
super().greet() # Calls greet() from A
class D(B, C): # D inherits from B and C
def greet(self):
print("Olà from D")
super().greet() # This will follow MRO
# Create object of D and call greet
d = D()
d.greet()
# Print the MRO
print("\nMethod Resolution Order (MRO):")
print(D.__mro__)
OUTPUT:
Olà from D
Namaste from B
Marhaba from C
Hello from A
Method Resolution Order (MRO):
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class
'__main__.A'>, <class 'object'>)
3. Write a python code to read a phone number and email-id from the user and validate
it for correctness.
import re
def validate_phone(phone):
# Indian phone number: 10 digits, starts with 6-9
pattern = r'^[6-9]\d{9}$'
return re.match(pattern, phone)
def validate_email(email):
# Basic email pattern
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email)
# Read input from user
phone = input("Enter your phone number: ")
email = input("Enter your email ID: ")
# Validate phone number
if validate_phone(phone):
print("Phone number is valid.")
else:
print("Invalid phone number. It must be 10 digits starting with 6-9.")
# Validate email
if validate_email(email):
print("Email ID is valid.")
else:
print("Invalid email ID. Please check the format (e.g., name@example.com).")
OUTPUT:
Enter your phone number: 7894567895
Enter your email ID: nazima@gmail.com
Phone number is valid.
Email ID is valid.
Enter your phone number: 7894565
Enter your email ID: naz&gmail.com
Invalid phone number. It must be 10 digits starting with 6-9.
Invalid email ID. Please check the format (e.g., name@example.com).
NOTES:
What is RE?
RE stands for Regular Expression (sometimes called regex or regexp).
A regular expression is a special sequence of characters that defines a search pattern.
It is mainly used for string matching, searching, and validation.
For example, you can use regex to check if a phone number, email, or password
meets a certain format.
1. ^[6-9]\d{9}$
This regex is often used to validate Indian mobile phone numbers (starting with digits
6 to 9 and having a total of 10 digits).
^
Anchors the match at the start of the string.
[6-9]
Matches exactly one digit between 6 and 9 (inclusive). This means the first digit of the
phone number must be 6, 7, 8, or 9.
\d{9}
\d matches any digit (0-9). {9} means exactly 9 digits following the first digit.
$
Anchors the match at the end of the string.
Therefore, the string must start with a digit 6-9, followed by exactly 9 digits, and nothing
else before or after. So the whole string must be exactly 10 digits, valid Indian phone
number format.
2. ^[\w\.-]+@[\w\.-]+\.\w+$
This regex is used to validate email addresses in a simplified form.
^
Start of the string.
[\w\.-]+
Matches one or more (+) characters that are either:
o \w = word characters (letters a-z, A-Z, digits 0-9, and underscore _)
o . = literal dot (.)
o - = literal hyphen (-)
This part matches the username or local part before the @.
@
Matches the literal "@" symbol.
[\w\.-]+
Matches one or more word characters, dots, or hyphens again, this is the domain name
part.
\.
Matches a literal dot (.) separating domain and top-level domain (TLD).
\w+
Matches one or more word characters, this is the top-level domain (like com, org, net).
$
End of the string.
Regex Purpose Explanation
Validate Indian phone Starts with 6-9, followed by
^[6-9]\d{9}$
numbers 9 digits, total 10 digits
Username with
letters/digits/dots/hyphens,
Validate email addresses
^[\w\.-]+@[\w\.-]+\.\w+$ then '@', then domain with
(simple)
letters/digits/dots/hyphens,
dot, and TLD
WEEK – 7
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for
given words
present in it and display on found.
3. Write a Python code to Read text from a text file, find the word with most number
of occurrences
4. Write a function that reads a file file1 and displays the number of words, number of
vowels,
blank spaces, lower case letters and uppercase letters.
1. Write a Python code to merge two given file contents into a third file.
from google.colab import files
file = open("file1.txt", "w")
# Write content to the file
file.write("Hello! This is a text file created using Python.\n")
file.write("You can add more lines like this.\n")
# Always close the file after writing
file.close()
file = open("file2.txt", "w")
# Write content to the file
file.write("python is an easy programming language\n")
file.write("the best part of its is vast libraries .\n")
# Always close the file after writing
file.close()
print("File 'example.txt' created successfully!")
file1 = 'file1.txt'
file2 = 'file2.txt'
merged_file = 'merged.txt'
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(merged_file, 'w') as mf:
mf.write(f1.read())
mf.write('\n') # Optional newline between files
mf.write(f2.read())
print("Files merged into merged.txt")
files.download("file1.txt")
files.download("file2.txt")
files.download("merged.txt")
2. Write a Python code to open a given file and construct a function to check for
given words present in it and display on found.
USING FUNCTIONS:
def search_words_in_file(filename, words):
with open(filename, 'r') as file:
content = file.read()
for word in words:
if word in content:
print(f"'{word}' found in file.")
else:
print(f"'{word}' not found in file.")
# Example usage:
search_words_in_file(‘merged.txt', ['python', 'code', 'banana'])
WITHOUT USING FUNCTIONS:
filename = 'merged.txt'
words = ['python', 'code', 'India']
with open(filename, 'r') as file:
content = file.read()
for word in words:
if word in content:
print(f"'{word}' found in file.")
else:
print(f"'{word}' not found in file.")
3. Write a Python code to Read text from a text file, find the word with most number of
occurrences
from collections import Counter
import string
filename = 'file1.txt'
with open(filename, 'r') as file:
text = file.read()
# Normalize text: lowercase and remove punctuation
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
# Split into words and count
words = text.split()
word_count = Counter(words)
most_common = word_count.most_common(1)
if most_common:
print(f"The most frequent word is '{most_common[0][0]}' with {most_common[0]
[1]} occurrences.")
else:
print("No words found.")
4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blank spaces, lower case letters and uppercase letters.
USING FUNCTIONS:
def analyze_file(filename):
vowels = "aeiouAEIOU"
with open(filename, 'r') as file:
content = file.read()
word_count = len(content.split())
vowel_count = sum(1 for char in content if char in vowels)
space_count = content.count(' ')
lowercase_count = sum(1 for char in content if char.islower())
uppercase_count = sum(1 for char in content if char.isupper())
print(f"Words: {word_count}")
print(f"Vowels: {vowel_count}")
print(f"Spaces: {space_count}")
print(f"Lowercase letters: {lowercase_count}")
print(f"Uppercase letters: {uppercase_count}")
# Example usage:
analyze_file('file1.txt')