python lab manual(CSM)
python lab manual(CSM)
PYTHON PROGRAMMING
LAB MANUAL
FACULTY: [Link]
FOR
B TECH CSE/CSM
1st YEAR- SEM-II(R25)
LIST OF EXPERIMENTS
1. Use a web browser to go to the Python website [Link] Explore the
information available on Python and the links to Python-related pages. Start the
Python interpreter and type help() to use the online help utility.
2. Start the Python interpreter and use it as a calculator to perform basic arithmetic
operations.
3. Write a Python program to calculate compound interest when the principal amount,
rate of interest, and number of periods are given.
4. Write a Python program to read the name, address, email, and phone number of a
person through the keyboard and print the details.
5. Write a Python program to print the following triangle using a for loop:
5
44
333
2222
11111
6. Write a Python program to check whether the given input character is a digit,
lowercase character, uppercase character, or a special character using an if–else–if
ladder.
7. Write a Python program to print all prime numbers in a given interval using the break
statement.
8. Write a Python program to convert a list and a tuple into arrays.
9. Write a Python program to find common values between two arrays.
10. Write a function called palindrome that takes a string argument and returns True if it is
a palindrome and False otherwise. Use the built-in function len().
11. 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.
12. Write a function called has_duplicates that takes a list and returns True if any element
appears more than once. The original list should not be modified.
13. Write a function called remove_duplicates that takes a list and returns a new list
containing only unique elements from the original list. The order need not be
preserved.
14. Write a Python program to read dictionary values from the user and construct a
function to invert the dictionary such that keys become values and values become
keys.
15. Write a Python program to add a comma between the characters of a word. Example:
If the given word is Apple, the output should be A,p,p,l,e.
16. Write a Python program to remove a given word from all places in a string.
17. Write a function that takes a sentence as input and converts the first letter of every
word to uppercase and the remaining letters to lowercase without using built-in
functions.
18. Write a recursive function that generates all binary strings of n-bit length.
19. Write a Python program to define a matrix and print it.
20. Write a Python program to perform multiplication of two square matrices.
21. Explain how to create a Python module. Construct a module using different
geometrical shapes and define operations on them as functions.
22. Write a Python program demonstrating the structure of exception handling for general-
purpose exceptions.
23. 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.
24. Add an attribute named color to Rectangle objects and modify the draw_rectangle
function so that it uses the color attribute as the fill color.
25. 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.
26. Define a new class called Circle with appropriate attributes. Instantiate a few Circle
objects and write a function called draw_circle to draw circles on the canvas.
27. Write a Python program to read a phone number and email-id from the user and
validate them for correctness.
28. Write a Python program to merge the contents of two files into a third file.
29. Write a Python program to open a given file and construct a function to check whether
given words are present in the file and display them if found.
30. Write a Python program to read text from a file and find the word with the maximum
number of occurrences.
31. Write a function that reads a file and displays the number of words, number of vowels,
blank spaces, lowercase letters, and uppercase letters.
32. Import NumPy, Plotly, and SciPy libraries and explore their functionalities.
33. Install the NumPy package using pip and explore its features.
34. Write a Python program to implement digital logic gates AND, OR, NOT, and EX-
OR.
35. Write a GUI program to create a window wizard containing two text labels, two text
fields, and two buttons named Submit and Reset.
Instructions to Students
Before entering the lab, students must carry the following (MANDATORY):
Python is designed to be simple, readable, and easy to learn, using English-like keywords
and fewer symbols compared to other programming languages.
Prerequisites
Characteristics of Python
Interpreted Language
Python programs are executed line by line by the interpreter. There is no need for
compilation, similar to Perl and PHP.
Interactive Language
Python allows users to interact directly with the interpreter using the Python prompt.
Object-Oriented Language
Python supports object-oriented programming concepts such as classes and objects,
which help in organizing code efficiently.
Beginner-Friendly Language
Python is easy to learn and is widely used for applications ranging from simple scripts
to web development, games, and data analysis.
History of Python
Python was developed by Guido van Rossum at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
It was influenced by several programming languages such as:
ABC
Modula-3
C and C++
Algol-68
SmallTalk
Unix Shell scripting
Python is currently maintained by a core development team, with Guido van Rossum
continuing to play a significant role in its development.
Features of Python
Additional Advantages
import webbrowser
[Link]('[Link]
Output:
Start the Python interpreter and type help() to start the online help utility.
Answer:
help()
Sample Output:
If this is your first time using Python, you should definitely check out the tutorial:
[Link]
Enter the name of any module, keyword, or topic to get help on writing Python programs.
Type 'quit' to exit.
Answer:
if operator == "+":
print("Result:", first + second)
elif operator == "-":
print("Result:", first - second)
elif operator == "*":
print("Result:", first * second)
elif operator == "/":
print("Result:", first / second)
elif operator == "%":
print("Result:", first % second)
else:
print("Invalid Operation")
Example Output 1:
Example Output 2:
1.i) Write a program to calculate compound interest when principal, rate and number
of periods are given.
CI = Amount - principal
compound_interest(10000, 10.25, 5)
Output
import math
x1, y1 = 1, 2
x2, y2 = 4, 6
print(f"The distance between the points ({x1}, {y1}) and ({x2}, {y2}) is {dist}")
Output:
print(f"Name: {name}")
print(f"Address: {address}")
print(f"Email: {email}")
Output
Enter your name: sai
Name: sai
Address: shiridi
Email: sairam@[Link]
WEEK-2
[Link] the below triangle using for loop.
def half_pyramid(n):
print("5", end="")
print()
half_pyramid(5)
Output
*
**
***
****
*****
[Link] 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)
def check_input_type(char):
if [Link]():
print(f"{char} is a digit.")
elif [Link]():
elif [Link]():
else:
check_input_type(char)
Output:
Enter a character: a
a is a lowercase character.
Enter a character: A
A is an uppercase character
Enter a character: $
$ is a special character.
3. Python Program to Print the Fibonacci sequence using while loop
def fibonacci(n):
a, b = 0, 1
count = 0
a, b = b, a + b
count += 1
n = 10
fibonacci(n)
Output
0 1 1 2 3 5 8 13 21 34
4. Python program to print all prime numbers in a given interval(usebreak)
prime_list = []
continue
break
else:
return prime_list
# Driver program
starting_range = 2
ending_range = 7
print(primes)
Output
[2, 3, 5]
Week-3
1. i) Write a program to convert a list and tuple into arrays
import numpy as np
Output
Original list:
[1, 2, 3, 4, 5]
After converting list into array:
[1 2 3 4 5]
After converting tuple into array:
[ 6 7 8 9 10]
return list(common_values)
array1 = [1, 2, 3, 4, 5]
array2 = [4, 5, 6, 7, 8]
Output:
Output:
Enter the first number: 4
Enter the second number: 5
The GCD of 4 and 5 is: 1
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.
def palindrome(s):
if s == s[::-1]:
return True
else:
return False
if palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")
Output:
Enter a string: madam
'madam' is a palindrome.
Week-4
[Link] 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. a=[1,2,3,4,5]
def is_sorted(a):
return a == sorted(a)
a = [1, 2, 3, 4, 5]
if is_sorted(a):
print("The list is sorted in ascending order.")
else:
print("The list is not sorted in ascending order.")
Output:
The list is sorted in ascending order.
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.
def has_duplicates(lst):
return len(lst) != len(set(lst))
a = [1, 2, 3, 4, 5]
if has_duplicates(a):
print("The list has duplicates.")
else:
print("The list does not have duplicates.")
Output:
The list does not have duplicates.
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):
return list(set(lst))
a = [1, 2, 2, 3, 4, 5, 5]
print("Original list:", a)
print("List with duplicates removed:", remove_duplicates(a))
Output:
Original list: [1, 2, 2, 3, 4, 5, 5]
List with duplicates removed: [1, 2, 3, 4, 5]
ii). The wordlist I provided, [Link], doesn’t contain single letter words. So you might
want to add “I”, “a”, and the empty string.
file_path = "[Link]"
with open(file_path, 'r') as file:
words = [Link]().splitlines()
[Link](additional_words)
words = list(set(words))
[Link]()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output:
Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
size = len(matrix1)
for i in range(size):
for j in range(size):
return result
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
print(row)
Output:
size = len(matrix1)
for i in range(size):
for j in range(size):
for k in range(size):
return result
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
print(row)
Output:
Resultant Matrix after multiplication:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
import math
# [Link]
Output:
Area of square: 25
Perimeter of square: 20
Area of circle: 153.93804002589985
Circumference of circle: 43.982297150257104
Area of triangle: 6.0
Perimeter of triangle: 12.0
if choice == 1:
# Division operation
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print(f"Result: {result}")
elif choice == 2:
# File read operation
filename = input("Enter the filename to read: ")
with open(filename, 'r') as file:
content = [Link]()
print("File content:")
print(content)
elif choice == 3:
# List access operation
my_list = [1, 2, 3, 4, 5]
index = int(input("Enter the index to access: "))
print(f"Value at index {index}: {my_list[index]}")
else:
print("Invalid choice!")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except FileNotFoundError:
print("Error: The specified file was not found.")
except IndexError:
print("Error: Index out of range for the list.")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Operation completed successfully.")
finally:
print("Exception handling demo completed.")
output
Choose an operation to perform:
1. Division
2. File Read
3. List Access
Enter your choice (1/2/3): 1
Enter numerator: 8
Enter denominator: 7
Result: 1.1428571428571428
Operation completed successfully.
Exception handling demo completed.
def exception_handling_demo():
try:
print("Choose an operation to perform:")
print("1. Division")
print("2. File Read")
print("3. List Access")
if choice == 1:
# Division operation
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print(f"Result: {result}")
elif choice == 2:
# File read operation
filename = input("Enter the filename to read: ")
with open(filename, 'r') as file:
content = [Link]()
print("File content:")
print(content)
elif choice == 3:
# List access operation
my_list = [1, 2, 3, 4, 5]
index = int(input("Enter the index to access: "))
print(f"Value at index {index}: {my_list[index]}")
else:
print("Invalid choice!")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except FileNotFoundError:
print("Error: The specified file was not found.")
except IndexError:
print("Error: Index out of range for the list.")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Operation completed successfully.")
finally:
print("Exception handling demo completed.")
Output
Case 1: Division by zero
Choose an operation to perform:
1. Division
2. File Read
3. List Access
Enter your choice (1/2/3): 1
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
Exception handling demo completed.
Case 2: File not found
Choose an operation to perform:
1. Division
2. File Read
3. List Access
Enter your choice (1/2/3): 2
Enter the filename to read: non_existent.txt
Error: The specified file was not found.
Exception handling demo completed.
Case 3: Successful list access
Choose an operation to perform:
1. Division
2. File Read
3. List Access
Enter your choice (1/2/3): 3
Enter the index to access: 2
Value at index 2: 3
Operation completed successfully.
Exception handling demo completed.
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.
class Canvas:
"""
Represents a canvas as a grid of characters.
"""
def __init__(self, width, height):
[Link] = width
[Link] = height
# Initialize canvas with empty spaces
[Link] = [[" " for _ in range(width)] for _ in range(height)]
def draw(self):
"""Display the canvas."""
for row in [Link]:
print("".join(row))
class Rectangle:
"""
Represents a rectangle with top-left corner, width, and height.
"""
def __init__(self, x, y, width, height):
self.x = x
self.y = y
[Link] = width
[Link] = height
def main():
canvas = Canvas(20, 10) # Create a canvas of size 20x10
rectangle = Rectangle(5, 3, 10, 5) # Rectangle at (5,3) with width 10 and height 5
draw_rectangle(canvas, rectangle)
[Link]()
if __name__ == "__main__":
main()
output
|--------|
| |
| |
| |
|--------|
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.
class Canvas:
def __init__(self, width, height):
[Link] = width
[Link] = height
[Link] = [[" " for _ in range(width)] for _ in range(height)]
def draw(self):
for row in [Link]:
print("".join(row))
class Rectangle:
"""
Rectangle with color attribute.
"""
def __init__(self, x, y, width, height, color="#"):
self.x = x
self.y = y
[Link] = width
[Link] = height
[Link] = color
def main():
canvas = Canvas(20, 10)
rectangle = Rectangle(5, 3, 10, 5, "#")
draw_rectangle(canvas, rectangle)
[Link]()
if __name__ == "__main__":
main()
output
|--------|
|########|
|########|
|########|
|--------|
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.
class Canvas:
def __init__(self, width, height):
[Link] = width
[Link] = height
[Link] = [[" " for _ in range(width)] for _ in range(height)]
def draw(self):
for row in [Link]:
print("".join(row))
def set_pixel(self, x, y, char="*"):
if 0 <= x < [Link] and 0 <= y < [Link]:
[Link][y][x] = char
class Point:
"""
Represents a point with x, y coordinates and a character.
"""
def __init__(self, x, y, char="*"):
self.x = x
self.y = y
[Link] = char
def main():
canvas = Canvas(20, 10)
point1 = Point(5, 5, "X")
point2 = Point(10, 3, "O")
point3 = Point(15, 8, "+")
draw_point(canvas, point1)
draw_point(canvas, point2)
draw_point(canvas, point3)
[Link]()
if __name__ == "__main__":
main()
output
d. Define a new class called Circle with appropriate attributes and instantiate a few
Circle objects.
import math
class Canvas:
def __init__(self, width, height):
[Link] = width
[Link] = height
[Link] = [[" " for _ in range(width)] for _ in range(height)]
def draw(self):
for row in [Link]:
print("".join(row))
class Circle:
"""
Represents a circle with center, radius, and character.
"""
def __init__(self, center_x, center_y, radius, char="*"):
self.center_x = center_x
self.center_y = center_y
[Link] = radius
[Link] = char
x=0
y=r
d = 1 - r # Decision parameter
draw_symmetric_points(x0, y0, x, y)
while x < y:
x += 1
if d < 0:
d += 2 * x + 1
else:
y -= 1
d += 2 * (x - y) + 1
draw_symmetric_points(x0, y0, x, y)
def main():
canvas = Canvas(40, 20)
circle1 = Circle(10, 10, 5, "O")
circle2 = Circle(25, 10, 7, "*")
draw_circle(canvas, circle1)
draw_circle(canvas, circle2)
[Link]()
if __name__ == "__main__":
main()
output
OOOOO
O O
O O
O O
O O
O O
O O
O O
OOOOO
*******
** **
* *
* *
* *
* *
* *
** **
*******
class A:
def show(self):
def show(self):
class C(A):
def show(self):
pass
d = D()
[Link]()
output
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):
# Example: Validate 10-digit number, optionally with country code +91 or 0
pattern = [Link](r"^(?:\+91|0)?[6-9]\d{9}$")
return bool([Link](phone))
def validate_email(email):
# Simple regex for email validation
pattern = [Link](r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
return bool([Link](email))
def main():
phone = input("Enter your phone number: ")
email = input("Enter your email id: ")
if validate_phone(phone):
print("Valid phone number.")
else:
print("Invalid phone number.")
if validate_email(email):
print("Valid email id.")
else:
print("Invalid email id.")
if __name__ == "__main__":
main()
output
WEEK- 7
1. Write a Python code to merge two given file contents into a third file.
except FileNotFoundError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
output
1. Merge two files into a third file
Input:
Output:
The [Link] file will contain the contents of [Link] followed by a newline, then
contents of [Link].
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.
Args:
file_name (str): Name of the file to check.
words_to_check (list): List of words to search for in the file.
"""
try:
with open(file_name, 'r') as file:
content = [Link]().lower() # Case insensitive search
print(f"Searching for words in '{file_name}'...")
if found_words:
print(f"The following words were found in the file: {', '.join(found_words)}")
else:
print("No given words were found in the file.")
except FileNotFoundError:
print(f"Error: The file '{file_name}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
file_name = input("Enter the name of the file (with extension, e.g., [Link]): ")
words_to_check = input("Enter the words to search for (comma-separated): ").split(',')
check_words_in_file(file_name, words_to_check)
output
Input:
Enter the name of the file (with extension, e.g., [Link]): [Link]
Enter the words to search for (comma-separated): hello, python, test
Output:
3. Write a Python code to Read text from a text file, find the word with most number of
occurrences
def find_most_frequent_word(file_name):
"""
Reads text from a file and finds the word with the most occurrences.
Args:
file_name (str): Name of the file to read.
Returns:
str: The word with the most occurrences and its frequency.
"""
try:
with open(file_name, 'r') as file:
content = [Link]()
# Split the content into words (case-insensitive)
words = [Link]().split()
except FileNotFoundError:
print(f"Error: The file '{file_name}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
file_name = input("Enter the name of the file (with extension, e.g., [Link]): ")
find_most_frequent_word(file_name)
output
Input:
Enter the name of the file (with extension, e.g., [Link]): [Link]
Output:
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.
def analyze_file(file_name):
"""
Reads a file and analyzes the text for various statistics.
Args:
file_name (str): Name of the file to analyze.
Displays:
- Number of words
- Number of vowels
- Number of blank spaces
- Number of lowercase letters
- Number of uppercase letters
"""
try:
with open(file_name, 'r') as file:
content = [Link]()
# Calculate statistics
num_words = len([Link]())
num_vowels = sum(1 for char in content if [Link]() in 'aeiou')
num_spaces = [Link](' ')
num_lowercase = sum(1 for char in content if [Link]())
num_uppercase = sum(1 for char in content if [Link]())
except FileNotFoundError:
print(f"Error: The file '{file_name}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
file_name = input("Enter the name of the file (with extension, e.g., [Link]): ")
analyze_file(file_name)
Input:
Enter the name of the file (with extension, e.g., [Link]): [Link]
Output:
javascript
CopyEdit
Analysis of '[Link]':
Number of words: 6
Number of vowels: 7
Number of blank spaces: 5
Number of lowercase letters: 14
Number of uppercase letters: 2
WEEK - 8
1. Import numpy, Plotpy and Scipy and explore their functionalities.
import numpy as np
import plotly.graph_objects as go
from scipy import stats
output
NumPy Array: [1 2 3]
Mean: 2.0
Mean (SciPy): 6.0
Variance (SciPy): 10.0
output
Addition: [11 22 33]
Multiplication: [10 40 90]
Dot product: 140
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
def AND(a, b):
return a & b
def NOT(a):
return ~a & 1 # Limit result to 0 or 1
# Test
print("AND(1, 0):", AND(1, 0))
print("OR(1, 0):", OR(1, 0))
print("NOT(1):", NOT(1))
print("XOR(1, 0):", XOR(1, 0))
output
AND(1, 0): 0
OR(1, 0): 1
NOT(1): 0
XOR(1, 0): 1
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
# Example
print("Half Adder (1, 1):", half_adder(1, 1))
print("Full Adder (1, 1, 1):", full_adder(1, 1, 1))
print("Parallel Adder ([1,0,1], [1,1,0]):", parallel_adder([1,0,1], [1,1,0]))
output
Half Adder (1, 1): (0, 1)
Full Adder (1, 1, 1): (1, 1)
Parallel Adder ([1,0,1], [1,1,0]): [1, 0, 1, 1]
5. Write a GUI program to create a window wizard having two text labels, two
text fields and two buttons as Submit and Reset.
import tkinter as tk
def submit():
print("Submitted:", [Link](), [Link]())
def reset():
[Link](0, [Link])
[Link](0, [Link])
# Create window
window = [Link]()
[Link]("Simple Form")
# Buttons
[Link](window, text="Submit", command=submit).grid(row=2, column=0)
[Link](window, text="Reset", command=reset).grid(row=2, column=1)
[Link]()
output
On clicking "Submit", the values entered in the fields are printed in the console: