0% found this document useful (0 votes)
3 views41 pages

python lab manual(CSM)

The document is a lab manual for Python programming at Annamacharya Institute of Technology and Sciences, detailing a list of experiments for first-year B.Tech students in the CSE department. It includes instructions for lab attendance, prerequisites for learning Python, and a comprehensive introduction to Python programming, including its features and characteristics. The manual outlines various programming exercises and tasks to be completed in the lab, covering topics such as basic arithmetic operations, data structures, functions, and GUI programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views41 pages

python lab manual(CSM)

The document is a lab manual for Python programming at Annamacharya Institute of Technology and Sciences, detailing a list of experiments for first-year B.Tech students in the CSE department. It includes instructions for lab attendance, prerequisites for learning Python, and a comprehensive introduction to Python programming, including its features and characteristics. The manual outlines various programming exercises and tasks to be completed in the lab, covering topics such as basic arithmetic operations, data structures, functions, and GUI programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ANNAMACHARAYA INSTITUTE OF TECHNOLOGY AND SCIENCES

PIGLIPUR, BATASINGRAM, HYDERABAD


(AUTONOMOUS)

DEPARTMENT OF CSE (ARTIFICIAL INTELLIGENCE & MACHINE


LEARNING)

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):

1. Identity card issued by the college


2. Class notes
3. Lab observation book
4. Lab manual
5. Lab record

During the lab session:

 Sign in and sign out in the register without fail.


 Arrive on time; students late by more than 15 minutes will not be allowed to attend.
 Maintain 100% attendance; strict action will be taken otherwise.
 Follow the dress code while in the lab.
 No food or drinks allowed inside the lab.
 Leave all bags at the designated place.
 Ask lab staff if you need any help with equipment or procedures.
 Respect the laboratory environment and other users.
 Keep your workspace clean and tidy after finishing the experiment.
 Read the manual carefully before coming to the lab and know what you are supposed
to do.
 Perform experiments strictly as per the instructions in the manual.
 Copy all class-taught programs to your observation book before the lab session.
 Do not use floppy disks or pen drives without permission from the lab in-charge.
 Submit lab records on or before the specified due date.
Introduction to Python Programming
What is Python?

Python is a high-level, general-purpose programming language that is interpreted,


interactive, and object-oriented. It was created by Guido van Rossum between 1985 and
1990. Python source code is freely available under the GNU General Public License (GPL).

Python is designed to be simple, readable, and easy to learn, using English-like keywords
and fewer symbols compared to other programming languages.

Prerequisites

To learn Python, you should have:

 Basic knowledge of computer programming concepts


 Familiarity with any programming language is an added advantage

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

 Easy to Learn – Simple syntax and fewer keywords make it beginner-friendly.


 Easy to Read – Clear and readable code structure.
 Easy to Maintain – Well-structured code simplifies maintenance.
 Extensive Standard Library – Supports cross-platform development on Windows,
UNIX, and macOS.
 Interactive Mode – Useful for testing and debugging code.
 Portable – Runs on different hardware platforms with the same interface.
 Extendable – Can be integrated with low-level languages like C and C++.
 Database Support – Provides interfaces to major commercial databases.
 GUI Programming – Supports GUI development using frameworks for Windows,
macOS, and Unix.
 Scalable – Suitable for both small scripts and large software systems.

Additional Advantages

 Supports procedural, functional, and object-oriented programming


 Supports dynamic typing and automatic garbage collection
 Can be integrated with C, C++, Java, COM, ActiveX, and CORBA
 Can be used as both a scripting language and for large application development
WEEK -1

Use a web browser to go to the Python website [Link]

Answer (Python code):

import webbrowser

[Link]('[Link]

Output:

 Opens your default web browser at Python’s official site: [Link]

Start the Python interpreter and type help() to start the online help utility.

Answer:

help()

Sample Output:

Welcome to Python 3.7's help utility!

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.

 Example commands inside help: modules, keywords, quit

Start a Python interpreter and use it as a calculator to perform operations +, -, *, /, %.

Answer:

first = int(input("Enter first number: "))


second = int(input("Enter second number: "))

print("---- Press keys for operator (+, -, *, /, %) ----")


operator = input("Enter operator: ")

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:

Enter first number: 10


Enter second number: 3
---- Press keys for operator (+, -, *, /, %) ----
Enter operator: +
Result: 13

Example Output 2:

Enter first number: 10


Enter second number: 3
---- Press keys for operator (+, -, *, /, %) ----
Enter operator: %
Result: 1

1.i) Write a program to calculate compound interest when principal, rate and number
of periods are given.

def compound_interest(principal, rate, time):

Amount = principal * (pow((1 + rate / 100), time))

CI = Amount - principal

print("Compound interest is", CI)

compound_interest(10000, 10.25, 5)

Output

Compound interest is 6288.946267774416


ii) Given coordinates(x1,y1),(x2, y2)find the distance between two points

import math

def distance(x1, y1, x2, y2):

return [Link]((x2 - x1)**2 + (y2 - y1)**2)

x1, y1 = 1, 2

x2, y2 = 4, 6

dist = distance(x1, y1, x2, y2)

print(f"The distance between the points ({x1}, {y1}) and ({x2}, {y2}) is {dist}")

Output:

The distance between the points (1, 2) and (4, 6) is 5.0

2) Read name,address,email and phone number of a person through keyboard and


print the details.

name = input("Enter your name: ")

address = input("Enter your address: ")

email = input("Enter your email: ")

phone_number = input("Enter your phone number: ")

print("\n--- Personal Details ---")

print(f"Name: {name}")

print(f"Address: {address}")

print(f"Email: {email}")

print(f"Phone Number: {phone_number}")

Output
Enter your name: sai

Enter your address: shiridi

Enter your email: sairam@[Link]

Enter your phone number: 82372343

--- Personal Details ---

Name: sai

Address: shiridi

Email: sairam@[Link]

Phone Number: 82372343

WEEK-2
[Link] the below triangle using for loop.

def half_pyramid(n):

for i in range(1, n + 1):

for j in range(1, i + 1):

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]():

print(f"{char} is a lowercase character.")

elif [Link]():

print(f"{char} is an uppercase character.")

else:

print(f"{char} is a special character.")

char = input("Enter a character: ")

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

while count < n:

print(a, end=" ")

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)

def prime(x, y):

prime_list = []

for i in range(x, y):

if i == 0 or i == 1: # Skip 0 and 1 as they are not prime numbers

continue

for j in range(2, int(i / 2) + 1): # Check divisibility from 2 to i/2

if i % j == 0: # If i is divisible by j, it's not a prime

break

else:

prime_list.append(i) # If no divisors are found, i is prime

return prime_list

# Driver program

starting_range = 2

ending_range = 7

primes = prime(starting_range, ending_range)

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

# Initialize a list and a tuple


list_data = [1, 2, 3, 4, 5]
tuple_data = (6, 7, 8, 9, 10)

# Convert the list and tuple into NumPy arrays


array1 = [Link](list_data)
array2 = [Link](tuple_data)

# Print the original list and tuple


print("Original list:")
print(list_data)

# Print the arrays after conversion


print("After converting list into array:")
print(array1)

print("After converting tuple into array:")


print(array2)

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]

ii) Write a program to find common values between two arrays.


def find_common_values(array1, array2):
common_values = set(array1) & set(array2)

return list(common_values)

array1 = [1, 2, 3, 4, 5]
array2 = [4, 5, 6, 7, 8]

common_values = find_common_values(array1, array2)

print("Common values between the two arrays:", common_values)

Output:

Common values between the two arrays: [4, 5]


[Link] a function called gcd that akes parameters a and b and returns their greatest
common divisor.

def gcd(a, b):


while b:
a, b = b, a % b
return a

a = int(input("Enter the first number: "))


b = int(input("Enter the second number: "))
print("The GCD of", a, "and", b, "is:", gcd(a, b))

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):

s = [Link](" ", "").lower()

if s == s[::-1]:
return True
else:
return False

string = input("Enter a string: ")

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.

additional_words = ["I", "a", ""]

file_path = "[Link]"
with open(file_path, 'r') as file:
words = [Link]().splitlines()

[Link](additional_words)

words = list(set(words))

[Link]()

with open(file_path, 'w') as file:


for word in words:
[Link](word + "\n")

print("Updated word list with 'I', 'a', and '' added.")


WEEK 5
1.i) Write a python program that defines a matrix and prints

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Print the matrix


print("Matrix:")
for row in matrix:
print(row)

Output:
Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

ii) Write a python program to perform addition of two square matrices


def add_matrices(matrix1, matrix2):

size = len(matrix1)

result = [[0 for _ in range(size)] for _ in range(size)]

for i in range(size):

for j in range(size):

result[i][j] = matrix1[i][j] + matrix2[i][j]

return result

matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]

result_matrix = add_matrices(matrix1, matrix2)

print("Resultant Matrix after addition:")


for row in result_matrix:

print(row)

Output:

Resultant Matrix after addition:

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]

iii) Write a python program to perform multiplication of two square matrices


def multiply_matrices(matrix1, matrix2):

size = len(matrix1)

result = [[0 for _ in range(size)] for _ in range(size)]

for i in range(size):

for j in range(size):

for k in range(size):

result[i][j] += matrix1[i][k] * matrix2[k][j]

return result

matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]

result_matrix = multiply_matrices(matrix1, matrix2)

print("Resultant Matrix after multiplication:")

for row in result_matrix:

print(row)

Output:
Resultant Matrix after multiplication:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]

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.
Create [Link] file
# [Link]

import math

# Function to calculate the area of a square


def area_square(side):
return side ** 2

# Function to calculate the perimeter of a square


def perimeter_square(side):
return 4 * side

# Function to calculate the area of a circle


def area_circle(radius):
return [Link] * (radius ** 2)

# Function to calculate the circumference of a circle


def circumference_circle(radius):
return 2 * [Link] * radius

# Function to calculate the area of a triangle


def area_triangle(base, height):
return 0.5 * base * height

# Function to calculate the perimeter of a triangle (assuming it's a right triangle)


def perimeter_triangle(base, height):
hypotenuse = [Link](base ** 2 + height ** 2)
return base + height + hypotenuse

Using [Link] module

# [Link]

import geometry # Import the geometry module

# Example usage of the module functions

# Square with side 5


side = 5
print(f"Area of square: {geometry.area_square(side)}")
print(f"Perimeter of square: {geometry.perimeter_square(side)}")

# Circle with radius 7


radius = 7
print(f"Area of circle: {geometry.area_circle(radius)}")
print(f"Circumference of circle: {geometry.circumference_circle(radius)}")
# Triangle with base 4 and height 3
base = 4
height = 3
print(f"Area of triangle: {geometry.area_triangle(base, height)}")
print(f"Perimeter of triangle: {geometry.perimeter_triangle(base, height)}")

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

3. Use the structure of exception handling all general purpose exceptions.


def exception_handling_demo():
try:
print("Choose an operation to perform:")
print("1. Division")
print("2. File Read")
print("3. List Access")
choice = int(input("Enter your choice (1/2/3): "))

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.")

# Run the program


if __name__ == "__main__":
exception_handling_demo()

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")

choice = int(input("Enter your choice (1/2/3): "))

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.")

# Run the program


if __name__ == "__main__":
exception_handling_demo()

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))

def set_pixel(self, x, y, char="*"):


"""Set a specific pixel on the canvas to a given character."""
if 0 <= x < [Link] and 0 <= y < [Link]:
[Link][y][x] = char

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 draw_rectangle(canvas, rectangle):


"""
Draw a rectangle on the given canvas.
"""
# Draw the top and bottom edges
for x in range(rectangle.x, rectangle.x + [Link]):
canvas.set_pixel(x, rectangle.y, "-") # Top edge
canvas.set_pixel(x, rectangle.y + [Link] - 1, "-") # Bottom edge

# Draw the left and right edges


for y in range(rectangle.y, rectangle.y + [Link]):
canvas.set_pixel(rectangle.x, y, "|") # Left edge
canvas.set_pixel(rectangle.x + [Link] - 1, y, "|") # Right edge

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))

def set_pixel(self, x, y, char="*"):


if 0 <= x < [Link] and 0 <= y < [Link]:
[Link][y][x] = char

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 draw_rectangle(canvas, rectangle):


# Fill the rectangle area with the color
for y in range(rectangle.y, rectangle.y + [Link]):
for x in range(rectangle.x, rectangle.x + [Link]):
canvas.set_pixel(x, y, [Link])

# Draw edges (overwrite fill)


for x in range(rectangle.x, rectangle.x + [Link]):
canvas.set_pixel(x, rectangle.y, "-") # Top edge
canvas.set_pixel(x, rectangle.y + [Link] - 1, "-") # Bottom edge

for y in range(rectangle.y, rectangle.y + [Link]):


canvas.set_pixel(rectangle.x, y, "|") # Left edge
canvas.set_pixel(rectangle.x + [Link] - 1, y, "|") # Right edge

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 draw_point(canvas, point):


canvas.set_pixel(point.x, point.y, [Link])

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))

def set_pixel(self, x, y, char="*"):


if 0 <= x < [Link] and 0 <= y < [Link]:
[Link][y][x] = char

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

def draw_circle(canvas, circle):


x0, y0, r = circle.center_x, circle.center_y, [Link]
char = [Link]

x=0
y=r
d = 1 - r # Decision parameter

def draw_symmetric_points(cx, cy, px, py):


canvas.set_pixel(cx + px, cy + py, char)
canvas.set_pixel(cx - px, cy + py, char)
canvas.set_pixel(cx + px, cy - py, char)
canvas.set_pixel(cx - px, cy - py, char)
canvas.set_pixel(cx + py, cy + px, char)
canvas.set_pixel(cx - py, cy + px, char)
canvas.set_pixel(cx + py, cy - px, char)
canvas.set_pixel(cx - py, cy - px, char)

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

*******
** **
* *
* *
* *
* *
* *
** **
*******

Circle at (10,10) radius 5 drawn with O

Circle at (25,10) radius 7 drawn with *

2. Write a Python program to demonstrate the usage of Method Resolution Order


(MRO) in multiple levels of Inheritances.

class A:

def show(self):

print("Method from class A")


class B(A):

def show(self):

print("Method from class B")

class C(A):

def show(self):

print("Method from class C")

class D(B, C):

pass

d = D()

[Link]()

# Print the Method Resolution Order (MRO)

print("MRO of class D:", [cls.__name__ for cls in D.__mro__])

output

Method from class B

MRO of class D: ['D', 'B', 'C', 'A', '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):
# 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

Enter your phone number: 825156956693


Enter your email id: gfdfvdfv2d56
Invalid phone number.
Invalid email id.

WEEK- 7

1. Write a Python code to merge two given file contents into a third file.

def merge_files(file1, file2, output_file):


try:
# Open the first file and read its contents
with open(file1, 'r') as f1:
content1 = [Link]()

# Open the second file and read its contents


with open(file2, 'r') as f2:
content2 = [Link]()

# Open the output file and write the merged content


with open(output_file, 'w') as out:
[Link](content1)
[Link]("\n") # Optional: Add newline between the two contents
[Link](content2)

print(f"Files '{file1}' and '{file2}' have been merged into '{output_file}'.")

except FileNotFoundError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

# Specify file names


file1 = input("Enter the name of the first file: ")
file2 = input("Enter the name of the second file: ")
output_file = input("Enter the name of the output file: ")

# Merge the files


merge_files(file1, file2, output_file)

output
1. Merge two files into a third file

Input:

Enter the name of the first file: [Link]


Enter the name of the second file: [Link]
Enter the name of the output file: [Link]

Output:

Files '[Link]' and '[Link]' have been merged into '[Link]'.

 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.

def check_words_in_file(file_name, words_to_check):


"""
Function to check for given words in a file and display them if 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}'...")

# Check for each word in the content


found_words = [word for word in words_to_check if [Link]() in content]

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(',')

# Strip any extra whitespace from the words


words_to_check = [[Link]() for word in words_to_check]

check_words_in_file(file_name, words_to_check)

output

Assume [Link] contains the text:

Hello world! This is a test file.

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:

Searching for words in '[Link]'...


The following words were found in the file: hello, test

If none of the words are found, it would print:

No given words were found in the 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

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()

# Remove punctuation from words


words = [[Link]([Link]) for word in words if [Link]([Link])]

# Count occurrences of each word


word_counts = Counter(words)

# Find the word with the maximum occurrences


most_frequent_word, frequency = word_counts.most_common(1)[0]

print(f"The most frequent word is '{most_frequent_word}' with {frequency} occurrences.")

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

Assume [Link] contains:

apple banana apple orange apple banana

Input:

Enter the name of the file (with extension, e.g., [Link]): [Link]

Output:

The most frequent word is 'apple' with 3 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.

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]())

# Display the results


print(f"Analysis of '{file_name}':")
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 letters: {num_lowercase}")
print(f"Number of uppercase letters: {num_uppercase}")

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)

Assume [Link] contains:

Hello World! This is a Test.

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

# NumPy: Array and Math Operation


arr = [Link]([1, 2, 3])
print("NumPy Array:", arr)
print("Mean:", [Link](arr))

# Plotly: Interactive Plotting


fig = [Link](data=[Link](y=[2, 3, 1]))
fig.update_layout(title='Simple Bar Graph')
[Link]()

# SciPy: Statistical Analysis


data = [2, 4, 6, 8, 10]
mean, var = [Link](data), [Link](data)
print("Mean (SciPy):", mean)
print("Variance (SciPy):", var)

output

NumPy Array: [1 2 3]
Mean: 2.0
Mean (SciPy): 6.0
Variance (SciPy): 10.0

2. a) Install NumPy package with pip and explore it.

pip install numpy


import numpy as np

# Basic array and operations


a = [Link]([10, 20, 30])
b = [Link]([1, 2, 3])
print("Addition:", a + b)
print("Multiplication:", a * b)
print("Dot product:", [Link](a, b))

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 OR(a, b):


return a | b

def NOT(a):
return ~a & 1 # Limit result to 0 or 1

def XOR(a, b):


return a ^ b

# 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

def half_adder(a, b):


sum_ = a ^ b
carry = a & b
return sum_, carry

def full_adder(a, b, cin):


sum1, carry1 = half_adder(a, b)
sum2, carry2 = half_adder(sum1, cin)
carry_out = carry1 | carry2
return sum2, carry_out

def parallel_adder(bits1, bits2):


result = []
carry = 0
for b1, b2 in zip(bits1[::-1], bits2[::-1]):
s, carry = full_adder(b1, b2, carry)
[Link](0, s)
[Link](0, carry)
return result

# 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")

# Labels and Entries


[Link](window, text="First Name").grid(row=0, column=0)
entry1 = [Link](window)
[Link](row=0, column=1)

[Link](window, text="Last Name").grid(row=1, column=0)


entry2 = [Link](window)
[Link](row=1, column=1)

# 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

A window appears with:

 Two text labels: “First Name” and “Last Name”


 Two text fields
 Two buttons: Submit and Reset

On clicking "Submit", the values entered in the fields are printed in the console:

Submitted: John Doe

On clicking "Reset", both fields are cleared.


THE END

You might also like