0% found this document useful (0 votes)
2 views72 pages

Python Lab Programs

The document provides a comprehensive guide on Python programming, covering installation, basic arithmetic operations, and various programming tasks such as calculating compound interest, reading user input, checking character types, and working with arrays and matrices. It includes detailed code examples for each task, demonstrating functions, loops, and conditionals. Additionally, it explores advanced topics like recursion, matrix operations, and using the NumPy library for numerical computations.

Uploaded by

paninfo05
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views72 pages

Python Lab Programs

The document provides a comprehensive guide on Python programming, covering installation, basic arithmetic operations, and various programming tasks such as calculating compound interest, reading user input, checking character types, and working with arrays and matrices. It includes detailed code examples for each task, demonstrating functions, loops, and conditionals. Additionally, it explores advanced topics like recursion, matrix operations, and using the NumPy library for numerical computations.

Uploaded by

paninfo05
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMS

CYCLE 1:

1.

I. Use a web browser to go to the Python website [Link] This page contains
information about Python and links to Python-related pages, and it gives you the ability
to search the Python documentation.
# Python Download and Installation Process

Python: Version 3.10.5


Downloading
1. link to download latest python [Link]
Visit this

The following page will appear in your browser.

Installing
1. Double-click the icon labeling the file [Link].
An Open File - Security Warning pop-up window will appear.

2. Click Run.
A Python 3.10.5 (64-bit) Setup pop-up window will appear.
Ensure that the Install launcher for all users (recommended) and the Add Python

3.10 to PATH checkboxes at the bottom are checked.

A new Python 3.10.0 (64-bit) Setup pop-up window will appear with a Setup Progress message and a
progress bar.

During installation, it will show the various components it is installing and move the progress bar towards
completion. Soon, a new Python 3.10.0 (64-bit) Setup pop-up window will appear with a Setup was
successfully message.
[Link] the Close
button. Python installed
II. Start the Python interpreter and type help () to start the online help utility.
2. Start a Python interpreter and use it for arithmetic operations.
3. Write a program to calculate compound interest when principal, rate, frequency of
compounding and number of years are given.

# A program to calculate compound interest


P = 1200 # Principal
T=2 # Time in years
R = 5.4 # Rate of interest
N=1 # Frequency of compounding

amount = P * (1 + R / (100 * N)) ** (N * T)


CI = amount - P
print("Compound Interest =", CI)
print("Total Amount =", amount)
output:

Compound Interest = 133.0992

Total Amount = 1333.0992


4. Read the name, address, email and phone number of a person through the keyboard
and print the details.
#A program to read and print personal details
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")

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


print("Name:", name)
print("Address:", address)
print("Email:", email)
print("Phone Number:", phone)

output:
Enter name: Ram
Enter address: India
Enter email: ram@[Link]
Enter phone number: 9876543210
--- Person Details ---
Name: Ram
Address: India
Email: ram@[Link]
Phone Number: 9876543210
5. Print the below pattern using a for loop.

5
44
333
2222
11111
for i in range(5, 0, -1):
for j in range(6 - i):
print(i, end=" ")
print()
(or)
n=int(input())
for i in range(n):
for j in range(i+1):
print(n-i, end=" ")
print()
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

ch = input("Enter a character: ")

# Check only single character

if len(ch) != 1:

print("Please enter only one character.")

elif ch >= '0' and ch <= '9':

print("It is a digit.")

elif ch >= 'a' and ch <= 'z':

print("It is a lowercase character.")

elif ch >= 'A' and ch <= 'Z':

print("It is an uppercase character.")

else:

print("It is a special character.")

output:

Enter a character: Z

Uppercase character
[Link] program to print all prime numbers in a given interval (use break).

start = int(input("enter start no.."))

end = int(input("enter end no.."))

for num in range(start, end + 1):

count = 0

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

if num % i == 0:

count += 1

if count == 2:

print(num, end=" ")

output:

Enter the starting number: 5

Enter the ending number: 15

Prime numbers between 5 and 15 are:

5 7 11 13
8. Write a program to convert a list and tuple into arrays.

from array import array

# List and Tuple

my_list = [5, 10, 15]

my_tuple = (20, 25, 30)

# Convert to arrays

array1 = array('i', my_list)

array2 = array('i', my_tuple)

print("Array from List:", array1)

print("Array from Tuple:", array2)

Output:

Array from List: array('i', [5, 10, 15])

Array from Tuple: array('i', [20, 25, 30])


9. Write a program to find common values between two arrays.

array1 = [1, 2, 3, 4, 5, 6]

array2 = [4, 5, 6, 7, 8, 9]

# Convert arrays to sets and find common elements

common = set(array1) & set(array2)

# Convert result back to list

common_values = list(common)

print("Common values:", common_values)

Output: [4, 5, 6]
10. 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):

# Remove spaces and convert to lowercase

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

# Check if string is equal to its reverse

return s == s[::-1]

# Example usage

word = input("Enter a string: ")

if palindrome(word):

print(word, "is a palindrome")

else:

print(word, "is not a palindrome")

Output:

Enter a string: Racecar


NOTE:

s[::-1] → Reversing a string

• In Python, strings support slicing: s[start:stop:step]


• s[::-1] means:
o start → default (beginning of string)
o stop → default (end of string)
o step = -1 → move backwards, effectively reversing the string
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.

def is_sorted(lst):

return lst == sorted(lst)

# Read list from user

n = int(input("Enter number of elements: "))

lst = []

for i in range(n):

[Link](int(input("Enter element: ")))

# Check and display result

if is_sorted(lst):

print("The list is sorted in ascending order")

else:

print("The list is not sorted in ascending order")

Output:

Enter number of elements: 4

Enter element: 2

Enter element: 4

Enter element: 6

Enter element: 8

The list is sorted in ascending order


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

for i in range(len(lst)):

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

if lst[i] == lst[j]:

return True

return False

# Read list from user

n = int(input("Enter number of elements: "))

lst = []

for i in range(n):

[Link](input("Enter element: "))

# Check and display result

if has_duplicates(lst):

print("The list has duplicate elements")

else:

print("The list has no duplicate elements")

Output:

Enter number of elements: 3

Enter element: 1

Enter element: 2

Enter element: 2

The list has duplicate elements


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

# Read list from user

n = int(input("Enter number of elements: "))

lst = []

for i in range(n):

[Link](input("Enter element: "))

new_list = remove_duplicates(lst)

print("Original list:", lst)

print("List without duplicates:", new_list)

Output:

Enter number of elements: 5

Enter element: 10

Enter element: 20

Enter element: 10

Enter element: 30

Enter element: 20

Original list: ['10', '20', '10', '30', '20']

List without duplicates: ['20', '10', '30']


14. Create a text file named [Link] containing a list of words, one per line and it should
not include single-letter words or an empty string. Write a Python function that adds “I”,
“a”, and the empty string to the word list.

def add_words(filename):

# Read words from file

with open(filename, "r") as file:

words = [Link]().splitlines()

# Add required words

[Link]("I")

[Link]("a")

[Link]("")

return words

# Function call

word_list = add_words("[Link]")

print("Updated word list:")

print(word_list)

Output:

Updated word list:

['apple', 'banana', 'computer', 'python', 'science', 'I', 'a', '']


15. 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_dictionary(d):

inverted = {}

for key, value in [Link]():

inverted[value] = key

return inverted

# Read dictionary from user

n = int(input("Enter number of key-value pairs: "))

d = {}

for i in range(n):

key = input("Enter key: ")

value = input("Enter value: ")

d[key] = value

# Invert dictionary

inv_dict = invert_dictionary(d)

print("Original Dictionary:", d)

print("Inverted Dictionary:", inv_dict)

Output:

Enter number of key-value pairs: 3

Enter key: a

Enter value: 1

Enter key: b

Enter value: 2
Enter key: c

Enter value: 3

Original Dictionary: {'a': '1', 'b': '2', 'c': '3'}

Inverted Dictionary: {'1': 'a', '2': 'b', '3': 'c'}


16. Write a python code to add a comma between the characters. If the given word is
'Apple', it should become 'A,p,p,l,e' .

word = "Apple"

result = ",".join(word)

print(result)

Output: A,p,p,l,e

(Or)

def add_commas(word):
return ",".join(word)

print(add_commas("Apple"))
print(add_commas("bananna"))
name=input("enter any string")
print(add_commas(name))
Output:
A,p,p,l,e
b,a,n,a,n,n,a
enter any stringberry
b,e,r,r,y
17. Write a python program to remove the given word in all the places in a string.

text = "Python is easy and Python is powerful"

word_to_remove = "Python"

result = [Link](word_to_remove, "")

print(result)

Output:

is easy and is powerful


CYCLE 2:

18. Write a function that takes a sentence as an input parameter and replaces the first
letter of every word with the corresponding upper case letter and the rest of the letters in
the word by corresponding letters in lower case without using a built-in function.

def capitalize_sentence(sentence):

result = ""

new_word = True

for ch in sentence:

# Check for space

if ch == " ":

result += ch

new_word = True

else:

if new_word:

# Convert first letter of word to uppercase

if 'a' <= ch <= 'z':

result += chr(ord(ch) - 32)

else:

result += ch

new_word = False

else:

# Convert remaining letters to lowercase

if 'A' <= ch <= 'Z':

result += chr(ord(ch) + 32)

else:
result += ch

return result

Output:

s = "hELLo woRLD fROM pYtHON"

print(capitalize_sentence(s))

Hello World From Python


19. Writes a recursive function that generates all binary strings of n-bit length

def generate_binary_strings(n):

# Base case

if n == 0:

return [""]

smaller = generate_binary_strings(n - 1)

result = []

for s in smaller:

[Link]("0" + s)

[Link]("1" + s)

return result

n=3

binary_strings = generate_binary_strings(n)

for b in binary_strings:

print(b)

Output:

000

100

010

110

001

101

011

111
20. Write a python program that defines a matrix and prints.

import numpy as np

# Define a matrix

matrix = [Link]([

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

])

# Print the matrix

print(matrix)

Output:

[[1 2 3]

[4 5 6]

[7 8 9]]
21. Write a python program to perform multiplication of two square matrices.

import numpy as np

# Define first square matrix

A = [Link]([[1, 2],

[3, 4]])

# Define second square matrix

B = [Link]([[5, 6],

[7, 8]])

# Multiply the matrices

C = [Link](A, B)

# Print the result

print("Matrix A:")

print(A)

print("\nMatrix B:")

print(B)

print("\nProduct of A and B:")

print(C)

Output:
Matrix A:

[[1 2]

[3 4]]

Matrix B:

[[5 6]

[7 8]]

Product of A and B:

[[19 22]

[43 50]]
22. Import Numpy and explore their functionalities.

a) Creating a matrix of given order m x n containing random numbers in the range 1 to


99999.

import numpy as np

m=3

n=4

matrix = [Link](1, 100000, size=(m, n))

print("Matrix:\n", matrix)

print("Shape:", [Link])

print("Data type:", [Link])

print("Max:", [Link]())

print("Min:", [Link]())

print("Sum:", [Link]())

print("Mean:", [Link]())

print("Transpose:\n", matrix.T)

Output:

Matrix:

[[54321 98765 12345 67890]

[23456 34567 45678 56789]

[87654 76543 65432 54321]]

Shape: (3, 4)
Data type: int64

Max: 98765

Min: 12345

Sum: 603311

Mean: 50275.916666666664

Transpose:

[[54321 23456 87654]

[98765 34567 76543]

[12345 45678 65432]

[67890 56789 54321]]

b)Write a program that adds, subtracts and multiplies two matrices. Provide an interface
such that, based on the prompt, the function (addition, subtraction, multiplication)
should be performed.

import numpy as np

# Input matrix order

r1 = int(input("Enter number of rows for Matrix A: "))

c1 = int(input("Enter number of columns for Matrix A: "))

r2 = int(input("Enter number of rows for Matrix B: "))

c2 = int(input("Enter number of columns for Matrix B: "))

# Input matrices

print("\nEnter elements of Matrix A:")

A = [Link]([[int(input()) for j in range(c1)] for i in range(r1)])


print("\nEnter elements of Matrix B:")

B = [Link]([[int(input()) for j in range(c2)] for i in range(r2)])

# Display matrices

print("\nMatrix A:\n", A)

print("Matrix B:\n", B)

# Menu

print("\nChoose Operation:")

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

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

# Perform operations

if choice == 1:

if [Link] == [Link]:

print("\nAddition Result:\n", A + B)

else:

print("\nAddition not possible. Matrices must have same dimensions.")

elif choice == 2:

if [Link] == [Link]:

print("\nSubtraction Result (A - B):\n", A - B)

else:
print("\nSubtraction not possible. Matrices must have same dimensions.")

elif choice == 3:

if c1 == r2:

print("\nMultiplication Result (A x B):\n", [Link](A, B))

else:

print("\nMultiplication not possible. Columns of A must equal rows of B.")

else:

print("\nInvalid choice!")

Output:

Enter number of rows for Matrix A: 2

Enter number of columns for Matrix A: 2

Enter number of rows for Matrix B: 2

Enter number of columns for Matrix B: 2

Enter elements of Matrix A:

Enter elements of Matrix B:

6
7

Matrix A:

[[1 2]

[3 4]]

Matrix B:

[[5 6]

[7 8]]

Choose Operation:

1. Addition

2. Subtraction

3. Multiplication

Enter your choice (1/2/3): 1

Addition Result:

[[ 6 8]

[10 12]]

c)Write a program to solve a system of n linear equations in n variables using matrix


inverse.

import numpy as np

# Input number of variables

n = int(input("Enter number of variables (n): "))


# Input coefficient matrix A

print("\nEnter coefficients of matrix A:")

A = [Link]([[float(input()) for j in range(n)] for i in range(n)])

# Input constant matrix B

print("\nEnter constants of matrix B:")

B = [Link]([[float(input())] for i in range(n)])

print("\nCoefficient Matrix A:\n", A)

print("Constant Matrix B:\n", B)

# Check if inverse exists

det = [Link](A)

if det != 0:

A_inv = [Link](A)

X = [Link](A_inv, B)

print("\nInverse of Matrix A:\n", A_inv)

print("\nSolution Matrix X:\n", X)

else:

print("\nMatrix A is singular. Inverse does not exist.")

Output:

Enter number of variables (n): 2


Enter coefficients of matrix A:

Enter constants of matrix B:

2
23. Import Plotpy and Scipy and explore their functionalities.
a) Finding if two sets of data have the same mean value.
import numpy as np
from scipy import stats
import plotly.graph_objects as go

# Two data sets


data1 = [Link]([12, 15, 14, 10, 13, 15, 14])
data2 = [Link]([11, 14, 13, 12, 14, 13, 12])

# Calculate means
mean1 = [Link](data1)
mean2 = [Link](data2)

print("Mean of Data Set 1:", mean1)


print("Mean of Data Set 2:", mean2)

# Independent t-test
t_stat, p_value = stats.ttest_ind(data1, data2)

print("\nT-statistic:", t_stat)
print("P-value:", p_value)

# Conclusion
if p_value > 0.05:
print("Conclusion: Both data sets have the same mean value.")
else:
print("Conclusion: The mean values are significantly different.")

# Plot using Plotly


fig = [Link]()
fig.add_trace([Link](y=data1, name="Data Set 1"))
fig.add_trace([Link](y=data2, name="Data Set 2"))

fig.update_layout(
title="Comparison of Two Data Sets",
yaxis_title="Values"
)

[Link]()
Output:

Mean of Data Set 1: 13.2857

Mean of Data Set 2: 12.7143

T-statistic: 1.02

P-value: 0.33

Conclusion: Both data sets have the same mean value.

b) Plotting data read from a file.


import numpy as np
import plotly.graph_objects as go

# Read data from file


data = [Link]("[Link]")

# Separate columns
x = data[:, 0]
y = data[:, 1]

# Create plot
fig = [Link]()

fig.add_trace([Link](
x=x,
y=y,
mode='lines+markers',
name='File Data'
))

# Layout settings
fig.update_layout(
title="Plot of Data Read from File",
xaxis_title="X values",
yaxis_title="Y values"
)

# Display plot
[Link]()
Output:
Data loaded successfully from [Link]

c) Fitting a function through a set a data points using polyfit function.


import numpy as np
import plotly.graph_objects as go

# Given data points


x = [Link]([1, 2, 3, 4, 5])
y = [Link]([2, 4, 5, 4, 5])

# Fit a polynomial of degree 2


coeff = [Link](x, y, 2)

# Create polynomial function


poly = np.poly1d(coeff)

# Fitted values
y_fit = poly(x)
# Display coefficients
print("Polynomial coefficients:", coeff)

# Plot data and fitted curve


fig = [Link]()

fig.add_trace([Link](
x=x, y=y, mode='markers', name='Original Data'
))

fig.add_trace([Link](
x=x, y=y_fit, mode='lines', name='Best Fit Curve'
))

fig.update_layout(
title="Curve Fitting using [Link]()",
xaxis_title="X",
yaxis_title="Y"
)
[Link]()
Output:
Polynomial coefficients: [-0.21428571 1.74285714 0.8]

d) Plotting a histogram of a given data set.

import numpy as np

import plotly.graph_objects as go

# Given data set

data = [12, 15, 14, 10, 13, 15, 14, 16, 18, 17, 15, 14]

# Create histogram

fig = [Link](data=[

[Link](
x=data,

nbinsx=6

])

# Layout settings

fig.update_layout(

title="Histogram of Given Data Set",

xaxis_title="Data Values",

yaxis_title="Frequency"

# Show plot

[Link]()

Output:
24. Write a Python file named geometry_module.py that acts as your module. This module
should contain classes for at least two different geometric shapes (like Rectangle and Circle).
Each class must have methods to calculate its area and perimeter. The module should also
include a standalone function, display_shape_info (), that takes a shape object as input and
prints its area and perimeter. In a separate Python file named lab_exercise.py, import your
geometry_module. In this file, create instances of the Rectangle and Circle classes from your
module. Then, call the display_shape_info () function on each of your shape instances to prove
that your module works as expected.

File 1: geometry_module.py

This file acts as a module and contains:

• Rectangle class
• Circle class
• display_shape_info() standalone function

# geometry_module.py

import math

class Rectangle:

def __init__(self, length, width):

[Link] = length

[Link] = width

def area(self):

return [Link] * [Link]

def perimeter(self):

return 2 * ([Link] + [Link])


class Circle:

def __init__(self, radius):

[Link] = radius

def area(self):

return [Link] * [Link] ** 2

def perimeter(self):

return 2 * [Link] * [Link]

def display_shape_info(shape):

print("Area:", [Link]())

print("Perimeter:", [Link]())

print("-" * 30)

File 2: lab_exercise.py

This file imports the module, creates objects, and tests the functionality.

# lab_exercise.py

import geometry_module as gm

# Create Rectangle object

rect = [Link](10, 5)
# Create Circle object

circle = [Link](7)

print("Rectangle Information:")

gm.display_shape_info(rect)

print("Circle Information:")

gm.display_shape_info(circle)

Output:

Rectangle Information:

Area: 50

Perimeter: 30

------------------------------

Circle Information:

Area: 153.93804002589985

Perimeter: 43.982297150257104

------------------------------
25. Write a Python program for a university case study that demonstrates the use of
general-purpose exceptions (try-except) while processing student data. The program
should accept basic student details such as name, roll number, and marks, and then
attempt to calculate the student’s average marks. While doing so, it must be able to handle
unexpected errors, including cases where data is missing or entered in an invalid format
(e.g., marks entered as text), errors like division by zero during average calculation, as
well as any other unforeseen exceptions that may occur during execution.

# University Case Study: Student Data Processing

# Demonstrates General-Purpose Exception Handling

def calculate_average(marks_list):

try:

if len(marks_list) == 0:

raise ZeroDivisionError("No subjects entered. Cannot calculate average.")

total = sum(marks_list)

average = total / len(marks_list)

return average

except ZeroDivisionError as zde:

print("Error:", zde)

return None

def main():
try:

print("----- Student Data Processing System -----")

# Accept Student Details

name = input("Enter Student Name: ").strip()

if not name:

raise ValueError("Name cannot be empty.")

roll_no = input("Enter Roll Number: ").strip()

if not roll_no:

raise ValueError("Roll number cannot be empty.")

num_subjects = int(input("Enter number of subjects: "))

if num_subjects <= 0:

raise ValueError("Number of subjects must be greater than zero.")

marks = []

# Accept Marks

for i in range(num_subjects):

mark = float(input(f"Enter marks for subject {i+1}: "))

if mark < 0 or mark > 100:

raise ValueError("Marks should be between 0 and 100.")


[Link](mark)

# Calculate Average

average = calculate_average(marks)

if average is not None:

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

print("Name :", name)

print("Roll No :", roll_no)

print("Marks :", marks)

print("Average :", round(average, 2))

except ValueError as ve:

print("Value Error:", ve)

except ZeroDivisionError as zde:

print("Division Error:", zde)

except Exception as e:

print("Unexpected Error Occurred:", e)

else:

print("\nData processed successfully!")


finally:

print("\nProgram execution completed.")

# Run Program

if __name__ == "__main__":

main()

Input: Case 1:

Enter Student Name: Rahul

Enter Roll Number: 101

Enter number of subjects: 3

Enter marks for subject 1: 80

Enter marks for subject 2: 75

Enter marks for subject 3: 90

Output:

Average : 81.67

Data processed successfully!

Program execution completed.

Input: Case 2:

Enter marks for subject 1: eighty

Output:

Value Error: could not convert string to float: 'eighty'

Program execution completed.


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

import turtle

# Define Rectangle class

class Rectangle:

def __init__(self, width, height, x=0, y=0):

[Link] = width

[Link] = height

self.x = x # Starting X position

self.y = y # Starting Y position

# Function to draw rectangle

def draw_rectangle(canvas, rect):

"""

Draws a rectangle on the given canvas using turtle

canvas -> [Link] object

rect -> Rectangle object

"""

[Link]()

[Link](rect.x, rect.y) # Move to starting position

[Link]()
# Draw rectangle

for _ in range(2):

[Link]([Link])

[Link](90)

[Link]([Link])

[Link](90)

# Main program

def main():

screen = [Link]()

[Link]("Rectangle Drawing")

pen = [Link]()

[Link](1)

# Create Rectangle object

rect1 = Rectangle(150, 100, -50, 50)

# Draw Rectangle

draw_rectangle(pen, rect1)

[Link]()
if __name__ == "__main__":

main()

Output:

----------------------

| |

| |

| |

| |

----------------------
27. Write a Python program to add an attribute named color to your Rectangle objects and
modify draw_rectangle so that it uses the color attribute as the fill color.

import turtle

# Rectangle class with color attribute

class Rectangle:

def __init__(self, width, height, x=0, y=0, color="black"):

[Link] = width

[Link] = height

self.x = x

self.y = y

[Link] = color # New attribute

# Modified draw function

def draw_rectangle(canvas, rect):

"""

Draws a colored rectangle using turtle

"""

[Link]()

[Link](rect.x, rect.y)

[Link]()
# Set fill color

[Link]([Link])

canvas.begin_fill() # Start filling

for _ in range(2):

[Link]([Link])

[Link](90)

[Link]([Link])

[Link](90)

canvas.end_fill() # Stop filling

# Main program

def main():

screen = [Link]()

[Link]("Colored Rectangle")

pen = [Link]()

[Link](1)

# Create rectangle objects with different colors

rect1 = Rectangle(150, 100, -100, 50, "red")


rect2 = Rectangle(120, 80, 50, -50, "blue")

# Draw rectangles

draw_rectangle(pen, rect1)

draw_rectangle(pen, rect2)

[Link]()

if __name__ == "__main__":

main()

Output:

███████████████████ (Red Rectangle)

█████████████

█████████████ (Blue Rectangle)


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

import turtle

# Define Point class

class Point:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

# Function to draw a point

def draw_point(canvas, point):

"""

Draws a point on the given canvas

canvas -> [Link] object

point -> Point object

"""

[Link]()

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

[Link]()

[Link](8) # Draw a dot of size 8


# Main Program

def main():

screen = [Link]()

[Link]("Drawing Points")

pen = [Link]()

[Link](1)

# Create Point objects

p1 = Point(0, 0)

p2 = Point(100, 50)

p3 = Point(-80, -40)

# Draw points

draw_point(pen, p1)

draw_point(pen, p2)

draw_point(pen, p3)

[Link]()

if __name__ == "__main__":

main()

Output:

• •
29. 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.

import turtle

# Define Circle class

class Circle:

def __init__(self, radius, x=0, y=0, color="black"):

[Link] = radius

self.x = x

self.y = y

[Link] = color

# Function to draw circle

def draw_circle(canvas, circle):

"""

Draws a filled circle on the given canvas

canvas -> [Link] object

circle -> Circle object

"""

[Link]()

# Move to starting point (adjust because turtle draws from edge)


[Link](circle.x, circle.y - [Link])

[Link]()

[Link]([Link])

canvas.begin_fill()

[Link]([Link])

canvas.end_fill()

# Main Program

def main():

screen = [Link]()

[Link]("Drawing Circles")

pen = [Link]()

[Link](1)

# Instantiate Circle objects

c1 = Circle(50, 0, 0, "red")

c2 = Circle(30, 100, 50, "blue")

c3 = Circle(40, -120, -60, "green")

# Draw circles
draw_circle(pen, c1)

draw_circle(pen, c2)

draw_circle(pen, c3)

[Link]()

if __name__ == "__main__":

main()

Output:

🔴 🟢
30. 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):

"""

Validates phone number:

- Must contain exactly 10 digits

- Digits only

"""

pattern = r"^[0-9]{10}$"

if [Link](pattern, phone):

return True

else:

return False

def validate_email(email):

"""

Validates email format:

Example: name123@[Link]

"""

pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"

if [Link](pattern, email):
return True

else:

return False

def main():

phone = input("Enter Phone Number: ")

email = input("Enter Email ID: ")

print("\n----- Validation Result -----")

if validate_phone(phone):

print("Phone Number is VALID ✅")

else:

print("Phone Number is INVALID ❌")

if validate_email(email):

print("Email ID is VALID ✅")

else:

print("Email ID is INVALID ❌")

if __name__ == "__main__":
main()

Input:

Enter Phone Number: 9876543210

Enter Email ID: student@[Link]

Output:

Phone Number is VALID ✅

Email ID is VALID ✅
31. Write a python code to merge two given file contents into a third file.

# Program to merge two files into a third file

def merge_files(file1, file2, output_file):

try:

# Open first file in read mode

with open(file1, 'r') as f1:

content1 = [Link]()

# Open second file in read mode

with open(file2, 'r') as f2:

content2 = [Link]()

# Open third file in write mode

with open(output_file, 'w') as f3:

[Link](content1)

[Link]("\n") # Optional: add newline between contents

[Link](content2)

print("Files merged successfully!")

except FileNotFoundError:

print("Error: One of the input files does not exist.")


except Exception as e:

print("An unexpected error occurred:", e)

# Main program

file1 = input("Enter first file name: ")

file2 = input("Enter second file name: ")

output_file = input("Enter output file name: ")

merge_files(file1, file2, output_file)

[Link]

Hello

Welcome to Python

[Link]
32. Write a python code to determine if two strings are anagrams, find the first non-repeating
character, and count character frequencies.

string = input("Enter a string: ")

frequency = {}

for ch in string:

if ch in frequency:

frequency[ch] += 1

else:

frequency[ch] = 1

print("Character Frequencies:")

for key, value in [Link]():

print(key, ":", value)


33. Write a Python code to read text from a text file, find the word with most number of
occurrences.

# Open the file in read mode

file = open("[Link]", "r")

# Read file content

text = [Link]().lower()

# Close the file

[Link]()

# Split text into words

words = [Link]()

# Dictionary to store word frequency

frequency = {}

for word in words:

if word in frequency:

frequency[word] += 1

else:

frequency[word] = 1

# Find word with maximum frequency


max_word = None

max_count = 0

for word, count in [Link]():

if count > max_count:

max_count = count

max_word = word

print("Word with maximum occurrences:", max_word)

print("Number of occurrences:", max_count)


34. Write a function that reads a file and displays the number of words, number of vowels,
blank spaces, lower case letters and uppercase letters.

def analyze_file(filename):

# Initialize counters

word_count = 0

vowel_count = 0

space_count = 0

lower_count = 0

upper_count = 0

vowels = "aeiouAEIOU"

# Open file and read content

with open(filename, "r") as file:

text = [Link]()

# Count words

words = [Link]()

word_count = len(words)

# Analyze each character

for ch in text:

if ch in vowels:
vowel_count += 1

if ch == " ":

space_count += 1

if [Link]():

lower_count += 1

if [Link]():

upper_count += 1

# Display results

print("Number of words:", word_count)

print("Number of vowels:", vowel_count)

print("Number of blank spaces:", space_count)

print("Number of lowercase letters:", lower_count)

print("Number of uppercase letters:", upper_count)

# Function call

analyze_file("[Link]")

Input:

Hello World

Python Is Easy

Output:

Number of words: 5
Number of vowels: 7

Number of blank spaces: 3

Number of lowercase letters: 12

Number of uppercase letters: 4


35. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR.

# AND Gate

def AND(a, b):

return a and b

# OR Gate

def OR(a, b):

return a or b

# NOT Gate

def NOT(a):

return not a

# EX-OR (XOR) Gate

def XOR(a, b):

return a ^ b

# Taking inputs (0 or 1)

a = int(input("Enter first input (0 or 1): "))

b = int(input("Enter second input (0 or 1): "))

print("AND Gate:", AND(a, b))

print("OR Gate:", OR(a, b))


print("NOT Gate (a):", NOT(a))

print("XOR Gate:", XOR(a, b))

Output:

Enter first input (0 or 1): 1

Enter second input (0 or 1): 0

AND Gate: 0

OR Gate: 1

NOT Gate (a): False

XOR Gate: 1

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

from tkinter import messagebox

# Create main window

window = [Link]()

[Link]("Window Wizard")

[Link]("350x250")

# Function for Submit button

def submit_data():

name = [Link]()

age = [Link]()
[Link]("Submitted Data",

f"Name: {name}\nAge: {age}")

# Function for Reset button

def reset_data():

[Link](0, [Link])

[Link](0, [Link])

# Labels

label1 = [Link](window, text="Name:")

[Link](pady=5)

entry1 = [Link](window)

[Link](pady=5)

label2 = [Link](window, text="Age:")

[Link](pady=5)

entry2 = [Link](window)

[Link](pady=5)

# Buttons

submit_btn = [Link](window, text="Submit", command=submit_data)

submit_btn.pack(pady=5)
reset_btn = [Link](window, text="Reset", command=reset_data)

reset_btn.pack(pady=5)

# Run the window

[Link]()

You might also like