Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

New Python Lab Manual PDF

Uploaded by

keerthi
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)
36 views

New Python Lab Manual PDF

Uploaded by

keerthi
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/ 53

DEPARTMENT OF SCIENCE AND HUMANITIES

ACADEMIC YEAR: 2024-2025

24ESC122 – PYTHON PROGRAMMING LAB MANUAL

NAME : _____________________________________

ROLL NO :_________________

BRANCH :__________________

YEAR/SEM : _____________
Certified that this is the bonafide record of work done

by Mr./Ms.................................................................................in the

of 24ESC122 – PYTHON PROGRAMMING LABORATORY

this institution, as prescribed by the Anna University, Chennai for the FIRST

Semester Science and Humanities , during the year 2024-2025.

Staff - In charge Head of the Department

Submitted for the University Practical Examination held on ........................at

Sree Sakthi Engineering College, Coimbatore – 641 104.

Internal Examiner External Examiner


LIST OF EXPERIMENTS
S.NO DATE NAME OF THE EXPERIMENT PAGE MARKS STAFF
NO SIGN
EX. NO:1a Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Electricity
Billing

AIM:

To develop a flowchart for electricity billing.

ALGORITHM:

Step1: Start.
Step2: Read the previous unit and current unit.
Step 3: Calculate the used units by subtracting the current unit and previous unit. Step4:
Calculate the Electricity bill from the used units.
Step 5: Print the amount of electricity bill. Step6: Stop.

PSEUDOCODE:

READ Previous unit,Current Unit


CALCULATE Used Unit = Current Unit – Previous Unit ElectricityBill=Used Unit x 2
PRINT ElectricityBill
FLOWCHART:

RESULT:

Thus, the flowchart for the electricity billing is developed.


EX. NO:1b. Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Retail
Shop Billing

AIM:

To develop a flowchart for the retail shop billing.

ALGORITHM:

Step1: Start.
Step2: Read the barcode of the product.
Step3: Display the product name and the amount.
Step 4: Check if more products is available, if available go to Step 2, otherwise go to Step
5.
Step5: Calculate the total cost of the products.
Step6: Print total cost. Step7: Stop.

PSEUDOCODE:

IF more products available THEN READ bar code


DISPLAY Product name, amount
ELSE
CALCULATE Total Cost
PRINT Total Cost
ENDIF
FLOWCHART:

RESULT:

Thus, the flowchart for retail shop billing is developed.


EX. NO:1c. Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Sin Series

AIM:

To develop a flowchart for the Sine Series.

ALGORITHM:

Step1: Start
Step2: Read x and n.
Step3: Print x and n.
Step 4: Convert x values into radian using formula x = x * 3.1412/180. Step5: Substitute t=x
and sum=x.
Step 6: Set the for loop for doing the calculation as initialize i to 1 and check i is less thann+1
and increment i by 1.
Step 7: Calculate t=(t*pow(-1),(2*i-1))*x*x)/(2*i*(2*i+1).
Step8: Calculate sum = sum + t.
Step9: Print sum.
Step10: Stop

PSEUDOCODE:

READ x, n PRINT x, n
CONVERT x =x * 3.1412/180
SUBSTITUTE t=x, sum=x FOR i=1; i<n+1;i++
t= (t*pow (-1), (2*i-1))*x*x)/(2*i*(2*i+1). sum = sum + t
END FOR
PRINT sum
FLOWCHART:

RESULT:
Thus, the flowchart for the sine series is developed.
EX. NO:1d Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Weight of
a Motorbike

AIM:

To develop a flowchart for finding the weight of a motor bike.

ALGORITHM:

Step1: Start.
Step2: Read the size of the motor bile in cc.
Step3: Check whether the size of the motor bike is less than or equal to 300 cc, if so, Print
Average weight is 350 pounds otherwise go to step 4.
Step4: Check whether the size of the motor bike is less than or equal to 500 cc, if so, Print
Average weight is 410 pounds otherwise go to step 5.
Step5: Check whether the size of the motor bike is less than or equal to 900cc, if so, Print
Average weight is 430 pounds otherwise go to step 6.
Step6: Check whether the size of the motor bike is equal to 1100 cc, if so, Print Average weight
is 500 pounds otherwise go to step 7.
Step 7: Print Average weight is 600 pounds.
Step 8: Stop.

PSEUDOCODE:

READ size in cc
IF size<=300 THEN
PRINT Average weight = 350 pounds ELSEIF size <=500 THEN
PRINT Average weight = 410 pounds ELSEIF size <=900 THEN
PRINT Average weight = 430 pounds ELSEIF size =1100 THEN
PRINT Average weight=500pounds
ELSE
ENDIF PRINT Average weight=600pounds
FLOWCHART:

RESULT:

Thus, the flowchart for finding the weight of the motor bike is developed.
EX. NO:1e Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Weight of
a steel bar

AIM:

To develop a flowchart for finding weight of a steel bar.

ALGORITHM:

Step1:Start.
Step2:Read the diameter in mm and length of the steel bar.
Step3:Check whether the length is in meter if so, calculate weight as diameter x diameter x
length and divide it by 162, otherwise go to step4.
Step 4: calculate weight as diameter x diameter x length and divide it by 533.
Step5: Print the weight.
Step6: Stop.

PSEUDOCODE:

READ diameter, length IF length in meter, THEN


Weight=diameter*diameter*length/162
ELSE
Weight=diameter*diameter*length/533
ENDIF
PRINT Weight
FLOWCHART:

RESULT:

Thus, the flowchart for finding the weight of a steel bar is developed.
EX. NO:1f Identification and solving of simple real life or scientific or
DATE: technical problems and developing flow charts for the Compute
Electrical Current
in Three Phase AC Circuit

AIM:

To develop a flowchart to compute electrical current in three phase AC circuit.

ALGORITHM:

Step1: Start.
Step2: Get the value of voltage, resistance, current and power factor.
Step3: Compute the electric current by multiplying voltage, resistance, current and power factor
with 3.
Step 4: Print the calculated electric current.
Step5: Stop.

PSEUDOCODE:

READ voltage, resistance, current and power factor


COMPUTE Electric Current = 3 x voltage x resistance x current x power factor PRINT Electric
Current
FLOWCHART:

RESULT:

Thus, the flowchart for computing the electric current in three phase AC circuit is developed.
EX. NO:2a Python programming exchange the values of two variables using
DATE: simple statements and expressions

AIM:
To write a Python Program to exchange the value of two variables.

ALGORITHM:
Step 1: start the program
Step2: enter two variables and assign value for it(x, y)
Step3: simply exchange the variables(y, x) and assign it to variables(x,y)
step 4: print ‘x’ value
Step5: print ‘y’ value step6: end the program

PROGRAM:
x=5
y = 10
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print ('The value of x after swapping:',x)
print ('The value of y after swapping:', y)

OUTPUT :
The value of x after swapping: 10
The value of y after swapping: 5
x=5
y = 10
x, y = y, x print ("x =", x)
print ("y =", y)

OUTPUT:
x = 10
y=5

RESULT:
Thus the Python Program to exchange the value of two variables was written and executed
successful
EX. NO:2b Python programming circulate the values of n variables using
DATE: simple statements and expressions

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

ALGORITHM:
Step1: start the program
Step2: read the total number of values step3: enter the values
Step4: append the value in the list1 step5: print the list1 of elements
Step6: check the range of values and pop the first element from the list1 and append it at the
last in the list1
Step7: continue until range (0 to 3) exit.
Step8: end the program.

PROGRAM:
def circulate(A,N):
for i in range (1,N+1):
B=A[i:]+A[:i]
print("Circulation",i,"=",B)
A=[1,2,3,4,5]
N=int(input("Enter n:"))
circulate(A,N)

OUTPUT:
Enter n:5
Circulation 1 = [2, 3, 4, 5, 1]
Circulation 2 = [3, 4, 5, 1, 2]
Circulation 3 = [4, 5, 1, 2, 3]
Circulation 4 = [5, 1, 2, 3, 4]
Circulation 5 = [1, 2, 3, 4, 5]

RESULT:
Thus the Python Program to circulate the values of n variables was written and executed
successfully.
EX. NO:2c Python programming distance between two
DATE: points using simple statements and expressions

AIM:
To write a Python Program to find the distance between two points.
ALGORITHM:
Step1: start the program step2: import math library
Step 3: take a two points as an input from an user.
Step 4: calculate the difference between the corresponding x-coordinates i.e.:x2 - x1 and y
Coordinates i.e.:y2 - y1of two points.
Step 5: apply the formula derived from pythagorean theorem i.e.: sqrt ((x2 - x1) ^2 + (y2 - y1)
^2)
Step 6 : end the program

PROGRAM:
import math
x1=int(input("Enter x1:"))
y1=int(input("Enter y1:"))
x2=int(input("Enter x2:"))
y2=int(input("Enter y2:"))
distance= math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print ("Distance=",distance)

OUTPUT:
Enter x1:3
Enter y1:2
Enter x2:7
Enter y2:8
Distance= 7.211102550927978

RESULT:
Thus the Python Program to find the distance between two points was written and
executed successfully.
EX. NO:3a Scientific problems Number series using Conditionals and
DATE: Iterative loops

AIM :
To write a python program to print number series.

ALGORITHM :

Step1: start the program


Step2: initialize the values of a and b
Step3: read the number of terms in the sequence; n
step4: print value of a, b
Step5: add the values of a, b and store in c
Step6: print the values of a, b and assign value of b, c into a, b
step7: repeat the step5 & 6 for n-2 times.

PROGRAM:
n=int(input("Enter the number:"))
i=0
while(i<n):
print(i)
i=i+1

OUTPUT:
enter the number:5
0
1
2
3
4

RESULT:

Thus the python program to print number series was written and executed
successfully.
EX. NO:3b Scientific problems number patterns using Conditionals and
DATE: Iterative loops.

AIM:
To write a python program to print number pattern.

ALGORITHM:
Step1: start
Step2: range (10) –range function takes values from 0 to 9
step3: str (i) prints string version of i .(i.e i value)
Step4: using for loop print str (i) values i times in every iteration

PROGRAM:
rows = int(input('Enter the number of rows: '))
for i in range(1, rows+1):
for j in range(i):
print(i, end=' ')
print()
(or)
for i in range(10): print(str(i)*i)

OUTPUT:
1
22
333
4444
55555
666666
7777777
88888888
999999999

RESULT:
Thus the python program to print number pattern was written and executed successfully.
EX. NO:3c Scientific problems pyramid pattern of a star using Conditionals
DATE: and Iterative loops

AIM:

To write a python program to print Pyramid pattern of a star.

ALGORITHM:

Step1: first, we get the height of the pyramid rows from the user.
Step2: in the first loop, we iterate from i = 0 to i = rows.
Step3: the second loop runs from j = 0 to i + 1.
Step4: in each iteration of this loop, we print i + 1 number of * without a new line.
Step5: here, the row number gives the number of * required to be printed on that row.
Step6: once the inner loop ends, we print new line and start printing * in a new line.

PROGRAM:
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()
full_pyramid(5)

OUTPUT:
*
**
***
****
*****

RESULT:
Thus the python program to print Pyramid pattern of a star was written and executed
successfully.
EX. NO:4.A Implementing real-time/technical applications Items present in a
DATE: Library using Lists and Tuples.

AIM:
To write a python program to implement items present in a Library using List.

ALGORITHM:
Step1: Start the program
Step2: Assign list of library materials
Step3Perform all the list operation /Tuples operation
Step4: Print the result
Step5: End the program

PROGRAM:
Library using Lists
library=["book","autor","barcodenumber","price"]
print(library)
library[0]='RAMAYANA'
print(library[0])
print(library)
library[1]='Valmiki'
library[2]=123576
library[3]=230
print(library)

OUTPUT:
['book', 'autor', 'barcodenumber', 'price']
RAMAYANA
['RAMAYANA', 'autor', 'barcodenumber', 'price']
['RAMAYANA', 'Valmiki', 123576, 230]
TUPLE:
LIBRARY USING TUPLES
libcomp=('books', 'newspaper', 'computer', 'magazine', 'journals')
print(libcomp)
print(libcomp[0])
Tuplelength=len(libcomp)
print(Tuplelength)
print(libcomp[1:4])

OUTPUT:
('books', 'newspaper', 'computer', 'magazine', 'journals')
books
5
('newspaper', 'computer', 'magazine')

RESULT:

Thus the Python program to implement items present in a Library using List was written
and executed successfully.
EX. NO:4.b Implementing real-time/technical applications Components of a
DATE: car using Lists

AIM:
To write a python program to implement components of a car using List

ALGORITHM:
Step1: Start the program
Step2: Assign list of car parts
Step3: Perform all the list operation
Step4: Print the result
Step5: End the program

PROGRAM:
COMPONENTS OF CAR USING LIST
carparts =['ENGINE','WHEEL','GEAR','BATTERY']
print(carparts)
carparts.append('BREAK')
print(carparts)
carparts.remove('BREAK')
print(carparts)
print(carparts.index('WHEEL'))
carparts.reverse()
print('Reversed list:',carparts)
New = carparts[:]
print(New)

OUTPUT
['ENGINE', 'WHEEL', 'GEAR', 'BATTERY']
['ENGINE', 'WHEEL', 'GEAR', 'BATTERY']
['ENGINE', 'WHEEL', 'GEAR', 'BATTERY', 'BREAK']
['ENGINE', 'WHEEL', 'GEAR', 'BATTERY']
1
Reversed list: ['BATTERY', 'GEAR', 'WHEEL', 'ENGINE']
['BATTERY', 'GEAR', 'WHEEL', 'ENGINE']
COMPONENTS OF CAR USING TUPLES

carparts =('ENGINE','WHEEL','GEAR','BATTERY')
print(carparts)
print('Item in the first position is: ',carparts[0])
print('Item in the 5th position is: ',carparts[3])
print(carparts.index('WHEEL'))
tuples=len(carparts)
print(tuples)

OUTPUT:

('ENGINE', 'WHEEL', 'GEAR', 'BATTERY')


('ENGINE', 'WHEEL', 'GEAR', 'BATTERY')
Item in the first position is: ENGINE
Item in the 5th position is: BATTERY
1
4

RESULT:

Thus the python program to implement components of a car using List was written and
executed successfull
EX. NO:4.c.(i) Implementing real-time/technical applications Materials
DATE: required for construction of a building using Lists

AIM:
To write a python program to implement materials required for construction of a building using
List.

ALGORITHM:
Step1:Start the program
Step2:Assign list of building materials
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

PROGRAM

MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING USING LISTS


Buildingconstruction=['bricks','cement','sand','water','steel']
print(Buildingconstruction)
Buildingconstruction.append('WOOD')
print(Buildingconstruction)
Buildingconstruction.remove('WOOD')
print(Buildingconstruction)
print(Buildingconstruction.index('sand'))
Buildingconstruction.reverse()
print('Reversed list:',Buildingconstruction)
New = Buildingconstruction[:]
print(New)

OUTPUT
['bricks', 'cement', 'sand', 'water', 'steel']
['bricks', 'cement', 'sand', 'water', 'steel']
['bricks', 'cement', 'sand', 'water', 'steel', 'WOOD']
['bricks', 'cement', 'sand', 'water', 'steel']
2
Reversed list: ['steel', 'water', 'sand', 'cement', 'bricks']
['steel', 'water', 'sand', 'cement', 'bricks']
TUPLE:
Buildingconstruction=('bricks','cement','sand','water','steel')
print(Buildingconstruction)
print(Buildingconstruction)
New = Buildingconstruction[:]
print(New)
tuples=len(Buildingconstruction)
print(tuples)

OUTPUT
('bricks', 'cement', 'sand', 'water', 'steel')
('bricks', 'cement', 'sand', 'water', 'steel')
('bricks', 'cement', 'sand', 'water', 'steel')
5

RESULT:
Thus the python program to implement materials required for construction of a
building using List was written and executed successfully.
EX. NO:5.a.(i) Implementing real-time/technical applications Language using
DATE: Sets and Dictionaries

AIM:
To write a python program to implement language using set and dictionaries.

ALGORITHM:
Step1: Start the program.
Step2: Assign the languages.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
LANGUANGE USING SET
language1={'JAVA','C++','PYTHON'}
language2={'VB','ORACLE'}
print(language1)
print(language2)
language1.add('SQL')
print(language1)
language1.remove('SQL')
print(language1)
print(language2.union(language1))

OUTPUT:

{'PYTHON', 'C++', 'JAVA'}


{'VB', 'ORACLE'}
{'PYTHON', 'SQL', 'C++', 'JAVA'}
{'PYTHON', 'C++', 'JAVA'}
{'C++', 'PYTHON', 'JAVA', 'VB', 'ORACLE'}
DICTIONARY
language={'C':5, 'C++':3, 'ORACLE':9, 'PYTHON':7}
print(language)
x = language.copy()
print(x)
x = language.pop('C')
print(x)
print(language)
x = language.values()
print(x)
x = language.keys()
print(x)
language.clear()
print (language)

OUTPUT

'C': 5, 'C++': 3, 'ORACLE': 9, 'PYTHON': 7}


{'C': 5, 'C++': 3, 'ORACLE': 9, 'PYTHON': 7}
5
{'C++': 3, 'ORACLE': 9, 'PYTHON': 7}
dict_values([3, 9, 7])
dict_keys(['C++', 'ORACLE', 'PYTHON'])
{}

RESULT:
Thus the python program to implement language using dictionaries was written and
executed successfully.
EX. NO:5.b.(i) Implementing real-time/technical applications an
components of automobile using Sets and Dictionaries

AIM:
To write a python program to implement components of an automobile using set.

ALGORITHM:
Step1: Start the program.
Step2: Assign the components of automobile.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
COMPONENTS USING SETS
components1={'ENGINE', 'GEAR', 'TIRE'}
components2={'STREEING', 'TRANSMISSION'}
print(components1)
print(components2)
components1.add('Gearbox')
print(components1)
components1.remove('Gearbox')
print(components1)

OUTPUT
{'ENGINE', 'GEAR', 'TIRE'}
{'STREEING', 'TRANSMISSION'}
{'ENGINE', 'GEAR', 'Gearbox', 'TIRE'}
{'ENGINE', 'GEAR', 'TIRE'}
PROGRAM:

COMPONENTS USING DICTIONARIES

components = {'Break':2,'Tire':4,'Steer':1}
print(components)
x = components.copy()
print(x)
x = components.get('Tire')
print(x)
x = components.items()
print(x)
components.update({'color': 'White'})
print(components)
x = components.pop('Break')
print(x)

OUTPUT

{'Break': 2, 'Tire': 4, 'Steer': 1}


{'Break': 2, 'Tire': 4, 'Steer': 1}
4
Dict,items([('Break', 2), ('Tire', 4), ('Steer', 1)])
{'Break': 2, 'Tire': 4, 'Steer': 1, 'color': 'White'}
2

RESULT:
Thus the python program to implement components of an automobile using set and
dictionaries was written and executed successfully.
EX. NO:5.C Implementing real-time/technical applications Elements of a
DATE: civil structure using Sets

AIM:
To write a python program to implement elements of a civil structure using sets.

ALGORITHM:
Step1: Start the program.
Step2: Assign the elements of a civil structure.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
elements1={'columns','roof', 'stair','floors'}
elements2={'foundation','floors','walls'}
print(elements1)
print(elements2)
elements1.add('beams')
print(elements1)
elements1.remove('beams')
print(elements1)
print(elements2.union(elements1))
print(elements1 & elements2)

OUTPUT:

{'stair', 'columns', 'floors', 'roof'}


{'walls', 'foundation', 'floors'}
{'floors', 'stair', 'beams', 'columns', 'roof'}
{'floors', 'stair', 'columns', 'roof'}
{'columns', 'foundation', 'floors', 'walls', 'stair', 'roof'}
{'floors'}

RESULT:
Thus the python program to implement elements of a civil structure using sets was written
and executed successfully.
EX. NO:5.c.(ii) Implementing real-time/technical applications
DATE: Elements of a civil structure using Dictionaries.

AIM:
To write a python program to implement elements of a civil structure using dictionary.

ALGORITHM:
Step1: Start the program.
Step2: Assign the elements of a civil structure.
Step3: Perform all the dictionary operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
elements = {"foundation":14, "floors":3, "walls":19, "beams":7}
print(elements)
x = elements.copy() print(x)
x = elements.get("beams") print(x)
x = elements.items()
print(x) elements.update({"roof":5})
print(elements)
x = elements.pop("foundation")
print(x)
print(elements)

OUTPUT:

{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7}


{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7}
7
dict_items([('foundation', 14), ('floors', 3), ('walls', 19), ('beams', 7)])
{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7, 'roof': 5}
14
{'floors': 3, 'walls': 19, 'beams': 7, 'roof': 5}
RESULT:
Thus the python program to implement elements of a civil structure using dictionary was
written and executed successfully.
EXPT.NO 6
(A) Implementing Factorial Programs Using Functions.
DATE:

AIM:

To write a Python function to calculate the factorial of a number

PROCEDURE:

Step 1: Get a positive integer input (n) from the user.


Step 2: Check if the values of n equal to 0 or not if it's zero it will return 1
Otherwise else statement can be executed.
Step 3: Using the below formula, calculate the factorial of a number n*factorial(n-1)
Step 4: Print the output i.e the calculated.

PROGRAM:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

n = int(input("Input a number to compute the factorial: "))


print(factorial(n))

OUTPUT:

Input a number to compute the factorial: 5


120

RESULT:
Thus the Python Program to find factorial of a given number using function was written and
executed successfully.
EXPT.NO 6 B Implementing Program Largest Number In A List Using Function
DATE:

AIM:
To Write a Python program to get the largest number from a list.

PROCEDURE:
Step1: Start the program Step2: Take a list of values
Step3: using max () function finds first largest number
Step4: using remove () function remove first largest largest function
Step5: Again using max () function finds second largest number
Step6: print the two largest number
Step7: End the program

PROGRAM:
integers = [1, 16, 3, 39, 26, 4, 8, 16]
copy_of_integers = integers[:]
largest_integer = max(copy_of_integers)
copy_of_integers.remove(largest_integer)
second_largest_integer = max(copy_of_integers)
print(largest_integer)
print(second_largest_integer)

OUTPUT:
39
26

RESULT:
Thus the Python Program to find two largest numbers in a list using functions was written
and executed successfully.
EX. NO:6.c. Implementing Area of shape programs using Functions
DATE:

AIM:
To write a Python Program to find area of shape using functions.

ALGORITHM:

Step 1: Get the input from the user shape’s name.


Step 2: If it exists in our program then we will proceed to find the entered shape’s area
according to their respective formulas.
Step 3: If that shape doesn’t exist then we will print “Sorry!
Step 4: Stop the program

PROGRAM:
def calculate_area(name):
name = name.lower()

if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print(f"The area of the rectangle is {rect_area}.")

elif name == "square":


s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"The area of the square is {sqt_area}.")

elif name == "triangle":


h = int(input("Enter triangle's height: "))
b = int(input("Enter triangle's base length: "))
tri_area = 0.5 * b * h
print(f"The area of the triangle is {tri_area}.")

elif name == "circle":


r = int(input("Enter circle's radius: "))
pi = 3.14
circ_area = pi * r * r
print(f"The area of the circle is {circ_area}.")

elif name == "parallelogram":


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height: "))
para_area = b * h
print(f"The area of the parallelogram is {para_area}.")

else:
print("Sorry! This shape is not available.")

if __name__ == "__main__":
print("Calculate Shape Area")
shape_name = input("Enter the name of the shape whose area you want to find: ")
calculate_area(shape_name)

OUTPUT:
Calculate Shape Area
Enter the name of the shape whose area you want to find: RECTANGLE
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of the rectangle is 150.

RESULT:
Thus the Python Program to find area of shape using functions was written and executed
successfully.
EX. NO:7.a. Implementing Reverse string programs using Strings
DATE:

AIM:

To write a Python Program to reverse a string.

ALGORITHM:

STEP1:Start the program

STEP2:Define a function name myfunction ()


STEP3: Enter text to reverse
STEP4: Reverse the string using slice statement [::-1]
STEP5: Print the reversed string
STEP6: End the program

PROGRAM:
def my_function(x): return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)

OUTPUT:
sdrawkcab ekil skool txet siht woh rednow I

RESULT:
Thus the Python Program to reverse a string was written and executed successfully.
EX. NO:7.b. Implementing Palindrome programs using Strings
DATE:

AIM:

To write a Python Program to find palindrome for the given string.

ALGORITHM:

STEP1: Start the program


STEP2: Get the string from the user
STEP3: Check given string is equal to slice statement
STEP4: Print string is palindrome or else not palindrome
STEP5: Stop the program.

PROGRAM:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
print(string[::-1])
else:
print("Not a palindrome")
print(string[::-1])

OUTPUT:
Enter a string:qwert Not a palindrome Trewq

Enter a string:malayalam The string is a palindrome Malayalam

RESULT:
Thus the Python Program to find palindrome for the given string was written and executed
successfully.
EX. NO:7.c. Implementing Character Count programs using Strings
DATE:

AIM:
To write a Python Program to count the given character.

ALGORITHM:

STEP1: Start the program


STEP2: Assign the sentence to the variable
STEP3: Get the character from the user
STEP4: count the character using count ()
STEP5: print the number of occurrences of character
STEP6: Stop the program

PROGRAM:
message = 'python is popular programming language'
print('Number of occurrence of p:',
message.count('p'))

OUTPUT:
Number of occurrence of p: 4

RESULT:
Thus the Python Program to count the given character was written and executed successfully.
EX. NO:7.d. Implementing Replacing Characters programs using Strings
DATE:

AIM:

To write a Python Program to replace the character.

ALGORITHM:

STEP1: Start the program


STEP2: Get a string from the user
STEP3: Get a replace character from the user and replace the character using replace ()
STEP4: print the string
STEP5: Stop the program

PROGRAM:
a_string = "aba"
a_string = a_string.replace("a", "b")
print(a_string)

OUTPUT:
bbb

RESULT:
Thus the Python Program to replace the character was written and executed successfully.
EX. NO:8.a. Implementing Pandas programs using written modules and
DATE: Python Standard Libraries

AIM:

To implement pandas using written modules and Python Standard Libraries

ALGORITHM:

STEP1: Start the program


STEP2: import pandas library
STEP3: create alias for pandas
STEP4: create a simple pandas series from a list
STEP5: store the series in variable
STEP6: print the series using variable
STEP7: Stop the program

PROGRAM:
import pandas as pd
S = pd.Series([11, 28, 72, 3, 5, 8])
print(S)

OUTPUT:
0 11
1 28
2 72
3 3
4 5
5 8

Dtype : int64

RESULT:
Thus implemented pandas using written modules and Python Standard Libraries was
written and executed successfully.
EX. NO:8.b. Implementing Numpy programs using written modules and
DATE: Python Standard Libraries

AIM:
To implement Numpy using written modules and Python Standard Libraries.

ALGORITHM:

STEP1: Start the program


STEP2: Import numpy library
STEP3: create alias for numpy
STEP4: create an array of list
STEP5: Print the array
STEP6: print the shape of array
STEP7: Stop the program

PROGRAM:
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array print(a.shape)
b = a[1:, 2:]
print(b)

OUTPUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]

RESULT:
Thus implemented Numpy using written modules and Python Standard Libraries was written
and executed successfully.
EX. NO:8.c. Implementing Matplotlib programs using written modules and
DATE: Python Standard Libraries.

AIM:

To implement matplotlib using written modules and Python Standard Libraries

ALGORITHM:

STEP1: Install Matplotlib


STEP2: Import pyplot and create alias for it.
STEP3: Define the x-axis and corresponding y-axis values as lists.
STEP4: Plot and name them using plt.xlabel () and plt.ylabel () functions
STEP5: Give a title to your plot using .title () function.
STEP6: Finally, to view your plot using show () function.

PROGRAM:
from matplotlib
import pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='r',width=.1)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Audi", color='b',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance(kms)')
plt.title('Information')
plt.show()

OUTPUT:

RESULT:
Thus implemented matplotlib using written modules and Python Standard Libraries was
written and executed successfully.
EX. NO:8.d. Implementing Scipy programs using written modules and Python
DATE: Standard Libraries

AIM:
To implement Scipy using written modules and Python Standard Libraries.

ALGORITHM:

STEP1: Install Scipy library and import special function


STEP2: using special function calculate exponential, sin and cos values
STEP3: Print the values.

PROGRAM:
from scipy import special a = special.exp10(3)
print(a)
b = special.exp2(3) print(b)
c = special.sindg(90) print(c)
d = special.cosdg(45) print(d)

OUTPUT:
1000.0
8.0
1.0
0.707106781187

RESULT:
Thus implemented Scipy using written modules and Python Standard Libraries was written
and executed successfully.
EX. NO:9.a. Implementing real-time/technical applications to copy from one
DATE: file to another using File Handling

AIM:
To write a python program to copy from one file to another using file handling.

ALGORITHM:

Step 1: Start
Step 2: Open first.txt in read mode and read the contents of first.txt.
Step 3: Open second.txt in append mode and append the content of first.txt into second.txt.
Step 4: Stop

PROGRAM:

with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:


for line in firstfile:
secondfile.write(line)

OUTPUT:

first.txt
Welcome to Sree Sakthi Engineering college

second.txt
open second file ( all lines are copied successful )
Welcome to Sree Sakthi Engineering college

RESULT:

Thus, the python program to copy from one file to another using file handling was written
and executed successfully.
EX. NO:9.b. Implementing real-time/technical applications for word count
DATE: using File Handling

AIM :

To write a python program to count the words in a file using file handling.

ALGORITHM:
Step 1: Start
Step 2: Open the file in read mode and handle it in text mode.
Step 3: Read the text using read() function.
Step 4: Split the text using space separator.
Step 5: Refine the count by validating the words after splitting.
Step 6: Print the number of words in the text file.
Step 7: Stop

PROGRAM:

file = open("first.txt", "rt") data = file.read()


words = data.split()
print('Number of words in text file :', len(words))

OUTPUT:

first.txt
Welcome to Sree Sakthi Engineering college
Number of words in text file : 6

RESULT:

Thus, the python program to count the words in a file using file handling was written and
executed successfully.
EX. NO:9.c. Implementing real-time/technical applications for longest word
DATE: using File Handling

AIM:

To write a python program to find the longest word in a file using file handling.

ALGORITHM:

Step 1: Start
Step 2: Read the file which contains the text
Step 3: Open the file in the read mode
Step 4: Read and split the words in the file
Step 5: calculate the length of the words
Step 6: compare the length of the words and return the longest word.
Step 7: Stop

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('first.txt'))

OUTPUT:

first.txt
Welcome to Sree Sakthi Engineering college ['Engineering,']

RESULT:

Thus, the python program to find the longest word in a file using file handling was written and
executed successfully.
EX. NO:10.a. Implementing real-time/technical applications for Divide by Zero
DATE: Error using Exception Handling

AIM:

To write a python program to demonstrate the divide by zero error using Exception Handling.

ALGORITHM:

Step 1: Start
Step 2: Get inputs from the user, two numbers.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step 6: Stop

PROGRAM:

try:
num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except Value Error as e:
print("Invalid Input Please Input Integer...")
except Zero Division Error as e:
print(e)

OUTPUT:

Enter First Number: 5


Enter Second Number: 0
division by zero

RESULT:

Thus, the python program to demonstrate the divide by zero error using Exception Handling
was written and executed successfully.
EX. NO:10.b. Implementing real-time/technical applications for voter’s age
DATE: validity using Exception Handling

AIM:

To write a python program to validate voter’s age using Exception Handling.

ALGORITHM:

Step 1: Start
Step 2: Get the age as input
Step 3: If the entered value is a value apart from number, throw an exception
Step 4: If the value is less than zero, print an error message.
Step 5: If the value is number, check whether the number is greater than or equal to 18.
Step 6: If the age is 18, print able to vote else print not able to vote
Step 7: Stop

PROGRAM:

age = int(input("Enter your age: "))

if age >= 18:


print("Eligible to vote.")
else:
print("Not eligible to vote.")

OUTPUT:

Enter your age: 18


Eligible to vote.

RESULT:

Thus, the python program to validate voter’s age using Exception Handling was written
and executed successfully.
EX. NO:10.c. Implementing real-time/technical applications for student mark
DATE: range validation using Exception Handling

AIM:

To write a python program to validate the student mark range using Exception Handling.

ALGORITHM:

Step 1: Start
Step 2: Read the mark
Step 3: Check whether the marks is less than zero and greater than 100 and print the result
Step 4: Stop

PROGRAM:
mark = int(input("Enter the mark: "))

if 0 <= mark <= 100:


print("Valid mark.")
else:
print("Invalid mark.")

OUTPUT:

Enter the mark: 80


Valid mark.

RESULT:

Thus, the python program to validate the student mark range using Exception Handling was
written and executed successfully.

You might also like