Python Lab
Python Lab
Program:
#addi on
print(n1 + n2)
#subtrac on
print(n1 - n2)
#mul plica on
print(n1 * n2)
#division
print(n1 / n2)
OUTPUT:
3.0 + 5.0 =
8.0
3.0 - 5.0 =
-2.0
3.0 * 5.0 =
15.0
3.0 / 5.0 =
0.6
1
2. Write a program to calculate compound interest when principal, rate and number of periods are given.
PROGRAM:
OUTPUT:
***********************************************************************************************
3. Given coordinates (x1, y1), (x2, y2) find the distance between two points
PROGRAM:
# Reading co-ordinates
# Calcula ng distance
# Displaying result
2
OUTPUT:
Enter x1: 5
Enter y1: 2
Enter x2: 3
Enter y2: 5
Distance = 3.605551
***********************************************************************************************
4. Read name, address, email and phone number of a person through keyboard and print the details.
PROGRAM:
# read name, address, contact and email from user and print them
name = input()
address = input()
contact = input()
email = input()
OUTPUT:
Name: Dheeraj
Address: Hyderabad
Contact: 9546716813
Email: [email protected]
3
5. Print the below triangle using for loop.
44
333
2222
11111
PROGRAM:
if j== i-1;
print(n)
else,
print(n, end = “ “)
n = n-1
OUTPUT:
44
333
2222
11111
************************************************************************************************
6. 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)
PROGRAM:
def check_character(char):
if char.isdigit():
print(f"{char} is a digit.")
elif char.islower():
elif char.isupper():
else:
4
print(f"{char} is a special character.")
check_character(input_char)
OUTPUT:
Enter a character: @
@ is a special character.
************************************************************************************************
PROGRAM:
n1, n2 = 0, 1
count = 0
if nterms <= 0:
elif nterms == 1:
print(n1)
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
n1 = n2
5
n2 = nth
count += 1
OUTPUT :
Fibonacci sequence:
*************************************************************************************************
8. Python program to print all prime numbers in a given interval (use break)
PROGRAM:
lower = 0
upper = 10
if num > 1:
if (num % i) == 0:
break
else:
print(num)
OUTPUT:
6
9. Write a program to convert a list and tuple into arrays.
PROGRAM:
import numpy as np
list_data = [1, 2, 3, 4, 5]
array_from_list = np.array(list_data)
array_from_tuple = np.array(tuple_data)
OUTPUT:
List to Array: [1 2 3 4 5]
*************************************************************************************************
PROGRAM:
import numpy as np
ar2 = [1, 3, 4, 2]
print(np.intersect1d(ar1, ar2))
OUTPUT:
[1 2 3 4]
*************************************************************************************************
11. Write a func on called gcd that takes parameters a and b and returns their greatest common divisor.
PROGRAM:
if(b == 0):
return a
else:
return hcf(b, a % b)
7
a = 60
b = 48
# prints 12
print(hcf(60, 48))
OUTPUT:
*************************************************************************************************
12. Write a func on called palindrome that takes a string argument and returnsTrue if it is a palindrome and False
otherwise. Remember that you can use the built-in func on len to check the length of a string.
PROGRAM:
my_str = 'aIbohPhoBiA'
my_str = my_str.casefold()
rev_str = reversed(my_str)
if list(my_str) == list(rev_str):
else:
OUTPUT:
*************************************************************************************************
13. . Write a func on called is_sorted that takes a list as a parameter and returns True if the list is sorted in
ascending order and False otherwise.
PROGRAM:
def is_sorted(a):
for i in range(len(a)-1):
if a[i]<=a[i+1]:
return True
return False
8
print(is_sorted([3,4,4,8,2,5,6,2]))
OUTPUT:
True
*************************************************************************************************
14. Write a func on 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.
PROGRAM:
def has_duplicates(a):
if len(a) !=len(set(a)):
return True
else:
return False
a=[1,2,3,4,5]
print(has_duplicates(a))
OUTPUT:
False
*************************************************************************************************
15. Write a func on 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
PROGRAM:
def Remove(duplicate):
final_list = []
final_list.append(num)
return final_list
# Driver Code
print(Remove(duplicate))
OUTPUT:
9
16. Write a python code to read dic onary values from the user. Construct a func on to invert its content. i.e., keys
should be values and values should be keys.
PROGRAM:
d1 = dict( )
return d1
d = dict( )
OUTPUT:
Enter a value : A
Enter a value : B
Enter a value : C
Enter a value : D
Enter a value : E
The original dic onary :{1:’A’ , 2:’B’ , 3:’C’ , 4:’D’ , 5:’ E’}
The inversed dic onary :{‘A’:1 , ‘B’:2 , ‘C’:3 , ‘D’ :4 , ‘E’ :5}
************************************************************************************************
17. Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e
PROGRAM:
x = "APPLE"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))
10
OUTPUT:
'A,P,P,L,E,'
*************************************************************************************************
PROGRAM:
a2 = a1.replace("word", '')
print(a2)
OUTPUT:
*************************************************************************************************
19. Write a func on that takes a sentence as an input parameter and replaces the first le er of every word with the
corresponding upper case le er and the rest of the le ers in the word by corresponding le ers in lower case without
using a built-in func on?
PROGRAM:
L = s.split(“ “)
nl = [ ]
for word in L :
retun nl
for w in new_L ;
print( w, end = “ “)
OUTPUT:
Paper Is In Hand
*************************************************************************************************
20. Writes a recursive func on that generates all binary strings of n-bit length
PROGRAM:
11
for i in range(1 << n):
print(binary_str)
# Example usage
n=2
print_binary_combina ons(n)
OUTPUT:
00
01
10
11
*************************************************************************************************
WEEK-5
21. Write a python program that defines a matrix and prints.
PROGRAM:
# Initialize matrix
matrix = []
print("enter the entries row wise:")
12
OUTPUT:
56
78
*************************************************************************************************
raise ValueError("Matrices must be square matrices (same number of rows and columns)")
size = len(mat1)
# Perform addi on
for i in range(size):
for j in range(size):
return result
# Example usage:
if __name__ == "__main__":
matrix1 = [
13
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
try:
print(row)
except ValueError as e:
print(e)
OUTPUT:
*************************************************************************************************
raise ValueError("Matrices must be square matrices (same number of rows and columns)")
size = len(mat1)
14
# Perform mul plica on
for i in range(size):
for j in range(size):
for k in range(size):
return result
# Example usage:
if __name__ == "__main__":
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
try:
print(row)
except ValueError as e:
print(e)
OUTPUT:
Result of matrix mul plica on:
15
24.How do you make a moduleive an example of construc on of a
module using different geometrical shapes and o? Gpera ons on them
as its func ons.
PROGRAM:
Crea ng a module in python involves crea ng a python file (module) with
func ons or classes that can be imported and used in other python scripts. Let’s
say, to create a module called ‘geometry.py’ that contains func ons shapes, etc...
Here’s how ‘geometry.py’ module can be structures
Import math
def rec_a(l, w):
return l*w
def rec_p(l, w):
return 2* (l+w)
def cir_a(radius ):
return (math.pi * r)
def tri_a (b, h):
return 0.5* b * h
this separate script imports the ‘geometry’ module and uses its func on to
perform calcula ons for different geometric shapes
16
25. Use the structure of excep on handling all general-purpose
excep ons.
PROGRAM:
Here’s a general purpose excep on handling structure that handles all excep ons:
try :
result = 10/0 #Zero Division error will raise
file = open (“non _existent .txt”, ‘r’) #file not found
except Excep on as e:
# This block catches any excep on in try blocks
Print (f”An error occured : {e}”)
else:
#This block exectes if no excep on occurs within the try block
Print(“ No excep ons occurred”)
finally :
#This block always occurs regardless of any situa on in the try block.
Print(“ finally block executed”)
17
Week-6
26. Write a func on called draw_rectangle that takes a Canvas and a
Rectangle as arguments and draws a representa on of the Rectangle
on the Canvas.
PROGRAM:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def set_pixel(self, x, y, char):
self.data[y][x] = char
def display(self):
for row in self.data:
print(''.join(row))
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw_rectangle(canvas, rectangle):
# Ensure rectangle dimensions are within canvas bounds
if (rectangle.x < 0 or rectangle.y < 0 or
18
rectangle.x + rectangle.width > canvas.width or
rectangle.y + rectangle.height > canvas.height):
raise ValueError("Rectangle dimensions exceed canvas bounds")
# Draw the top and bo om edges
for i in range(rectangle.width):
canvas.set_pixel(rectangle.x + i, rectangle.y, '-')
canvas.set_pixel(rectangle.x + i, rectangle.y + rectangle.height - 1, '-')
# Draw the le and right edges
for i in range(rectangle.height):
canvas.set_pixel(rectangle.x, rectangle.y + i, '|')
canvas.set_pixel(rectangle.x + rectangle.width - 1, rectangle.y + i, '|')
# Example usage:
if __name__ == "__main__":
# Create a canvas
canvas = Canvas(20, 10)
# Define a rectangle
rect = Rectangle(4, 2, 10, 5)
# Draw the rectangle on the canvas
draw_rectangle(canvas, rect)
# Display the canvas
canvas.display()
19
OUTPUT:
|--------|
| |
| |
| |
|--------|
=== Code Execu on Successful ===
******************************************************************
27. Add an a ribute named color to your Rectangle objects and modify
draw_rectangle so that it uses the color a ribute as the fill color
PROGRAM:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def set_pixel(self, x, y, char):
self.data[y][x] = char
def display(self):
for row in self.data:
print(''.join(row))
class Rectangle:
def __init__(self, x, y, width, height, color='*'):
self.x = x
20
self.y = y
self.width = width
self.height = height
self.color = color
def draw_rectangle(canvas, rectangle):
# Ensure rectangle dimensions are within canvas bounds
if (rectangle.x < 0 or rectangle.y < 0 or
rectangle.x + rectangle.width > canvas.width or
rectangle.y + rectangle.height > canvas.height):
raise ValueError("Rectangle dimensions exceed canvas bounds")
# Draw the filled rectangle
for i in range(rectangle.height):
for j in range(rectangle.width):
canvas.set_pixel(rectangle.x + j, rectangle.y + i, rectangle.color)
# Example usage:
if __name__ == "__main__":
# Create a canvas
canvas = Canvas(20, 10)
# Define a rectangle with color
rect = Rectangle(4, 2, 10, 5, color='*')
# Draw the rectangle on the canvas
draw_rectangle(canvas, rect)
# Display the canvas
canvas.display()
21
OUTPUT:
--------------------
| |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| |
--------------------
28. Write a func on called draw_point that takes a Canvas and a Point
as arguments and draws a representa on of the Point on the Canvas.
PROGRAM:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
22
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def draw_point(self, point):
# Check if the point is within the bounds of the canvas
if 0 <= point.x < self.width and 0 <= point.y < self.height:
# Represent the point with '*'
self.data[point.y][point.x] = '*'
def display(self):
for row in self.data:
print(' '.join(row))
def main():
canvas = Canvas(20, 10)
point = Point(5, 3)
canvas.draw_point(point)
print("Canvas with Point:")
canvas.display()
if __name__ == "__main__":
main()
OUTPUT:
Canvas with Point:
23
29. Define a new class called Circle with appropriate a ributes and
instan ate a few Circle objects. Write a func on called draw_circle
that draws circles on the canvas.
PROGRAM:
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = [[' ' for _ in range(width)] for _ in range(height)]
def draw_point(self, point, char='*'):
# Check if the point is within the bounds of the canvas
if 0 <= point.x < self.width and 0 <= point.y < self.height:
self.data[point.y][point.x] = char
def draw_circle(self, circle):
# Midpoint circle drawing algorithm
24
cx, cy = circle.center.x, circle.center.y
radius = circle.radius
x = radius
y=0
decision = 1 - x
while y <= x:
self.draw_point(Point(cx + x, cy + y))
self.draw_point(Point(cx - x, cy + y))
self.draw_point(Point(cx + x, cy - y))
self.draw_point(Point(cx - x, cy - y))
self.draw_point(Point(cx + y, cy + x))
self.draw_point(Point(cx - y, cy + x))
self.draw_point(Point(cx + y, cy - x))
self.draw_point(Point(cx - y, cy - x))
y += 1
if decision <= 0:
decision += 2 * y + 1
else:
x -= 1
decision += 2 * (y - x) + 1
def display(self):
for row in self.data:
print(' '.join(row))
def main():
canvas = Canvas(20, 20)
25
# Example circles
circle1 = Circle(Point(8, 8), 5)
circle2 = Circle(Point(15, 10), 7)
# Draw circles on the canvas
canvas.draw_circle(circle1)
canvas.draw_circle(circle2)
print("Canvas with Circles:")
canvas.display()
if __name__ == "__main__":
main()
26
OUTPUT:
Canvas with Circles:
*
* *
* *
* *
* *
* *
* *
*
31. Write a python code to read a phone number and email-id from the
user and validate it for correctness.
PROGRAM:
import re
def validate_phone_number(phone_number):
# Regular expression pa ern for a valid phone number
pa ern = r'^(\+\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$'
return re.match(pa ern, phone_number) is not None
def validate_email(email):
# Regular expression pa ern for a valid email address
pa ern = r'^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$'
return re.match(pa ern, email) is not None
def main():
# Read phone number and email from the user
phone_number = input("Enter a phone number: ")
email = input("Enter an email address: ")
28
# Validate phone number
if validate_phone_number(phone_number):
print(f"Phone number '{phone_number}' is valid.")
else:
print(f"Phone number '{phone_number}' is not valid.")
# Validate email
if validate_email(email):
print(f"Email '{email}' is valid.")
else:
print(f"Email '{email}' is not valid.")
if __name__ == "__main__":
main()
OUTPUT:
Enter a phone number: 9959093361
Enter an email address: [email protected]
Phone number '9959093361' is valid.
Email '[email protected]' is valid.
29
WEEK-7
32. Write a Python code to merge two given file contents into a third
file
PROGRAM:
def merge_files(file1_name, file2_name, output_file_name):
try:
# Open the first file for reading
with open(file1_name, 'r') as file1:
file1_content = file1.read()
if __name__ == "__main__":
main()
OUTPUT:
File1.txt
Contents of file1.
Line 2 of file1.
File2.txt
Contents of file2.
Line 2 of file2.
merged_file.txt
Contents of file1.
Line 2 of file1.
31
Contents of file2.
Line 2 of file2.
33. Write a Python code to open a given file and construct a func on to
check for given words present in it and display on found.
PROGRAM:
def check_words_in_file(file_path, words_to_check):
try:
with open(file_path, 'r') as file:
file_content = file.read()
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'sample_file.txt' # Replace with your file path
32
words_to_check = ['apple', 'banana', 'orange', 'pear']
check_words_in_file(file_path, words_to_check)
if __name__ == "__main__":
main()
OUTPUT:
sample_file.txt
This is a sample file for tes ng purposes.
It contains some words like apple, orange, and banana.
34. Write a Python code to Read text from a text file, find the word with
most number of occurrences.
PROGRAM:
import re
from collec ons import Counter
def find_most_common_word(file_path):
try:
33
# Open the file and read its contents
with open(file_path, 'r') as file:
text = file.read()
# Use regex to extract words from the text (including hyphenated words)
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'sample_text.txt' # Replace with your file path
find_most_common_word(file_path)
if __name__ == "__main__":
34
main()
OUTPUT:
sample_text.txt
This is a sample text file. It contains some words like apple, banana, apple,
orange, banana, apple.
file_path = 'sample_text.txt
The most common word in 'sample_text.txt' is 'apple' with 3 occurrences.
35
35. Write a func on that reads a file file1 and displays the number of
words, number of vowels, blank spaces, lower case le ers and
uppercase le ers.
PROGRAM:
def analyze_file(file_path):
try:
with open(file_path, 'r') as file:
# Read the en re content of the file
content = file.read()
# Calculate the number of words
words = content.split()
num_words = len(words)
# Calculate the number of vowels
vowels = 'aeiouAEIOU'
num_vowels = sum(content.count(vowel) for vowel in vowels)
# Calculate the number of blank spaces
num_spaces = content.count(' ')
# Calculate the number of lowercase le ers
num_lower = sum(1 for char in content if char.islower())
# Calculate the number of uppercase le ers
num_upper = sum(1 for char in content if char.isupper())
# Print the analysis results
36
print(f"Number of words: {num_words}")
print(f"Number of vowels: {num_vowels}")
print(f"Number of blank spaces: {num_spaces}")
print(f"Number of lowercase le ers: {num_lower}")
print(f"Number of uppercase le ers: {num_upper}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except IOError:
print(f"Error reading file '{file_path}'.")
def main():
file_path = 'file1.txt' # Replace with your file path
analyze_file(file_path)
if __name__ == "__main__":
main()
OUTPUT:
file1.txt
This is a Sample TEXT file. It contains some words with vowels like apple, banana,
orange.
file_path = 'file1.txt
Number of words: 16
Number of vowels: 33
Number of blank spaces: 16
Number of lowercase le ers: 54
Number of uppercase le ers: 9
37
WEEK-8
36. Import numpy, Plotpy and Scipy and explore their func onali es.
PROGRAM:
import scipy.op mize as opt
from scipy.integrate import quad
# Example 1: Numerical Integra on
def integrand(x):
return np.exp(-x**2)
result, _ = quad(integrand, 0, np.inf)
print("Numerical Integra on Result:", result)
# Example 2: Op miza on
def objec ve(x):
return x**2 + 10*np.sin(x)
result = opt.minimize(objec ve, x0=0)
print("\nOp miza on Result:")
print("Minimum value:", result.fun)
print("Op mal x:", result.x)
OUTPUT:
Numerical Integra on Result: 0.8862269254527579
Op miza on Result:
Minimum value: -7.945823375615284
Op mal x: [-1.30644001]
38
37. Install NumPy package with pip and explore it
PROGRAM:
import numpy as np
# Crea ng a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(arr1)
2D Array (Matrix):
[[1 2 3]
[4 5 6]]
39
38. Write a program to implement Digital Logic Gates – AND, OR, NOT,
EX-OR.
PROGRAM:
# Define logic gates func ons
def AND_gate(input1, input2):
if input1 == 1 and input2 == 1:
return 1
else:
return 0
def OR_gate(input1, input2):
if input1 == 1 or input2 == 1:
return 1
else:
return 0
def NOT_gate(input1):
if input1 == 1:
return 0
else:
return 1
def XOR_gate(input1, input2):
if input1 != input2:
return 1
else:
return 0
# Test the logic gates
40
def main():
input1 = 1
input2 = 0
# AND gate
print(f"AND gate ({input1}, {input2}): {AND_gate(input1, input2)}")
# OR gate
print(f"OR gate ({input1}, {input2}): {OR_gate(input1, input2)}")
# NOT gate
print(f"NOT gate ({input1}): {NOT_gate(input1)}")
print(f"NOT gate ({input2}): {NOT_gate(input2)}")
# XOR gate
print(f"XOR gate ({input1}, {input2}): {XOR_gate(input1, input2)}")
if __name__ == "__main__":
main()
OUTPUT:
AND gate (1, 0): 0
OR gate (1, 0): 1
NOT gate (1): 0
NOT gate (0): 1
XOR gate (1, 0): 1
41
39. Write a program to implement Half Adder, Full Adder, and Parallel
Adder.
PROGRAM:
def half_adder(bit1, bit2):
sum_ = bit1 ^ bit2 # XOR gives the sum
carry = bit1 & bit2 # AND gives the carry
return sum_, carry
result = []
carry = 0
return result
def test_adders():
# Test Half Adder
bit1 = 1
bit2 = 0
sum_, carry = half_adder(bit1, bit2)
print(f"Half Adder: {bit1} + {bit2} = {sum_} (Sum), {carry} (Carry)")
44