GE3171-Lab Manual-PYTHON REG 2021
GE3171-Lab Manual-PYTHON REG 2021
B.TECH- AI&DS
I Year/I Semester
LAB MANUAL
Prepared By,
LIST OF EXPERIMENTS
12. Developing a game activity using Pygame like bouncing ball, car race etc.
EX. NO:1a Identification and solving of simple real life or scientific or technical
problems and developing flow charts for the Electricity Billing
DATE:
AIM:
ALGORITHM:
Step1: Start.
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:
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 technical
problems and developing flow charts for the Retail Shop Billing
DATE:
AIM:
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 Step5: Calculate the total cost of the products.
Step6: Print total
Cost.
Step7: Stop.
PSEUDOCODE:
RESULT:
Thus, the flowchart for retail shop billing is developed.
EX. NO:1c. Identification and solving of simple real life or scientific or technical
problems and developing flow charts for the Sin Series
DATE:
AIM:
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+1and
increment iby 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,
nPRINT
x, n
CONVERT x =x * 3.1412/180
SUBSTITUTE t=x,
sum=xFORi=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:
AIM:
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 350pounds 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 410pounds 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 430pounds 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
PRINT Average weight=600pounds
ENDIF
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 technical
problems and developing flow charts for the Weight of a steel bar
DATE:
AIM:
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 by162, 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:
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 technical
problems and developing flow charts for the Compute Electrical Current
DATE: in Three Phase AC Circuit
AIM:
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:
RESULT:
Thus, the flowchart for computing the electric current in three phase AC circuit is developed.
EX No: 2 Python Programming using simple statements and expressions (Exchange
the values of two variables, circulate the values of n variables, distance between two
points)
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
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
successfully.
Ex No 2b:Circulate the values of n variables
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 thelist1
STEP7: Continue until range (0 to 3) exit.
STEP8: End the program.
PROGRAM:
no_of_terms = int(input("Enter number of
values:")) list1 = []
for val in range(0,no_of_terms,1):
ele=int(input("Enter integer:"))
list1.append(ele)
print("Circulating the elements of list",list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values
: 4Enter integer : 5
Enter integer :
3 Enter integer
: 6 Enter
integer : 1
Circulating the elements of list [5, 3, 6, 1]
[3, 6, 1, 5]
[6, 1, 5, 3]
[1, 5, 3, 6]
[5, 3, 6, 1]
RESULT:
Thus the Python Program to circulate the values of n variables was written and executed successfully.
Ex No 2c: Distance between two points
AIM:
To write a Python Program to find the distance between two points.
ALGORITHM:
PROGRAM:
import math
p1=[4, 0]
p2=[6, 6]
distance=math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-
p2[1])**2))
print(distance)
OUTPUT:
6.324555320336759
RESULT:
Thus the Python Program to find the distance between two points was written and executed
successfully.
Ex No: 3 Scientific problems using Conditionals and Iterative loops. (Number series,
Number Patterns, pyramid pattern
AIM
ALGORITHM
PROGRAM:
a=0
b=1
n=int(input("Enter the number of terms in the sequence:"))
print(a,b,end="")
while(n-2):
c=a+b
a,b=b,c
print(c,end="")
n=n-1
OUTPUT:
RESULT:
Thus the python program to print number series was written and executed successfully.
Ex No 3b: Number Patterns
AIM:
ALGORITHM:
STEP1: Start
STEP4: Using for loop print str (i) values i times in every iteration
PROGRAM:
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:4.a.(i) Implementing real-time/technical applications Items present in a
Libraryusing Lists
DATE:
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
Step3:Perform all the list
operation
Step4:Print the result
Step5:End the program
PROGRAM:
librarycomp=['books', 'newspaper', 'computer', 'magazine',
'journals']print(librarycomp)
print(librarycomp[0]) print(librarycomp[1])
print(librarycomp.index('computer'))
print(len(librarycomp))
librarycomp.append('projects')
print(librarycomp)
librarycomp.insert(2,'newsletter')
print(librarycomp)
librarycomp.remove('projects')
print(librarycomp) librarycomp.pop(2)
print(librarycomp) librarycomp[2]='library
attendance' print(librarycomp)
librarycomp.sort()
print("After sorting: ",librarycomp)
librarycomp.reverse() print("Reversed list: ",
librarycomp)New = librarycomp[:]
print(New)x = slice(2)
print(librarycomp[x])
test_list1 = ['books', 'newspaper', 'computer', 'magazine',
'journals']test_list2 = ['project’,’ newsletter']
for i in test_list2 :
test_list1.append(
i)
print("Concatenated list using naive method : ", str(test_list1))
OUTPUT:
RESULT:
Thus the Python program to implement items present in a Library using List was written and executed
successfully.
EX. NO:4.a.(ii) Implementing real-time/technical applications Items present in a
Libraryusing Tuples
DATE:
AIM:
To write a python program to implement items present in a Library using Tuples.
ALGORITHM:
Step1: Start the program
Step2: Assign list of library materials
PROGRAM:
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
PROGRAM:
carparts =['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']print(carparts)
print(carparts[0]) print(carparts[1])
print(carparts.index('Wheel'))
print(len(carparts))
carparts.append('Headlights')
print(carparts)
carparts.insert(2,'Radiator')
print(carparts)
carparts.remove('Headlights')
print(carparts) carparts.pop(2)
print(carparts) carparts[2]='Tyre'
print(carparts)
carparts.sort()
print("After sorting: ",carparts) carparts.reverse()
print("Reversed list: ", carparts)New = carparts[:]
print(New)x = slice(2)
print(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:
'Engine','Gear','Transmission','Tyre'] Reversed
list:['Tyre','Transmission', 'Gear','Engine','Brake','Battery']
['Tyre', 'Transmission']
RESULT:
Thus the python program to implement components of a car using List was written and executed
successfully.
EX. NO:4.b.(ii) Implementing real-time/technical applications Components of a car using
Tuples
DATE:
AIM:
To write a python program to implement components of a car using Tuples.
ALGORITHM:
Step1: Start the program
Step2: Assign list of car parts
Step3: Perform all the Tuples operation
Step4: Print the result
Step5: End the program
PROGRAM:
carparts=('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery')
print('Our tuple is: ',carparts)
print('Item in the first position is: ',carparts[0])
print('Item in the 5th position is: ',carparts[4])
indexOfWheel=carparts.index('Wheel')
print('Index of Wheel is: ', indexOfWheel)
lengthcarpartsTuple = len(carparts)
print('Length of the carparts tuple is: ',lengthcarpartsTuple)for item in carparts:
print(item)
print(carparts*2)
print(carparts[1:4])
if "Brake" in carparts:
print("Brake is available in the carparts tuple")else:
print("Brake is not available in the carparts tuple")
OUTPUT:
Our tuple is:('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake',
'Battery')Itemin the first position is: Engine
Itemin the 5th position is:
BrakeIndex of Wheel is: 2
Length of the carparts tuple
is: 6Engine
Transmissio
nWheel
Gear
Brake
Batter
y
('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery', 'Engine', 'Transmission', 'Wheel', 'Gear',
'Brake', 'Battery')('Transmission', 'Wheel', 'Gear')
Brake is available in the carparts tuple
RESULT:
Thus the python program to implement components of a car using Tuples was written and executed
successfully.
EX. NO:4.c.(i) Implementing real-time/technical applications Materials required for
construction of a building using Lists
DATE:
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
PROGRAM
buildingconstructions=['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']
print(buildingconstructions)
print(buildingconstructions[0])
print(buildingconstructions[1])
print(buildingconstructions.index('sand'))
print(len(buildingconstructions))
buildingconstructions.append('wood')
print(buildingconstructions)
buildingconstructions.insert(2,'marbles')
print(buildingconstructions)
buildingconstructions.remove('wood')
print(buildingconstructions)
buildingconstructions.pop(2)
print(buildingconstructions)
buildingconstructions[2]='tiles'
print(buildingconstructions)
buildingconstructions.sort()
print("After sorting: ",buildingconstructions)
buildingconstructions.reverse()
print("Reversed list: ", buildingconstructions)
New = buildingconstructions[:]
print(New)x = slice(2)
print(buildingconstructions[x])
test_list1 = ['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']
test_list2 = ['sand','wood','marbles','tiles']
fori in test_list2 :
test_list1.append(i)
print("Concatenated list using naive method : ", str(test_list1))
OUTPUT:
RESULT:
Thus the python program to implement materials required for construction of a building using List was
written andexecuted successfully.
EX. NO:4.c.(ii) Implementing real-time/technical applications Materials required for
construction of a building using Tuples
DATE:
AIM:
To write a python program to implement materials required for construction of a building using Tuples.
ALGORITHM:
Step1: Start the program
Step2: Assign list of building
PROGRAM:
buildingconstruction=('bricks', 'cement', 'sand', 'water', 'gravels', 'steel')
print('Our tuple is:',buildingconstruction)
print('Item in the first position is: ',buildingconstruction[0])
print('Item in the 5th position is: ',buildingconstruction[4])
indexOfwater=buildingconstruction.index('water') print('Index of
water is: ', indexOfwater) Tuplelength=len(buildingconstruction)
print('Length of the buildingconstruction tuple is: ',Tuplelength)
for item in buildingconstruction:
print(item)
print(buildingconstruction*2)
print(buildingconstruction[1:4])
if "brick" in buildingconstruction:
print("bricks is available in the buildingconstruction tuple")
else:
print("bricks is not available in the buildingconstruction tuple")
OUTPUT:
Our tuple is: ('bricks', 'cement', 'sand', 'water', 'gravels',
'steel')Item in the first position is: bricks
Item in the 5th position is: gravels
Index of water is: 3
Length of the building construction tuple
is: 6bricks
cementsand
water gravels
steel
('bricks', 'cement', 'sand', 'water', 'gravels', 'steel', 'bricks', 'cement', 'sand', 'water', 'gravels', 'steel')
('cement', 'sand', 'water')
bricks is not available in the buildingconstruction tuple
RESULT:
Thus the python program to implement materials required for construction of a building using Tuples
was written andexecuted successfully.
EX. NO:5.a.(i)
Implementing real-time/technical applications Language using Sets
DATE:
AIM:
ALGORITHM:
PROGRAM:
language1={'C','C++','JAVA'}
language2={'VB','PYTHON','ORACLE','JAVA'}
print(language1)
print(language2)
language1.add('SQL')
print(language1)
language1.remove('SQL')
print(language1)
print(language1 | language2)
print(language2.union(language1))
print(language1 & language2)
print(language1.intersection(language2))
print(language1 -language2)
print(language2.difference(language1))
print(language1 ^ language2)
OUTPUT:
RESULT:
Thus the python program to implement language using set was written and executed successfully.
EX. NO:5.a.(ii) Implementing real-time/technical applications Language usingDictionaries
DATE:
AIM:
ALGORITHM:
PROGRAM:
print(language)
x=
language.copy()
print(x)
x = language.get("PYTHON")
print(x)
x = language.items()
print(x)
language.update({"JAVA":5})
print(language)
x=
language.pop("C")
print(x)
print(language)
x = language.setdefault ("C++", 5)
print(x)
print(language)
x=
language.values()
print(x)
y=5
thisdict = dict.fromkeys(language, y)
print(thisdict)
x=
language.keys()
print(x)
language.clear()
print (language)
OUTPUT:
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 components of an
automobile using Sets
DATE:
AIM:
ALGORITHM:
PROGRAM:
components1={'Engine','Chassis','Transmission'}
components2={'Steering','Tire','Engine'}
print(components1)
print(components2)
components1.add('Gearbox')
print(components1)
components1.remove('Gearbox')
print(components1)
print(components1 |
components2)
print(components2.union(components1))
print(components1 & components2)
print(components1.intersection(components2))
print(components1 - components2)
print(components2.difference(components1))
print(components1 ^ components2)
OUTPUT:
RESULT:
Thus the python program to implement components of an automobile using set was written and executed
successfully.
EX. NO:5.b.(ii) Implementing real-time/technical applications components of an
automobile using Dictionaries
DATE:
AIM:
ALGORITHM:
PROGRAM:
x = components.items()
print(x)
components.update({"color": "White"})
print(components)
x=
components.pop("Break")
print(x)
print(components)
x = components.setdefault("Break", "Tire")
print(x)
print(components)
x=
components.values()
print(x)
y=1
thisdict = dict.fromkeys(components, y)
print(thisdict)
x=
components.keys()
print(x)
components.clear()
print(components)
OUTPUT:
RESULT:
Thus the python program to implement components of an automobile using dictionary was written and
executed successfully.
EX. NO:5.c.(i) Implementing real-time/technical applications Elements of a civil
structure using Sets
DATE:
AIM:
ALGORITHM:
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(elements1 |
elements2)
print(elements2.union(elements1))
print(elements1 & elements2)
print(elements1.intersection(elements2))
print(elements1 - elements2)
print(elements2.difference(elements1))
print(elements1 ^ elements2)
OUTPUT:
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 Elements of a civil
structure using Dictionaries.
DATE:
AIM:
ALGORITHM:
PROGRAM:
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)
x = elements.setdefault ("foundation", 5)
print(x)
print(elements)
x = elements.values()
print(x)
y=5
thisdict = dict.fromkeys(elements, y)
print(thisdict)
x = elements.keys()
print(x)
elements.clear()
print(elements)
OUTPUT:
RESULT:
Thus the python program to implement elements of a civil structure using dictionary was written and
executed successfully.
EX. NO:6.a
Implementing Factorial of given number programs using Functions
DATE:
AIM:
To write a Python Program to find factorial of a given number using function.
ALGORITHM:
STEP1: Start the program
STEP2: Define a function name factorial ()
STEP3: Assign or Get the value of n from
the user.STEP3: Return 1 if n==1 or 0(since
1! &0! is 1) STEP4: Else compute n *
factorial (n - 1)
STEP5: Print the factorial value for a given
numberSTEP6: End the program
PROGRAM:
def factorial(n):
return 1 if(n==1 or n==0) else n *factorial(n
- 1);num = 5;
print("Factorial
of",num,"is",
factorial(num))
OUTPUT:
Factorial of 5 is 120
RESULT:
Thus the Python Program to find factorial of a given number using function was written and executed
successfully.
EX. NO:6.b.
Implementing two Largest numbers in a list programs using Functions
DATE:
AIM:
To write a Python Program to find two largest numbers in a list using functions.
ALGORITHM:
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
functionStep5: 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_intege
r)
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
executedsuccessfully.
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:
PROGRAM:
def areacalculator():
_input_ = input("Enter the shape you want to calculate area of: ")
area = 0
pie = 3.14
if _input_ == "Square":
side = int(input("Enter the value of
side: "))area = area + (side ** 2)
elif _input_ == "Circle":
radius = int(input("Enter the value of
radius: "))area = area + (2 * pie * radius)
elif _input_ == "Rectangle":
length = int(input("Enter the value of
length: ")) width = int(input("Enter the
value of length: ")) area = area + (length *
width)
elif _input_ == "Triangle":
base = int(input("Enter the value of base: "))
height = int(input("Enter the value of
height: "))area = area +(0.5 * base * height)
else:
print ("Select a valid shape")
print ("%.2f" % area)
areacalculator()
OUTPUT:
Enter the shape you want to calculate area of:
SquareEnter the value of side: 3
9.00
Enter the shape you want to calculate area of:
squareSelect a valid shape
0.00
RESULT:
Thus the Python Program to find area of shape using functions was written and executed sucessfully.
EX. NO:7.a.
Implementing Reverse string programs using Strings
DATE:
AIM:
ALGORITHM:
reverse
PROGRAM:
def
my_function(x)
:return x[::-1]
mytxt = my_function("I wonder how this text looks like
backwards")print(mytxt)
OUTPUT:
sdrawkcabekilskooltxetsihtwohrednow 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:
ALGORITHM:
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:qwertNot 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:
ALGORITHM:
using count ()
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:
ALGORITHM:
user
STEP3: Get a replace character from the user and replace the character using
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 Python
Standard Libraries
DATE:
AIM:
ALGORITHM:
for pandas
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
executedsuccessfully.
EX. NO:8.b. Implementing Numpy programs using written modules and Python
Standard Libraries
DATE:
AIM:
To implement Numpy using written modules and Python Standard Libraries.
ALGORITHM:
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
executedsuccessfully.
EX. NO:8.c. Implementing Matplotlib programs using written modules and Python
Standard Libraries.
DATE:
AIM:
ALGORITHM:
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 andexecuted successfully.
EX. NO:8.d. Implementing Scipy programs using written modules and Python Standard
Libraries
DATE:
AIM:
ALGORITHM:
STEP2: using special function calculate exponential, sin and cos values
PROGRAM:
from scipy
import speciala =
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
executedsuccessfully.
EX. NO:9.a. Implementing real-time/technical applications to copy from one file to
another using File Handling
DATE:
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:
OUTPUT:
first.txt
second.txt
open second file ( all lines are copied successful )
Welcome to Grace College of Engineering, Mullakkadu, Tuticorin
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 using File
Handling
DATE:
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
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 using File
Handling
DATE:
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
textStep 3: Open the file in the read
mode
Step 4: Read and split the words in the
fileStep 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 Grace College of Engineering, Mullakkadu,
Tuticorin['Engineering,']
RESULT:
Thus, the python program to find the longest word in a file using file handling was written and
executedsuccessfully.
EX. NO:10.a. Implementing real-time/technical applications for Divide by Zero Error
using Exception Handling
DATE:
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 ValueError as e:
print("Invalid Input Please Input
Integer...")except ZeroDivisionError as
e:
print(e)
OUTPUT:
RESULT:
Thus, the python program to demonstrate the divide by zero error using Exception Handling was
written andexecuted successfully.
EX. NO:10.b. Implementing real-time/technical applications for voter’s age validity using
Exception Handling
DATE:
AIM:
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
exceptionStep 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:
while
True:
try:
age = int(input("Please enter your
age: "))except ValueError:
print("Sorry, I didn't understand
that.")continue
if age < 0:
print("Sorry, your response must not be
negative.")continue
else:
break
if age >= 18:
print("You are eligible to
vote!")else:
print("You are not eligible to vote.")
OUTPUT:
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 range
validation using Exception Handling
DATE:
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 resultStep 4: Stop
PROGRAM:
while True:
studentmark = int(input("Enter the student
Mark: "))if studentmark< 0 or studentmark>
100:
print("The student Mark value is out of range, try
again.")else:
print("The student Mark entered is
Valid.")break
OUTPUT:
RESULT:
Thus, the python program to validate the student mark range using Exception Handling was
written and executedsuccessfully.
EX. NO:11 Exploring Pygame tool
DATE:
AIM:
PYGAME:
Pygame is a set of Python modules designed to make games. It uses SDL which
is a cross platform librarythat abstracts the multimedia components of a computer as
audio and video and allows an easier development of programs that uses these
resources.
INSTALLATION:
Before starting the installation process, you must have python installed at your
system. The pygameinstallation itself can be different from an OS.
pip install pygame
HELLO WORLD:
As usual, when learning something new in programming we start as small as
possible to check it everythingis working properly before proceeding with the
studies. To make that let’s create a file called hello.py with the following content:
# -*- coding:
utf- 8 -*-import
time import
pygame
pygame.init
()
screen =
pygame.display.set_mode([640,
480])
pygame.display.set_caption('Hello
World') screen.fill([0, 0, 0])
pygame.display.flip(
)time.sleep(5)
Then just need to run it. So, the result will be this:
The first three lines are common to the most programs written in python. At the first
line, we define the fileencoding used by the python interpreter which was utf-8. This line
is most common at codes written in python 2 thathas non-ASCII characters, if you are
using python3 you probably won’t use it because utf-8 is the default encodingalready. The
second and third code lines are importing the python libraries that will be responsible for
all the magic. The command pygame.init() starts all modules that need initialization inside
pygame.
At pygame.display.set_mode we create an area for the game window at the size of
640x480 pixels, followedby pygame.display.set_caption where we set the value “Hello
World” to our window title.
With the window created we can use the command fill from screen to fill it with the
black color. The colorsare passed on a list of three elements that represent the values from
RGB. Each value can go from 0 to 255. You canchange the values to see by yourself the
window changing its color.
The command pygame.display.flip represents an important concept to pygame and
game development itself.
When we use commands to draw at the screen, we are actually drawing a virtual surface
at the memory that represents a portion of our actual screen. To make that drawing
visible to the user we need to send it to the actual screen, and we do it in these two
separate steps to prevent from displaying incomplete frames to the user. It is likedrawing
at a board and then “flipping it” to people see what we drew.
And then, to finish the command sleep from the library time makes the program
to wait 5 seconds beforefinish the execution. Otherwise, the program would close before
we see the result.
RESULT:
Thus, the Pygame tool is explored.
4931_Grace College of Engineering,Thoothukudi
EX. NO: 12. a Developing a game activity using Pygame like bouncing ball
DATE:
AIM:
To write a Python program to develop a bouncing ball gaming activity
using Pygame.
ALGORITHM:
Step 1: import
pygame,sys,time modulesStep
2: Make pygame.init() function
call
PROGRAM:
import
pygame, sys,
time from
pygame.locals
import *from
time import *
pygame.init()
screen = pygame.display.set_mode((500, 400))
GE3171_PSPP LAB
4931_Grace College of Engineering,Thoothukudi
GE3171_PSPP LAB
4931_Grace College of Engineering,Thoothukudi
pygame.event.
get():if
event.type ==
QUIT:
pygam
e.quit()
sys.exit
()
OUTPUT:
RESULT:
GE3171_PSPP LAB