0% found this document useful (0 votes)
16 views88 pages

Final Record I Guess

The document outlines the laboratory manual for the GE3171 - Problem Solving and Python Programming course at Jaya Sakthi Engineering College. It includes a bonafide certificate section, a list of experiments, and detailed Python programs for various applications such as electricity billing, retail shop billing, and calculations involving sine series and weight of objects. Each program includes aims, algorithms, flowcharts, and sample outputs.

Uploaded by

lithish55555
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)
16 views88 pages

Final Record I Guess

The document outlines the laboratory manual for the GE3171 - Problem Solving and Python Programming course at Jaya Sakthi Engineering College. It includes a bonafide certificate section, a list of experiments, and detailed Python programs for various applications such as electricity billing, retail shop billing, and calculations involving sine series and weight of objects. Each program includes aims, algorithms, flowcharts, and sample outputs.

Uploaded by

lithish55555
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
You are on page 1/ 88

ANNA UNIVERSITY

JAYA SAKTHI ENGINEERING COLLEGE

STMARY'S NAGAR,THIRUNINRAVUR-602024

EMAIL: [email protected]
WEBSITE: WWW.SAKTHIEC.EDU.IN

GE3171-PROBLEMSOLVING AND PYTHON PROGRAMMING


LABORATORY

I YEAR/I SEMESTER

NAME :

REGISTER NO :

DEPARTMENT :
ANNA UNIVERSITY
JAYA SAKTHI ENGINEERING COLLEGE
THIRUNINRAVUR - 602024

(AN ISO 9001:2000 CERTIFIED INSTITUTION)

EMAIL : [email protected]

WEBSITE : WWW.SAKTHIEC.EDU.IN

BONAFIDE CERTIFICATE

NAME : REGISTER NO :
BRANCH : YEAR/SEM:

This is certified to be a Bonafide record of work done by the student in the GE3171- Problem
Solving And Python Programming Laboratory of the Jaya Sakthi Engineering College during
.

Head of the Department Signature of Faculty In-charge


Submitted for the Practical Examination to be held on .

Internal Examiner External Examiner


LIST OF EXPERIMENTS

S.NO. DATE NAMEOFTHEPROGRAM PAGE NO. Mark Sign.

1 Identification and solving of simple real life or scientific or technical problems, and developing

1a Electricity Billing

1b Retail shop billing

1c Sin series

1d Weight of a motorbike

1e Weight of a steel bar

1f Compute Electrical Currenting Three Phase AC Circuit

2 Python programming using simple statements and expressions

2a Exchange the values of two variables

2b Circulate the values of n variables

2c Distance between two points

3 Scientific problem suing Conditional sand Iterative loops.

3a Number series

3b Number Patterns

3c Pyramid pattern of star

3d Pyramid pattern of number

4 Implementing real-time/technical applications using Lists , Tuples

4a(i) Components of car using List

4a(ii) Components of car using Tuple

4b(i) Materials required for construction of a building using List

4b(ii) Materials required for construction of a building using Tuple

4c(i) Items present in a library using List

4c(ii) Items present in a library using Tuple

5 Implementing real-time/technical applications using Sets , Dictionaries.

5a(i) Application Language using sets

5a(ii) Application Language using Dictionaries


5b(i) Components of an auto mobile using sets
5b(ii) Components of an auto mobile using Dictionaries

5c(i) Elements of a civil structure using Sets


5c(ii) Elements of a civil structure using Dictionaries

6 Implementing programs using Functions.


6a Factorial of given number
6b Implementing two Largest number in a list
6c Area of shape
7 Implementing programs using Strings
7a Reverse string program
7b Implementing Palindrome program
7c Implementing character count program
7d Implementing Replacing characters program
8 Implementing programs using written modules and Python Standard
Libraries

8a Implementing Pandas program


8b Implementing NumPy program
8c Implementing Matplotlib program
8d Implementing SciPy program
9 Implementing real-time/technical applications using File handling
9a Implementing copy from one file to another
9b Implementing word count program
9c Implementing longest word program
10 Implementingreal-time/technicalapplicationsusingExceptionhandling
10a Implementing divide by zero error program

10b Implementing voter’s age validity program


10c Implementing student mark range validation
program

11 Exploring PyGame tool


12 Developing aga me activity using Pygame like
bouncing ball, car race etc
1. PROGRAMS USING, I/O STATEMENTS AND EXPRESSIONS.

1a) Electricity Billing

AIM:
To write a Python Program for implementing electricity billing

ALGORITHM:
1. Start the program.
2. Get the total units of current consumed by the customer using the
variable unit.
3. If the unit consumed less or equal to 100 units, Total amount is 0
4. If the unit consumed between 101 to 200 units, Total amount =
((101*1.5)+(unit-100)*2)
5. If the unit consumed between 201 to 500 units, Total amount =
((101*1.5)+(200-100)*2+(unit-200)*3)
6. If the unit consumed 300 to 350, Total amount = ((101*1.5)+(200-
100)*2+(300-200)*4.6+(unit-350)*5)
7. If the unit consumed above 350, fixed charge – 1500
8. Stop the program
FLOWCHART:
PROGRAM:

# Electricity billing
# Input the number of units consumed
unit = int(input("Enter the number of units: "))
# Rate structure
rates = [
[0], # Placeholder for 0 units
[0, 1.5], # Rates for 1-100 units
[0, 2.5, 3.5], # Rates for 101-200 and 201-500 units
[0, 3.5, 4.6, 6.6] # Rates for 501+ units
]
# Initialize bill
bill = 0
# Calculate the bill based on the number of units consumed
if unit >= 0 and unit <= 100:
bill = unit * rates[1][1]
elif unit <= 200:
bill = (100 * rates[1][1]) + (unit - 100) * rates[2][1]
elif unit <= 500:
bill = (100 * rates[1][1]) + (100 * rates[2][1]) + (unit - 200) * rates[2][2]
else:
bill = (100 * rates[1][1]) + (100 * rates[2][1]) + (300 * rates[2][2]) + (unit -
500) * rates[3][3]
# Print the results
print("Units consumed:", unit)
print("Bill: Rs", bill)

OUTPUT:

Enter the number of units: 10


Units consumed: 10
Bill: Rs 15.0

RESULT:
Thus, a Python Program for calculating electricity bill was executed and
the output was obtained.
1b) Retail Shop Billing

AIM:
To write a Python Program for implementing retail shop billing

ALGORITHM:
1. Start the program.
2. Assign tax =0.5
3. Assign rate for Shirt, Saree, T-shirt, Trackpant
4. Get the quantity of items from the user
5. Calculate total cost by multiplying rate and quantity of the items
6. Add tax value with the total cost and display the bill amount
7. Stop the program
FLOWCHART:
PROGRAM:
# Retail Shop Billing Tax
tax = 0.5
Rate = {"Shirt": 250, "Saree": 650, "T-Shirt": 150, "Trackpant": 150}
print("Retail Bill Calculator\n")
# Input quantities
Shirt = int(input("Shirt: "))
Saree = int(input("Saree: "))
TShirt = int(input("T-Shirt: "))
Trackpant = int(input("Trackpant: "))
# Calculate cost
Cost = (Shirt * Rate["Shirt"] +
Saree * Rate["Saree"] +
TShirt * Rate["T-Shirt"] +
Trackpant * Rate["Trackpant"])
# Calculate total bill including tax
Bill = Cost + Cost * tax
# Print the total bill
print("Please pay Rs. %.2f" % Bill)

OUTPUT:

Retail Bill Calculator

Shirt: 1
Saree: 1
T-Shirt: 2
Trackpant: 3
Please pay Rs. 2475.00

RESULT:
Thus, a Python Program for calculating retail bill was executed and the
output was obtained.
1c) Weight of a Steel Bar

AIM:
To write a Python Program to find unit weight of steel bars.

ALGORITHM:
1. Start the program.
2. Read D, Diameter of the steel bars.
3. Calculate W = D*D/162.
4. Print W, unit weight of the steel bars in kg/m
5. Stop.

FLOWCHART:
PROGRAM:

# UNIT WEIGHT OF STEEL BARS

D=float(input("Enter Diameter of steel bars in mm:") )


W=D*D/162
print("Unit Weight of the steel bar is {:.4f} kg/m ".format(W))

OUTPUT:

Enter Diameter of steel bars in mm:20


Unit Weight of the steel bar is 2.4691 kg/m

RESULT:

Thus, a Python Program for calculating unit weight of steel bars was
executed and the output was obtained.
1d) Weight of a Motorbike

AIM:
To write a Python Program to find weight of motorbike.

ALGORITHM:

1. Start the program


2. Constant price of the motorbike Mb,Mb1
3. Get values of num & num1
4. Total weight ← num*Mb +num1*Mb1
5. Display Total weight
6. Stop the program

FLOWCHART:
PROGRAM:
# WEIGHT OF MOTORBIKE

Mb1 = 30000 # Weight of Motorbike 1 in grams


Mb2 = 40000 # Weight of Motorbike 2 in grams

print("Enter your order items:")


num = int(input("Number of Motorbike 1: ")) # Fixed typo in "Motorbike"
num1 = int(input("Number of Motorbike 2: ")) # Fixed typo in "Motorbike"

# Calculate total weight


total_weight = num * Mb1 + num1 * Mb2

# Print the total weight


print("Your order total weight is:", total_weight, "gm")

OUTPUT:

Enter your order items:


Number of Motorbike 1: 13
Number of Motorbike 2: 24
Your order total weight is: 1350000 gm

RESULT:

Thus, a Python Program for calculating weight of motorbike was


executed and the output was obtained.
1e) ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT

AIM:
To write a Python Program to compute Electrical Current in Three Phase AC
Circuit.
ALGORITHM:

1. Start the program.


2. Read P, power in kw, V voltage in volts and PF power factor.
3. Calculate I=P /(V*PF).
4. Print I Current in amperes.
5. Stop.

FLOWCHART:

START

Read Power, Voltage, Power


factor

Calculate Current = P/(V*PF)

STOP
PROGRAM:

# ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT

# Input values

P = int(input("Enter Power in kW: ")) # Power in kilowatts

V = int(input("Enter Voltage in volts: ")) # Voltage in volts

PF = float(input("Enter Power Factor: ")) # Power factor

# Calculate current

I = P / (V * PF)

# Print the electrical current

print("Electrical Current in 3 phase AC circuit is {:.2f} ampere".format(I))

OUTPUT:

Enter Power in kW: 10


Enter Voltage in volts: 12
Enter Power Factor: 12.5
Electrical Current in 3 phase AC circuit is 0.07 ampere

RESULT:

Thus, a Python Program to compute Electrical Current in Three Phase


AC Circuit was executed and the output was obtained.
1 f) Sine Series

AIM:

To write a Python Program to compute sine series

ALGORITHM:

1. Start
2. Initialize double sum=0,x,i,j,y,z=1,a,f=1,k=1;
3. Enter x.
4. read x.
5. repeat steps 6 to 11 for(i=1 to i<=x)
6. set j=z=1
7. repeat steps 8 while(j<=i)
8. set z=z*i;
9. j=j+1;
10. repeat steps 10 while(k<=i).

FLOWCHART:
PROGRAM:

import math
def sine_series(x, n):
# Convert x from degrees to radians
x = math.radians(x)
# Initialize sine value
sine_value = 0
# Calculate sine series
for i in range(n):
# Calculate the term using the Taylor series formula
term = ((-1) ** i) * (x ** (2 * i + 1)) / math.factorial(2 * i + 1)
sine_value += term
return sine_value
# Input values
n = int(input("Enter the number of terms in the series: ")) # Number of terms
x = float(input("Enter the angle in degrees: ")) # Angle in degrees
# Calculate sine using the series
result = sine_series(x, n)
# Print the result
print("The sine of {} degrees using {} terms is {:.5f}".format(x, n, result))

OUTPUT:

Enter the number of terms in the series: 1

Enter the angle in degrees: 12

The sine of 12.0 degrees using 1 terms is 0.20944

RESULT:

Thus, a Python Program to compute sine series was executed and the
output was obtained.
PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
2 a) SWAPPING OF TWO NUMBERS USING TEMPORARY VARIABLE

AIM:

To write a Python Program to swap two numbers using a temporary variable.


ALGORITHM:

1. Start the program.


2. Read the first number X.
3. Display the values X,Y before swapping.
4. Assign X to Temp.
5. Assign Y to X.
6. Assign Temp to Y.
7. Display the values X,Y after swapping.
8. Stop.

FLOWCHART:

START

Declare a,b, and c

Read a and b

c=a
a=b
b=c

Print a and b

STOP
PROGRAM:

# SWAPPING OF TWO NUMBERS USING TEMPORARY VARIABLE

# Input values

X = int(input("Enter the value of X: "))

Y = int(input("Enter the value of Y: "))

# Display values before swapping

print("Before Swapping")

print("X =", X, "Y =", Y)

# Swapping using a temporary variable

Temp = X

X=Y

Y = Temp

# Display values after swapping

print("After Swapping")

print("X =", X, "Y =", Y)

OUTPUT:

Enter the value of X: 13


Enter the value of Y: 4
Before Swapping
X = 13 Y = 4
After Swapping
X = 4 Y = 13
RESULT:

Thus, a Python Program to swap two numbers using a temporary


variable was executed and the output was obtained.
2 b) SWAPPING OF TWO NUMBERS WITHOUT USING TEMPORARY
VARIABLE

AIM:
To write a Python Program to swap two numbers without using a temporary
variable.
ALGORITHM:

1. Start the program.


2. Read the first number X.
3. Display the values X,Y before swapping.
4. Compute X=X+Y.
5. Compute Y=X-Y.
6. Compute X=X-Y.
7. Display the values X,Y after swapping.
8. Stop.

FLOWCHART:
PROGRAM:

# SWAPPING OF TWO NUMBERS WITHOUT USING TEMPORARY


VARIABLE

# Input values

X = int(input("Enter the value of X: "))

Y = int(input("Enter the value of Y: "))

# Display values before swapping

print("Before Swapping")

print("X =", X, "Y =", Y)

# Swapping without using a temporary variable

X=X+Y

Y=X-Y

X=X-Y

# Display values after swapping

print("After Swapping")

print("X =", X, "Y =", Y)

OUTPUT:

Enter the value of X: 12


Enter the value of Y: 32
Before Swapping
X = 12 Y = 32
After Swapping
X = 32 Y = 12
RESULT:

Thus, a Python Program to swap two numbers without using a


temporary variable was executed and the output was obtained.
2 c) SWAPPING OF TWO NUMBERS USING TUPLE ASSIGNMENT

AIM:
To write a Python Program to swap two numbers using Tuple Assignment.
ALGORITHM:

1. Start the program.


2. Read the first number X.
3. Display the values X,Y before swapping.
4. Compute X,Y=Y,X.
5. Display the values X,Y after swapping.
6. Stop.

PROGRAM:
# SWAPPING OF TWO NUMBERS USING TUPLE ASSIGNMENT
X=int(input("Enter the value of X:") )
Y=int(input("Enter the value of Y:") )

print("Before Swapping ")


print("X=",X,"Y=",Y)

X,Y=Y,X

print("After Swapping ")


print("X=",X,"Y=",Y)

OUTPUT:
Enter the value of X:1
Enter the value of Y:2
Before Swapping
X= 1 Y= 2
After Swapping
X= 2 Y= 1

RESULT:
Thus, a Python Program to swap two numbers using tuple assignment
was executed and the output was obtained.
2 d) DISTANCE BETWEN TWO POINTS

AIM:
To write a Python Program to calculate distance between two points.
ALGORITHM:

1. Start the program.


2. Import module math.
3. Read X1 the distance of the point1 in X axis from origin.
4. Read Y2 the distance of the point1 in Y axis from origin.
5. Read X2 the distance of the point2 in X axis from origin
6. Read Y2 the distance of the point2 in Y axis from origin.
7. Compute distance = math.sqrt ( (X2 - X1)**2 +(Y2 - Y1)**2 ).
8. Display the value of distance.
9. Stop.

FLOWCHART:
PROGRAM:

# DISTANCE BETWEN TWO POINTS


import math
X1=float(input("Enter the value of X1:") )
Y1=float(input("Enter the value of Y1:") )

X2=float(input("Enter the value of X2:") )


Y2=float(input("Enter the value of Y2:") )

distance = math.sqrt ( (X2 - X1)**2 +(Y2 - Y1)**2 )

print("Distance is {:.4f}".format(distance))

OUTPUT:
Enter the value of X1:2
Enter the value of Y1:3
Enter the value of X2:4
Enter the value of Y2:5
Distance is 2.8284

RESULT:

Thus, a Python Program to calculate distance between two points.


2 e) DISTANCE BETWEN TWO POINTS USING LIST

AIM:
To write a Python Program to calculate distance between two points using
list.

ALGORITHM:

1. Start the program.


2. Assign values to P1as list data type.
3. Assign vales to P2 as list data type.
4. Compute distance = ( (P2[0] - P1[0])**2 +(P2[1] - P1[1])**2 )**0.5.
5. Display the value of distance.
8. Stop.

PROGRAM:

# DISTANCE BETWEEN TWO POINTS

P1 = [2.0, 3.0] # Define point P1

P2 = [4.0, 5.0] # Define point P2

# Calculate the distance between P1 and P2

distance = ((P2[0] - P1[0]) ** 2 + (P2[1] - P1[1]) ** 2) ** 0.5

# Print the distance

print("Distance is {:.4f}".format(distance))

OUTPUT:

Distance is 2.8284

RESULT:
Thus, a Python Program to calculate the distance between two points
using list was executed and the output was obtained.
2 f) CIRCULATE THE VALUES OF N VARIABLES

AIM:
To write a Python Program to circulate the values of N variables.

ALGORITHM:

1. Start the program


2. Read the value of n
3. Circulate the values using slice operator
4. Print the values
5. Stop the program

FLOWCHART:
PROGRAM:

def circulate(A, N):

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

B = A[i:] + A[:i]

print("Circulation", i, "=", B)

# Main code

A = [91, 92, 93, 94, 95]

N = int(input("Enter n: ")) # Prompt for user input

circulate(A, N) # Call the circulate function

OUTPUT:

Enter n: 13

Circulation 1 = [92, 93, 94, 95, 91]


Circulation 2 = [93, 94, 95, 91, 92]
Circulation 3 = [94, 95, 91, 92, 93]
Circulation 4 = [95, 91, 92, 93, 94]
Circulation 5 = [91, 92, 93, 94, 95]
Circulation 6 = [91, 92, 93, 94, 95]
Circulation 7 = [91, 92, 93, 94, 95]
Circulation 8 = [91, 92, 93, 94, 95]
Circulation 9 = [91, 92, 93, 94, 95]
Circulation 10 = [91, 92, 93, 94, 95]
Circulation 11 = [91, 92, 93, 94, 95]
Circulation 12 = [91, 92, 93, 94, 95]
Circulation 13 = [91, 92, 93, 94, 95]

RESULT:

Thus, a Python Program to circulate the number was executed and the
output was obtained.
3. SCIENTIFIC PROBLEMS USING CONDITIONALS AND
ITERATIVE LOOPS

3a) NUMBER SERIES


AIM:
To write a Python Program to calculate 12+22+32+……+N2.

ALGORITHM:

1. Start the program


2. Read the value of N.
3. Calculate sum of number series (12+22+32+……+N2) using while
condition
4. Print the value
5. Stop the program

FLOWCHART:
PROGRAM:

# Input a number

N = int(input("Enter a number: ")) # Changed curly quotes to straight quotes

Sum = 0 # Initialize sum

i=1 # Initialize counter

# Calculate the sum of squares

while i <= N:

Sum = Sum + i * i # Add the square of i to Sum

i += 1 # Increment i

# Print the result

print("Sum =", Sum) # Changed curly quotes to straight quotes

OUTPUT:

Enter a number : 10
Sum = 385

RESULT:
Thus, a Python Program to calculate number series was executed and
the output was obtained.
3b) NUMBER PATTERNS

AIM:

To write a Python Program to print odd number pattern of the given number
of terms.
ALGORITHM:

1: Start the program


2: Input N
3: print the pattern using loops
4: Stop

FLOWCHART:
PROGRAM:

# Input the number of lines


N = int(input("Enter number of Lines: "))

print("Number Triangle:")

# Loop to print the number triangle


for i in range(1, N + 1):
# Print the number 'i', 'i' times
for j in range(i):
print(i, end=" ")
print() # Move to the next line after each row

OUTPUT:

Enter number of Lines: 5


Number Triangle:
1
22
333
4444
55555

RESULT:

Thus, a Python Program to print number pattern was executed and the
output was obtained.
3C) PYRAMID PATTERN

AIM:

To write a Python Program to print pyramid pattern of the given number of


lines.

ALGORITHM:

1: Start the program


2: Read the number of rows to print from user
3: Print the pyramid pattern using for loops
4: Stop the program
FLOWCHART:
PROGRAM:

# Function to print full pyramid pattern

def full_pyramid(n):

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

# Print leading spaces

for j in range(n - i):

print(" ", end="")

# Print asterisks for the current row

for k in range(1, 2 * i):

print("*", end="")

print() # Move to the next line after each row

# Set the number of rows for the pyramid

num_rows = int(input("Enter the number of rows for the pyramid: "))

full_pyramid(num_rows)

OUTPUT:

Enter the number of rows for the pyramid: 5

*
***
*****
*******
*********
RESULT:
Thus, a Python Program to print pyramid pattern was executed and the
output was obtained.
4. REAL TIME/ TECHNICAL APPLICATIONS USING LISTS,
TUPLES

4a) COMPONENTS OF A CAR

.
AIM:

To write a python programming to perform operations on list

ALGORITHM:

1. Start
2. Perform update operation (Insert , Delete, modify, slice) on List object
3. Display the outputs
4. Stop.

PROGRAM:

carparts = ['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']

print("Original car parts:", carparts)

print("First part:", carparts[0])

print("Second part:", carparts[1])

print("Index of 'Wheel':", carparts.index('Wheel'))

print("Number of car parts:", len(carparts))

carparts.append('Headlights')

print("After adding 'Headlights':", carparts)

carparts.insert(2, 'Radiator')

print("After inserting 'Radiator' at index 2:", carparts)

carparts.remove('Headlights')

print("After removing 'Headlights':", carparts)

carparts.pop(2)
print("After popping the part at index 2:", carparts)

carparts[2] = 'Tyre'

print("After replacing index 2 with 'Tyre':", carparts)

carparts.sort()

print("After sorting:", carparts)

carparts.reverse()

print("Reversed list:", carparts)

New = carparts[:]

print("Copy of car parts:", New)

x = slice(2)

print("First two car parts using slice:", carparts[x])

test_list1 = [1, 4, 5, 6, 5]

test_list2 = [3, 5, 7, 2, 5]

for i in test_list2:

test_list1.append(i)

print("Concatenated list using naive method:", str(test_list1))

OUTPUT:

Original car parts: ['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']


First part: Engine
Second part: Transmission
Index of 'Wheel': 2
Number of car parts: 6
After adding 'Headlights': ['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake',
'Battery', 'Headlights']
After inserting 'Radiator' at index 2: ['Engine', 'Transmission', 'Radiator', 'Wheel',
'Gear', 'Brake', 'Battery', 'Headlights']
After removing 'Headlights': ['Engine', 'Transmission', 'Radiator', 'Wheel', 'Gear',
'Brake', 'Battery']
After popping the part at index 2: ['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake',
'Battery']
After replacing index 2 with 'Tyre': ['Engine', 'Transmission', 'Tyre', 'Gear', 'Brake',
'Battery']
After sorting: ['Battery', 'Brake', 'Engine', 'Gear', 'Transmission', 'Tyre']
Reversed list: ['Tyre', 'Transmission', 'Gear', 'Engine', 'Brake', 'Battery']
Copy of car parts: ['Tyre', 'Transmission', 'Gear', 'Engine', 'Brake', 'Battery']
First two car parts using slice: ['Tyre', 'Transmission']
Concatenated list using naive method: [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]

RESULT:

Thus, a Python Program to perform List operation was executed and the
output was verified.
4b) Building Materials
.
AIM:

To write a python programming to perform operations on list

ALGORITHM:

1. Start
2. Perform update operation (Insert , Delete, modify, slice) on List object
3. Display the outputs
4. Stop.

PROGRAM:

# List of building materials


Building_materials = ['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint']

# Print the original list of building materials


print("Building Materials:", Building_materials)

# Access and print specific elements


print("First Material:", Building_materials[0])
print("Fourth Material:", Building_materials[3])
print("Items in Building Materials from 0 to 4 index:", Building_materials[0:5])

# Append a new item to the list


item = input("Enter the Item to be appended: ")
Building_materials.append(item)
print("Building Materials after append():", Building_materials)

# Find the index of an item


item = input("Enter the Item to find index position: ")
print("Index position of {} is {}".format(item, Building_materials.index(item)))

# Sort the list of building materials


Building_materials.sort()
print("After sorting:", Building_materials)

# Pop the last element from the list


popped_item = Building_materials.pop()
print("Popped element is:", popped_item)
print("After deleting last element:", Building_materials)
# Remove a specific item from the list
item = input("Enter the Item to be deleted: ")
Building_materials.remove(item)
print("After removing:", Building_materials)

# Insert a new item at a specific index


item = input("Enter the Item to be inserted: ")
index = int(input("Enter the index where the Item to be inserted: "))
Building_materials.insert(index, item)
print("Building Materials after insert:", Building_materials

OUTPUT:

Building Materials: ['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint']


First Material: Cement
Fourth Material: Steel rod
Items in Building Materials from 0 to 4 index: ['Cement', 'Bricks', 'Sand', 'Steel
rod', 'Paint']
Enter the Item to be appended: 2
Building Materials after append(): ['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint', '2']
Enter the Item to find index position: 2
Index position of 2 is 5
After sorting: ['2', 'Bricks', 'Cement', 'Paint', 'Sand', 'Steel rod']
Popped element is: Steel rod
After deleting last element: ['2', 'Bricks', 'Cement', 'Paint', 'Sand']
Enter the Item to be deleted: 2
After removing: ['Bricks', 'Cement', 'Paint', 'Sand']
Enter the Item to be inserted: 2
Enter the index where the Item to be inserted: 2
Building Materials after insert: ['Bricks', 'Cement', '2', 'Paint', 'Sand']

RESULT:

Thus, a Python Program to perform List operation was executed and the
output was verified.
5. REAL TIME/ TECHNICAL APPLICATIONS USING SETS,
DICTIONARIES

5a). DICTIONARY OPERATIONS


AIM:

To write a python Program to perform Dictionary operations Insert, Delete, Modify


using built-in methods.

ALGORITHM:

1. Start
2. Perform update operation (Insert, Delete, modify) on Dictionary
operations
3. Display the outputs
4. Stop.

PROGRAM:
# Dictionary of building materials
Building_materials = {
1: "Cement",
2: "Bricks",
3: "Sand",
4: "Steel rod",
5: "Paint"
}

# Print the original dictionary of building materials


print("Building Materials:", Building_materials)

# Display using items() method


print("Display using items() method:")
print(Building_materials.items())

# Print dictionary keys and values


print("Dictionary keys:")
print(Building_materials.keys())
print("Dictionary values:")
print(Building_materials.values())

# Append a new item to the dictionary


item = input("Enter the Item to be appended: ")
Building_materials[6] = item
print("After appending:", Building_materials.items())
# Deleting Elements
index = int(input("Enter the key of the item to be deleted: "))
Building_materials.pop(index)
print("After removing:", Building_materials)

# Clear the entire content of the dictionary


Building_materials.clear()
print("After clearing the dictionary:", Building_materials)

# Delete the dictionary


del Building_materials

# Attempting to print the deleted dictionary will raise an error


try:
print(Building_materials)
except NameError:
print("Building_materials has been deleted.")

OUTPUT:

Building Materials: {1: 'Cement', 2: 'Bricks', 3: 'Sand', 4: 'Steel rod', 5: 'Paint'}


Display using items() method:
dict_items([(1, 'Cement'), (2, 'Bricks'), (3, 'Sand'), (4, 'Steel rod'), (5, 'Paint')])
Dictionary keys:
dict_keys([1, 2, 3, 4, 5])
Dictionary values:
dict_values(['Cement', 'Bricks', 'Sand', 'Steel rod', 'Paint'])
Enter the Item to be appended: 2
After appending: dict_items([(1, 'Cement'), (2, 'Bricks'), (3, 'Sand'), (4, 'Steel rod'),
(5, 'Paint'), (6, '2')])
Enter the key of the item to be deleted: 3
After removing: {1: 'Cement', 2: 'Bricks', 4: 'Steel rod', 5: 'Paint', 6: '2'}
After clearing the dictionary: {}
Building_materials has been deleted.

RESULT:

Thus, a Python Program to perform Dictionary operation was executed


and the output was verified.
5b). DICTIONARY OPERATIONS

AIM:

To write a python Program to perform Dictionary operations Insert, Delete, Modify


using built-in methods.

ALGORITHM:

1. Start
2. Perform update operation (Insert, Delete, modify) on Dictionary
operations.
3. Display the outputs
4. Stop.

PROGRAM:

# Define the sets


components1 = {'Engine', 'Chassis', 'Transmission'}
components2 = {'Steering', 'Tyre', 'Engine'}

# Print the original sets


print("Components 1:", components1)
print("Components 2:", components2)

# Add a new component to components1


components1.add('Gearbox')
print("After adding 'Gearbox' to components1:", components1)

# Remove the component 'Gearbox' from components1


components1.remove('Gearbox')
print("After removing 'Gearbox' from components1:", components1)

# Union of components1 and components2


print("Union of components1 and components2:", components1 | components2)
# Union using the union() method
print("Union using union() method:", components2.union(components1))

# Intersection of components1 and components2


print("Intersection of components1 and components2:", components1 &
components2)

# Intersection using the intersection() method


print("Intersection using intersection() method:",
components1.intersection(components2))

# Difference of components1 from components2


print("Difference (components1 - components2):", components1 - components2)

# Difference of components2 from components1


print("Difference (components2 - components1):",
components2.difference(components1))

# Symmetric difference between components1 and components2


print("Symmetric Difference:", components1 ^ components2)
OUTPUT:

Components 1: {'Chassis', 'Engine', 'Transmission'}


Components 2: {'Tyre', 'Steering', 'Engine'}
After adding 'Gearbox' to components1: {'Chassis', 'Engine', 'Gearbox',
'Transmission'}
After removing 'Gearbox' from components1: {'Chassis', 'Engine', 'Transmission'}
Union of components1 and components2: {'Chassis', 'Tyre', 'Steering',
'Transmission', 'Engine'}
Union using union() method: {'Tyre', 'Steering', 'Chassis', 'Transmission', 'Engine'}
Intersection of components1 and components2: {'Engine'}
Intersection using intersection() method: {'Engine'}
Difference (components1 - components2): {'Chassis', 'Transmission'}
Difference (components2 - components1): {'Tyre', 'Steering'}
Symmetric Difference: {'Tyre', 'Steering', 'Transmission', 'Chassis'}

RESULT:
Thus, a Python Program to perform Dictionary operation was executed
and the output was verified.
6. IMPLEMENTING PROGRAMS USING FUNCTION

6 a) FACTORIAL OF A NUMBER

AIM:

To write a Python Program to find the factorial of the given number using
functions.

ALGORITHM:

1: Start
2: Input N
3: Initialize F=1
4: Repeat until I= 1 to N
5: Calculate F=F*I
6: print F
7: Stop
PROGRAM:

# FACTORIAL OF A NUMBER
def Fact(N):
F=1
if N == 0 or N == 1: # Handle the case for 0 as well
return 1
else:
return N * Fact(N - 1)

# Input from the user


N = int(input("Enter a number: "))
print("Factorial of {} is {}".format(N, Fact(N)))

OUTPUT:

Enter a number:6

Factorial of 6 is 720

RESULT:
Thus, a Python Program to find the factorial of the given number using
functions was executed and the output was obtained.
6b) AREA OF SHAPE

AIM:

To write a Python Program to find the area of the shape using functions

ALGORITHM:

1: Start
2: Input shape of the area
3: call the function to calculate area of shape
4: print area
5: Stop

PROGRAM:
# AREA OF SHAPE
def calculate_area(name): if
name == "rectangle":
a = int(input("Enter rectangle length: "))
b = int(input("Enter rectangle breadth: ")) area =
a*b
print("The area of rectangle is:", area) elif
name == "square":
s = int(input("Enter length of side: ")) area = s
*s
print("The area of square is:", area) elif
name == "circle":
r = float(input("Enter radius: ")) pi =
3.14
area = pi * r * r
print("The area of circle is:", area) else:
print("Invalid shape!") # Handle invalid shape input

# Main program print("Calculate


Area of Shape")
shape = input("Enter the shape (rectangle/square/circle): ").lower() #
Convert input to lowercase
calculate_area(shape) # Call the function with the shape
OUTPUT:

enter the shape rectangle/square/circle : circle


Enter radius : 3.4
The area of square is 36.2984

RESULT:
Thus, a Python Program to calculate area of shape was executed and
the output was obtained.
6c) FINDING LARGEST NUMBER IN A LIST

AIM:

To write a Python Program to find the largest number in a list.

ALGORITHM:

1: Start
2: Read number of elements from user
3: Read the elements of lists using for loop
4: Find the largest element from list using max() function
5: Print the result
6: Stop
PROGRAM:

# Function to find the maximum element in a list


def maximum(numbers):
return max(numbers)

# Main program
n = int(input("Enter no. of elements: ")) # Get the number of elements
numbers = [] # Initialize an empty list

print("Enter", n, "elements") # Prompt for elements


for i in range(n):
element = int(input("Enther a number:")) # Input each element
numbers.append(element) # Add the element to the list

# Find and print the largest element


print("Largest element is:", maximum(numbers))
OUTPUT:

Enter no. of elements: 3

Enter 3 elements

Enther a number:232

Enther a number:246

Enther a number:135

Largest element is: 246

RESULT:

Thus, a Python Program to find the largest number in a list was


executed and the output was obtained.
7. PROGRAMS USING STRINGS

7 a) REVERSE OF A STRING

AIM:
To write a Python Program to reverse a string
ALGORITHM:

1. Start the Program


2. Read a string from user
3. Perform reverse operation
4. Print the result
5. Stop the program

PROGRAM:

# Function to reverse a string using slicing


def reverse_string(s):
return s[::-1]

# Main program
# Get user input
input_str = input("Enter a string: ") # Prompt the user to enter a string
# Reverse the string
reversed_str = reverse_string(input_str)
# Print the reversed string
print("Original string is:", input_str)
print("Reversed string is:", reversed_str)
OUTPUT:

Enter a string: hello world


Original string is: hello world
Reversed string is: dlrow olleh

RESULT:

Thus, a Python Program to reverse a string was executed and the


output was obtained.
7 b) PALINDROM OR NOT

AIM:

To write a python Program to perform string operations for the following using
built-in functions: Palindrome.

ALGORITHM:
1. Start
2. Read the text.
3. Display the reverse of the text using Slicing operator.
4. Reversed text and Original text are same then print the text is Palindrome.
5. Stop.

PROGRAM:

# Get user input


Str1 = input("Enter the text: ")
# Reverse the string
Str2 = Str1[::-1]
# Print the reversed text
print("Reversed Text:", Str2)

# Check if the original string is the same as the reversed string


if Str1 == Str2:
print("Given Text is a Palindrome")
else:
print("The given Text is not a Palindrome")

OUTPUT:

Enter the text: mam


Reversed Text: mam
Given Text is a Palindrome

RESULT:

Thus, a Python Program to check whether the string is palindrome or


not was executed and the output was obtained.
. 7 c) COUNTING CHARACTER IN A STRING

AIM:

To write a python Program to perform string operations for the following using
built-in functions: Character count.

ALGORITHM:

1. Start
2. Read the text.
3. Read the character to be counted.
4. Using count method count the appearance of the character.
5. print the count.
6. Stop

PROGRAM:

Str1=input("Enter the text: ")


Str2=input("Enter the chracter to be counted: ")
count=Str1.count(Str2)
print("{} appears in {} {} number of times".format(Str2,Str1,count))

OUTPUT:

Enter the text: Welcome


Enter the character to be counted: e
e appears in Welcome 2 number of times

RESULT:

Thus, a Python Program to count number of times a character have


occurred was executed and the output was obtained.
7 d) REPLACING CHARACTERS IN A STRING

AIM:

To write a python Program to perform string operations for the following using
built-in functions: Replace the characters.

ALGORITHM:
1. Start
2. Read the text.
3. Read the Text to be replaced and the Replace Text.
4. Using replace method replace the text.
5. print the Replace Text.
6. Stop

PROGRAM:

Str1 = input("Enter the Text:")


#print(Str1)
S1=input("Enter the Text to be replaced :")
S2=input("Enter the Text to be replaced by:")
Str2 = Str1.replace(S1,S2)
print("Replaced Text:")
print(Str2)
S1=input("Enter the Text to be replaced :")
S2=input("Enter the Text to be replaced by:")
count=int(input("Enter number of occurance to be replaced :"))
Str2 = Str1.replace(S1,S2,count)
print("Replaced Text:")
print(Str2)
OUTPUT:

Enter the Text:Class test Class score Class average


Enter the Text to be replaced :Class
Enter the Text to be replaced by:Internal
Replaced Text:
Internal test Internal score Internal average
Enter the Text to be replaced :Class
Enter the Text to be replaced by:Internal
Enter number of occurance to be replaced :2

Replaced Text:
Internal test Internal score Class average

RESULT:
Thus, a Python Program to perform String operation was executed and the
output was verified.
8. IMPLEMENTING PROGRAMS USING WRITTEN MODULES
AND PYTHON STANDARD LIBRARIES
8 a) PANDAS

AIM:

To write a python program to compare the elements of the two Pandas


Series using pandas library
Sample Series: [2,4,6,8,10],[1,3,5,7,10]
ALGORITHM:
1. Start the program
2. Import pandas from python standard libraries
3. Assign data series as ds1 and ds2
4. Compare the elements of the series and print equals, greater than and less
than
5. Stop the program

PROGRAM:

import pandas as pd

# Create two pandas Series


ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])

# Print Series 1
print("Series 1:")
print(ds1)

# Print Series 2
print("Series 2:")
print(ds2)
# Compare the elements of the two Series
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2) # Check for equality
print("Greater Than:")
print(ds1 > ds2) # Check if elements in ds1 are greater than those in ds2

print("Less Than:")
print(ds1 < ds2) # Check if elements in ds1 are less than those in ds2

OUTPUT:

Series 1:

0 2
1 4
2 6

3 8
4 10
dtype: int64 Series 2:
0 1

1 3

2 5

3 7

4 10

dtype: int64
Compare the elements of the said Series: Equals:
0 False
1 False

2 False

3 False

4 True dtype: bool


Greater Than:
0 True

1 True

2 True

3 True
4 False dtype:
bool Less Than:
0 False

1 False

2 False

3 False

4 False dtype:
bool
RESULT:

Thus, a Python Program to use pandas library was executed and the output
was verified.
8 b) Numpy

AIM:

To write a python program to test whether none of the elements of a given


array is zero using NumPy library.
ALGORITHM:
1. Start the program
2. Import numpy from python standard library
3. Declare an array and print the original array
4. Test whether none of the elements often array is zero or not
5. If it contains zero print False otherwise print True
6. Stop the Program.

PROGRAM:
import numpy as np

# Create the first array


x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)

# Test if none of the elements of the array is zero


print("Test if none of the elements of the said array is zero:")
print(np.all(x))

# Create the second array


x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)

# Test if none of the elements of the array is zero


print("Test if none of the elements of the said array is zero:")
print(np.all(x))
OUTPUT:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False

RESULT:

Thus, a Python Program to use numpy library was executed and the output
was verified.
8 c) MATPLOTLIB

AIM:
To write a python program to plot a graph using matplotlib library
ALGORITHM:
1. Start the program
2. Import matplotlib from python standard library
3. Declare two arrays to define coordinators for 2 points
4. Plot graph for those mentioned points using matplot library
5. Stop the Program.

PROGRAM:

import matplotlib.pyplot as
plt # Define the data points
x = [1,2,3,4,5]
y = [1,2,3,4,5]
# Create a scatter plot
plt.scatter(x, y, color='blue',
marker='o') # Add title and labels
plt.title("Scatter Plot of
Points") plt.xlabel("X-
axis") plt.ylabel("Y-axis")
# Show the
plot plt.grid()
plt.show()

OUTPUT:
RESULT:

Thus, a Python Program to use matplolib was executed and the output was
verified.
8 d) SCIPY

AIM:
To write a python program to return the specified unit in seconds using sciptlibrary

ALGORITHM:
1. Start the program
2. Import scipy from python standard library
3. Print specified units like minute, hour, day etc
4. Stop the Program.

PROGRAM:

from scipy import constants

# Print time conversions


print('1 minute =', constants.minute, 'seconds')
print('1 hour =', constants.hour, 'seconds')
print('1 day =', constants.day, 'seconds')
print('1 week =', constants.week, 'seconds')
print('1 year =', constants.year, 'seconds')
print('1 Julian year =', constants.Julian_year, 'seconds')

OUTPUT:

1 minute= 60.0 seconds


1 hour= 3600.0 seconds
1 day= 86400.0 seconds
1 week= 604800.0 seconds
1 year= 31536000.0 seconds
1 Julian year= 31557600.0 seconds
RESULT:

Thus, a Python Program to use scipy library was executed and the output was verified.
9. IMPLEMENTING REAL TIME /TECHNICAL APPLICATIONS
USING FILE HANDLING

9 a) FILE COPY

AIM:
To write a Python Program to copy the content of one file into another using
File manipulation function and methods.

ALGORITHM:

1: Start
2: Open a file named source.txt in read mode
3: Open a file named dest.txt in write mode
4: Read the content of file source.txt line by line using
for loop
5: Write the content onto file dest.txt usint write()
function
6: Close the file
7: Open a file named dest.txt in read mode
8: Read the content of file dest. using read() function
and display the content
9: Stop
PROGRAM:

# FILE COPY

fp1=open("source.txt","w")
fp1.write("python python\n")
fp1.write("java python\n")
fp1.write("c java\n")
fp1=open("source.txt","r")
fp2=open("dest.txt","w")
for line in fp1:
fp2.write(line)
fp1.close()
fp2.close()
fp2=open("dest.txt","r")
print("dest.txt")
print(fp2.read())

# Create and write to the source file


with open("source.txt", "w") as fp1:
fp1.write("python python\n")
fp1.write("java python\n")
fp1.write("c java\n")

# Read from the source file and write to the destination file
with open("source.txt", "r") as fp1, open("dest.txt", "w") as fp2:
for line in fp1:
fp2.write(line)

# Read and print the contents of the destination file


with open("dest.txt", "r") as fp2:
print("dest.txt")
print(fp2.read())
OUTPUT:

dest.txt
python python
java python
c java

RESULT:
Thus, a Python Program copy the content of one file into another was
executed and the output was obtained.
9 b) WORD COUNT -FILE

AIM:

To write a Python Program to find the words in a text file and the number of
occurrence of the words.

ALGORITHM:

1: Open a file named source.txt in read mode.


2: Create a empty dictionary named wordcount
3: Repeat until each word is read from file and splitted
using separator ‘space’
3a: Check if word is present in wordcount, then
3a.i: wordcount[word]=1
3b: Else wordcount[word]=wordcount[word]+1
4: print wordcount
5: Close the file
PROGRAM:

# WORD COUNT

# Open the source file for reading

with open("source.txt", "r") as fp1:

content = fp1.read()

# Print the contents of the source file

print("source.txt")

print(content)

# Initialize a dictionary to hold word counts

wordcount = {}

# Split the content into words

words = content.split()

# Count the occurrences of each word

for w in words:

if w not in wordcount:

wordcount[w] = 1

else:

wordcount[w] += 1

# Print the word count dictionary

print(wordcount)
fp1=open("source.txt","r")

wordcount={}
content=fp1.read()
print("source.txt")
print(content)
words=content.split()
for w in words:
if w not in wordcount:
wordcount[w]=1
else:
wordcount[w]+=1
print (wordcount)
fp1.close()

OUTPUT:

source.txt
python python
java python
c java

{'python': 3, 'java': 2, 'c': 1}

RESULT:
Thus, a Python Program to find the words in a text file and the number
of occurrence of the words was executed and the output was obtained.
9 C) LONGEST WORD

AIM:
To write a Python Program to find the longest word in a file.

ALGORITHM:

1. Start
2. Open the file from the specified path and read the data using read()
method
3. Find the longest word using max() function and print the result
4. Stop the program

PROGRAM:

def longest_word(filename):
with open (filename,’r’)as infile:words
= infile.read().split()
Max_len = len(max(words,key=len))
return [word for word in words if len(word)==max_len]
print(longest_word(“F:\Data.txt”)

with open(filename, 'r') as infile:


words = infile.read().split()

# Find the maximum length of the words


max_len = len(max(words, key=len))

# Return a list of words that have the maximum length


return [word for word in words if len(word) == max_len]

# Example usage
print(longest_word("F:\\Data.txt"))
OUTPUT:

[‘collection’]

RESULT:

Thus a Python Program to find the largest word in a file was executed
and the output was obtained.
10. IMPLEMENTING REAL TIME/TECHNICAL APPLICATIONS
USING EXCEPTION HANDLING

10 a) EXCEPTION HANDLING-VOTER’S AGE VALIDITY

AIM:
To write a Python Program to find validate voter’s age validity using
Exception Handling.

ALGORITHM:

1: Start
2: Read the value of age of the person.
3: if (Age > 18) then 3a else 3b.
3a: Print Eligible to vote.
3b: Print not Eligible to vote.
4: if valid age not entered raise exception

PROGRAM:

# EXCEPTION HANDLING-VOTER’S AGE VALIDITY

# EXCEPTION HANDLING - VOTER’S AGE VALIDITY

try:
age=int(input("enter your age"))
if(age>=18):
print ("eligible to vote")
else:
print("not eligible to vote")
except:
print("enter a valid age")

age = int(input("Enter your age: ")) # Prompt for age input

if age >= 18:

print("Eligible to vote") # Check if age is 18 or older

else:
print("Not eligible to vote") # If age is less than 18

except ValueError:

print("Enter a valid age") # Handle the case where input is not an integer

OUTPUT:

enter your age :s


enter a valid age

RESULT:
Thus, a Python Program to find validate voter’s age validity using
Exception Handling was executed and the output was obtained.
10 b) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING

AIM:
To write a Python Program to find handle divide by zero error using
exception handling

ALGORITHM:

1. Start
2. Read the value for n,d and c
3. Calculate Quotient = n/(d-c) in try block
4. If ZeroDivisionError arise print division by zero
5. Stop

PROGRAM:

n=int(input("enter the value of n:"))


d=int(input("enter the value of d:"))
c=int(input("enter the value of c:"))
try:
q=n/(d-c)
print(“Quotient”,q)
# Input values for n, d, and c
n = int(input("Enter the value of n: "))
d = int(input("Enter the value of d: "))
c = int(input("Enter the value of c: "))
try:
# Calculate the quotient
q = n / (d - c)
print("Quotient:", q) # Print the quotient
except ZeroDivisionError:
print("Division by zero") # Handle division by zero error
except ValueError:
print("Please enter valid integers") # Handle invalid integer input
OUTPUT:

enter the value of n:4


enter the value of d:4
enter the value of c:4
Division by zero

RESULT:
Thus, a Python Program handle divide by zero error using Exception
Handling was executed and the output was obtained.
10 c) STUDENT MARK RANGE VALIDATION

AIM:
To write a Python Program to perform student mark range validation

ALGORITHM:

1. Start
2. Read student mark from user
3. If mark is in between 0 and 100 print in range
4. Otherwise print out of range
5. Stop

PROGRAM:

Mark=int(input("enter the mark:"))


if Mark <0 or Mark>100:
print (“ value is out of range”)
# Input mark
Mark = int(input("Enter the mark: "))

# Check if the mark is out of range


if Mark < 0 or Mark > 100:
print("Value is out of range")
else:
print (“ value("Value is in range”)
")

OUTPUT:

enter the mark: 123


value is out of range

RESULT:
Thus, a Python Program student mark validation was executed and the
output was obtained.
11. EXPLORING PYGAME

AIM:

To write a python program to simulate bouncing ball using


Pygame
ALGORITHM:

1. Import the necessary files for the implementation of this


Pygame.
2. Set the display mode for the screen using
a. window
Surface=pygame.display.set_mode((500,400),0,32
)
3. Now set the display mode for the pygame to bounce
a. pygame.display.set_caption(“Bounce”)
4. Develop the balls with necessary colors.
a. BLACK=(0,0,0)
b. WHITE=(255,255,255)
c. RED=(255,0,0)
d. GREEN=(0,255,0)
e. BLUE=(0,0,255)
5. Set the display information
info=pygame.display.Info()
⮚ Set the initial direction as
down.
6. Change the direction from down to up.
7. Then again change the direction from up to down.
8. Set the condition for quit.
9. Exit from the pygame
PROGRAM:

import pygame

# Initialize Pygame
pygame.init()

# Set up the screen


screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Bouncing Ball")

# Set up the ball


ball_color = (255, 255, 255)
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_dx = 5
ball_dy = 5

# Start the game loop


running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Move the ball


ball_x += ball_dx
ball_y += ball_dy

# Bounce off the walls


if ball_x + ball_radius > screen_width or ball_x - ball_radius < 0:
ball_dx = -ball_dx
if ball_y + ball_radius > screen_height or ball_y - ball_radius < 0:
ball_dy = -ball_dy

# Draw the ball and update the screen


screen.fill((0, 0, 0)) # Clear the screen with black
pygame.draw.circle(screen, ball_color, (ball_x, ball_y), ball_radius) # Draw
the ball
pygame.display.update() # Update the display
# Quit Pygame
pygame.quit()

OUTPUT:

RESULT:
Thus, the bouncing ball using pygame has been successfully executed and
output is obtained.
12. SEARCHING AND SORTING

12 a) Binary Search

AIM:
To write a Python Program to find whether the given number is present in a
list using binary search.

ALGORITHM:

1: Create a List named list with some integer values


2: Get the element that has to be searched in the list from the
user and store in variable X
3: Assign the values of l and h
4 : while (l<=h) is true repeat till 6
5 : Mid=(lower limit + higher limit)/2
6: if ((X==list[mid]):
print “Element found” and terminate the loop
elif(X<list[mid]):
h=mid-1
else:
l=mid+1
9: Otherwise print “Element not found”
10: Stop
PROGRAM:

# BINARY SEARCH
# Note: Avoid using 'list' as a variable name since it's a built-in type in Python.
numbers = [11, 17, 20, 23, 29, 33, 37, 41, 45, 56]
X = int(input("Enter the number to be searched: "))
l=0
h = len(numbers) - 1

while l <= h:
mid = (l + h) // 2
if X == numbers[mid]:
print("Element found at index:", mid)
break
elif X < numbers[mid]:
h = mid - 1
else:
l = mid + 1
else:
print("Element not found")

OUTPUT:

Enter the number to be searched:17

Element found

RESULT:
Thus, a Python Program to find whether the given is present in a list
using binary search was executed and the output was obtained.
12b) Insertion Sort

AIM:

To write a Python Program to sort the elements in the list using Insertion

Sort.

ALGORITHM:

1. Initialize the list in a


2. For every element in the list
3. Get the index position of the element in j
4. Repeat until j>0 upto 7
5. If a[j-1] >a[j]:
6. Swap the elements a[j-1] and a[j]
otherwise break out of the loop
7. Decrement the value of j
8. Display the sorted List
9. Stop
PROGRAM:

# Insertion Sort
a = [16, 19, 11, 15, 10, 12, 14]
print("Original List:", a)

# Insertion Sort Algorithm


for i in range(1, len(a)):
j=i
while j > 0:
if a[j - 1] > a[j]:
a[j - 1], a[j] = a[j], a[j - 1] # Swap elements
j -= 1
else:
break

print("Sorted List:", a)

OUTPUT:

Sorted List: [10, 11, 12, 14, 15, 16, 19]

RESULT:
Thus, a Python Program to sort the elements in the list using Insertion
Sort was executed and the output was obtained.
13. CREATE A MODULE

AIM:

To create a module in python program.

ALGORITHM:

1. Start
2. Create mymodule.py
3. Import the mymodule.py
4. Print age of the person
5. STOP

PROGRAM:

mymodule.py

# mymodule.py

person1 = {

"name": "John",

"age": 36,
"country": "Norway"
}

"country": "Norway"

# new.py

import mymodule

a = mymodule.person1["age"]
print(a)

# Access the age from the person1 dictionary in mymodule


a = mymodule.person1["age"]

print(a)

OUTPUT:

36

RESULT:

Thus, a Python Program to create and import module was executed and
the output was obtained.

You might also like