python lab manual (2)
python lab manual (2)
DATE:
AIM:
ALGORITHM:
FLOW CHART:
START
IF
Units<=1
PayAmount=units*1.5
elif
unit<=20
PayAmount=(100*1.5)+(units-
100)*2.5
elif
unit<=30
PayAmount=(100*1.5)+(200- 100)*2.5+(units-200)*4
elif unit<=35
PayAmount=(100*1.5)+(200- 100)*2.5+(300-200)*4+(units-3
PayAmount=1500
STOP
[0,3.5,4.6,6.6]]
Bill = 0
Bill = 0
elif(Unit<=2
00):
Bill = (Unit-
100)*L[1][1]
elif(Unit<=500):
Bill = 100*L[2][1]+(Unit-200)*L[2][2]
else:
Bill = 100*L[3][1]+300*L[3][2]+(Unit-500)*L[3][3]
OUTPUT:
=====
Result:
Thus the program for calculating electricity bill has been executed successfully.
EX NO: 1.B
DATE
:
RETAIL SHOP BILLING
AIM:
ALGORITHM:
Assign tax=0.5
Assign
Rate={“Shirt”:250,”Teashirt”:20,”
Read
Tr quantity of all items from
ackpant”:150,”Saree”:650}
Calcula
te
cost=Shirtl*Rate[“Shirtl”]
+Teashirt*Rate[“Tea shirt”]
+Saree*Rate[“Saree”]+Trackpant*Rate[
Calculate Bill=cost+cost*tax
Print Bill
STOP
#program for calculating retail shop billing in Python
tax=0.5
Rate={"SHIRT":250,"SAREE":650,"TEASHIRT":150,"TRACKPANT":150}
items:\n")) SHIRT=int(input("SHIRT:"))
SAREE=int(input("SAREE:"))
TEASHIRT=int(input("TEASHIRT:"))
TRACKPANT=int(input("TRACKPANT:"))
cost=SHIRT*Rate["SHIRT"]+SAREE*Rate["SAREE"]+TEASHIRT*Rate["TEASHIRT"]+TRACK
PANT*Rate["TRACKPANT"]
Bill=cost+cost*tax
%f"%Bill) OUTPUT:
items:3 SHIRT:1
SAREE:1
TEASHIRT:1
TRACKPANT:0
Result:
Thus the program for calculating retail shop billing has been executed successfully.
EX NO: 1.C)
DATE :
AIM:
ALGORITHM:
FLOWCHART:
START
Read Diameter
Calculate
Weight=(D*D)/162
STOP
#program for calculating Weight of a Steel Bar in Python
OUTPUT:
Result:
Thus the program to calculating Weight of a Steel Bar has been executed
successfully.
EX NO: 1.D)
DATE :
AIM:
ALGORITHM:
FLOWCHART: START
Read Watts,
Calculate
power=√3 *
Print
STOP
PROGRAM:
: ")) CL = P/(math.sqrt(3)*VL*pf)
OUTPUT:
python current.py
Result:
DATE :
AIM:
ALGORITHM:
FLOWCHART:
START
Read ,X and
y values
Exchange or Swapping
values x,y =y,x
STOP
PROGRAM:
value : "))
print("Value 2= ",var2)
OUTPUT:
Enter value :
15 Enter
value : 10
Original
values : Value
1= 15
Value 2= 10
Program #swapping the values
var1 =10
var2 = 15
var1 print("Swapped
1 = ",var1)
print("Value 2 =
",var2)
OUTPUT:
Swapped values :
Value 1 = 15
Value 2 = 10
Result:
Thus the program to Exchange the values of two Variables has been executed
successfully.
EX NO: 2.b
DATE:
AIM:
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:
START
Read the
values of n
STOP
PROGRAM:
def circulate(A,N):
for i in
range(1,N+1):
B=A[i:]+A[:i]
print("Circulation",i,"=",
B) return
A=[91,92,93,94,95]
N=int(input("Enter
n:")) circulate(A,N)
OUTPUT:
Enter n:5
Result:
Thus the program to circulate the values of n variables has been executed
successfully
EX NO: 2.c
DATE:
AIM:
ALGORITHM:
1. Start the program
2. Read the value of x1,x2,y1 and y2
3. Calculate distance=√((𝑥2 − 𝑥1) ∗∗ 2) − ((𝑦2 − 𝑦1) ∗∗ 2)
4. Print the distance
5. Stop the program
START
FLOWCHART:
Calculate distance
y1 = int(input("y1 = "))
y2 = int(input("y2 = "))
round(dist,2)) OUTPUT:
x1 = 50
y1 = 758
x2 = 25
y2 = 50
Result:
Thus the program to Distance between two points has been executed successfully
EX NO: 3.a
DATE:
NUMBER SERIES
AIM:
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:
START
Read the
values of n
While
Sum=sum+i*i
Print sum
STOP
PROGRAM:
n = int(input('Enter a
i=1
while i<=n:
sum=sum+
i*i i+=1
print('Sum = ',sum)
OUTPUT:
Enter a number:
10 Sum = 385
Result:
Thus the program to calculate number series has been executed successfully.
EX NO: 3.b
DATE
: NUMBER PATTERN
AIM:
ALGORITHM:
1. Start the program
2. Read the number of rows to print from user
3. Print the pattern using for loops
4. Stop the program
FLOWCHART: START
Read Number
of rows
Print n
STOP
PROGRAM:
for n in range(1,N+1,1):
(1,n+1,1):
print(n, end="
")
print()
OUTPUT:
: 5 Number Triangle :
22
333
4444
55555
Result:
DATE
: PYRAMID PATTERN
AIM:
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
PROGRAM:
for n in range(1,N+1,1):
print(" "*(N-n),end="")
print(" * "*((2*n)-1))
OUTPUT:
: 5 Pyramid Star
pattern :
** *
** * * *
** * * * * *
** * * * * * * *
Result:
AIM:
ALGORITHM:
1. Start the program
2. Declare variable library to list the items present in a library
3. Do the operations of list like append, pop, sort, remove, etc on the list
4. Print the result.
5. Stop the program.
PROGRAM:
library
=['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebo
print('first element:
',library[0]) print('fourth
element: ',library[3])
',library.index('Newspaper')) library.sort()
library); library.remove('Maps')
print('after removing \'Maps\':
OUTPUT:
Result:
Thus the program to Items present in library has been executed successfully.
EX NO: 4.b
COMPONENTS OF A CAR
AIM:
ALGORITHM:
1. Start the program
2. Declare a list variable car to list the components of a car
3. Print the elements of list
4. Stop the program
PROGRAM:
def fnPrint(L):
for ele in L:
if(isinstance(ele,dict)):
for k, v in (ele.items()):
".join(v)) continue
print("\
Components:",)
fnPrint(Car_Main_components)
print("Car
Auxiliaries:")
fnPrint(Car_Auxiliarie
s) OUTPUT:
Chassi
Engine
Car Auxiliaries:
instrument panel
electric windows
system
Result:
4.c DATE:
ALGORITHM:
1. Start the program
2. Declare a dictionary building to list the elements of a civil structure
3. Do the dictionary operations add, update, pop and length
4. Print the result
5. Stop the program
Ceme
nt
Bricks
Block
Wooden Products
Hardware and
Fixtures Natural
Stones
Doors
Windo
ws
Modular
Kitchen Sand
Aggregates
Electrical
materials Tiles
BuildingMaterials = ('Cement', 'Bricks', 'Blocks', 'Wooden Products',
'Hardware and Fixtures', 'Natural Stones','Doors', 'Windows', 'Modular
Kitchen', 'Sand','Aggregates',
'Tiles')
print("Building Materials :
",BuildingMaterials) print("Electrical
Materials : ",ElectricalMaterials) #
# length of tuple
# Concat, repetition
print("Concatenation operation")
AllMaterials = BuildingMaterials+ElectricalMaterials
print("All materials")
print(AllMaterials)
print("Repetition
operation")
print(AllMaterials*2)
# Membership operator
print("Material present in
tuple.")
else:
# Iteration operation
print("Iteration operation")
print(mat)
OUTPUT:
Created tuple :
Electrical Materials : ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular
switches and sockets', 'Electric Panels', 'Switch Gear')
Length of tuple : 12
Concatenation
operation All
materials
('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures', 'Natural
Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles', 'Conduit
Pipes and Fittings', 'Wires and Cables', 'Modular switches and sockets', 'Electric
Panels', 'Switch Gear')
Repetition operation
Result:
Thus the program to Materials required for construction of a building has been
executed successfully.
EX NO: 5.A
COMPONENTS OF AN AUTOMOBILE
AIM:
ALGORITHM:
PROGRAM:
car =
{'Engine','Battery','Alternator','Radiator','Steering','Break','Seat
motorbike={'Engine','Fuel tank','Wheels','Gear','Break'}
motorbike
#union operation
#Symmetric difference
OUTPUT:
('Union of car and motorbike: ', set(['Engine', 'Alternator', 'Gear', 'Radiator', 'Seat
Belt', 'Battery', 'Fuel tank', 'Break', 'Wheels', 'Steering']))
Result:
Thus the program to Components of an automobile of a building has been executed
successfully.
EX NO: 5.B
AIM:
ALGORITHM:
PROGRAM:
building={1:'foundation',2:'floor',3:'beams',4:'columns',5:'roof',6:'stair'
} #Elements in dictionary
#length of a dictionary
6 :stair as lift
building.update({6:'lift'})
building[7]='window'
building.pop(3)
OUTPUT:
'roof')
('After updation of stair as lift: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5:
'roof', 6: 'lift'})
('After removing element beams from building: ', {1: 'foundation', 2: 'floor', 4: 'columns',
5: 'roof', 6:
'lift', 7: 'window'})
Result:
Thus the program to elements of a civil structure has been executed successfully.
EX NO: 6
FACTORIAL OF A NUMBER
AIM:
ALGORITHM:
PROGRAM:
def fnfact(N):
if(N==0):
return
1 else:
return(N*fnfact(N-1))
: "))
OUTPUT
Enter Number : 5
Factorial of 5 is
120 Result:
DATE:
AIM:
ALGORITHM:
PROGRAM:
def
maximum(list)
: return
max(list)
list=[]
n=int(input("Enter no.of
elements:"))
print("Enter",n,"elements")
i=0
for i in range(0,n):
element=int(inpu
t())
list.append(eleme
nt)
Enter no.of
elements:5 ('Enter',
5, 'elements')
65
78
52
99
56
Result:
Thus the program to finding largest number in a list has been executed successfully.
EX NO: 6 c
AIM:
ALGORITHM:
PROGRAM:
# Functions
# Area of a
shape def
fnSquare(s):
return (s*s)
def
fnRectangle(l,b):
return
(l*b) def
fnCircle(r):
return
3.142*r*r def
fnTriangle(base,ht):
return 0.5*base*ht
# square
s = eval(input("Enter side of square : "))
print("Area of rectangle
=",fnRectangle(l,b)) print("Area of
triangle =",fnTriangle(base,ht))
OUTPUT:
25
Area of rectangle =
25 Area of circle =
78.55 Area of
triangle = 12.5
Result:
Thus the program Area of shapes in a list has been executed successfully.
EX NO: 7
a. REVERSE OF A STRING
AIM:
ALGORITHM:
PROGRAM:
s=input("Enter a string:")
print("Reversed string
is:",s[::-1]) OUTPUT:
NOHTYP')
Result:
ALGORITHM:
PROGRAM:
s1=input("Enter a
string:") s2=s1[::-1]
if list(s1)==list(s2):
print("It is a
palindrome") else:
OUTPUT:
Enter a string:
'PYTHON' It is not a
palindrome Enter a
string: 'MADAM' It is a
palindrome
Result:
Thus the program checking palindrome in a string has been executed successfully.
Ex No: 7c
Date:
AIM:
ALGORITHM:
PROGRAM:
char=input("Enter a character/substring to
OUTPUT:
Result:
Thus the program counting character in a string has been executed successfully.
Ex No: 7d
Date:
AIM:
ALGORITHM:
PROGRAM:
print(string.replace(str1,
str2)) OUTPUT:
Result:
Thus the program Replacing characters in a string has been executed successfully.
Ex No: 7d
Date:
8.A) PANDAS
AIM:
To write a python program to compare the elements of the two Pandas Series
using Pandas
library.
ALGORITHM:
PROGRAM:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7,
10]) print("Series1:")
print(ds1)
print("Series2:
") print(ds2)
print("Compare the elements of the said
Series:") print("Equals:")
print(ds1 == ds2) print("Greater
than:") print(ds1 > ds2)
print("Less than:") print(ds1 <
ds2)
OUTPUT:
Series1:
0 2
1 4
2 6
3 8
4 10
dtype:
int64
Series2:
0 1
1 3
2 5
3 7
4 10
dtype: int64
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 the program Replacing characters in a string has been executed successfully.
EX NO:8.B
DATE:
NUMPY
AIM:
To write a program to test whether none of the elements of a given array is zero
using
NumPy library.
ALGORITHM:
PROGRAM:
import numpy as np
x = np.array([1, 2, 3,
4]) print("Original
array:") print(x)
is zero:") print(np.all(x))
x = np.array([0, 1, 2,
3]) print("Original
array:") print(x)
OUTPUT:
Original array:
[1 2 3 4]
[0 1 2 3]
Result:
Thus the program Replacing characters in a string has been executed successfully.
EX NO:8. C
DATE
MATPLOTLIB
AIM:
To write a python program to plot a graph using matplotlib library.
ALGORITHM:
PROGRAM:
import matplotlib.pyplot
xpoints = np.array([0,
6]) ypoints =
np.array([0, 250])
plt.plot(xpoints,
ypoints) plt.show()
OUTPUT:
Result:
.
EX NO:8. D
DATE
SCIPY
AIM:
To write a python program to return the specified unit in seconds (eg. Hour
returns 3600.0) using scipy library.
ALGORITHM:
PROGRAM:
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')
Result:
.
EX NO:9.A
DATE
AIM:
To write a python program to copy from one file to another.
ALGORITHM:
PROGRAM:
print("File copied
successfully!")
c=open(destinationfile, "r")
print(c.read())
c.close
()
print()
print()
OUTPUT:
successfully!
ROSE
JASMINE SUN
FLOWER
Result:
Thus the program copy from one file to another has been executed successfully
.
EX NO:9.B
DATE:
AIM:
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk.
They can be easily retrieved when required. Python supports two types of files. They
are Text files & Binary files.
ALGORITHM:
PROGRAM:
file = open("F:\Data.txt",
words = data.split()
OUTPUT:
Result:
Thus the program word count from a file has been executed successfully
9.C) FINDING LONGEST WORD IN A FILE
AIM:
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk. They
can be easily retrieved when required. Python supports two types of files. They are
Text files & Binary files.
ALGORITHM:
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'))
OUTPUT:
['collection']
Result:
Thus the program finding longest word in a file has been executed
successfully
EX No: 10
Date:
AIM:
To write a python program to handle divide by zero error using exception
handling.
ALGORITHM:
PROGRAM:
value of d:"))
c:")) try:
q=n/(d-c)
print("Quotient:",
q)
except
ZeroDivisionError:
print("Division by
Zero!")
OUTPUT:
Division by Zero!
('Quotient:', 4)
Result:
Thus the program handle divide by zero error using exception handling has
been executed successfully
10.B) VOTER’S AGE VALIDITY
AIM:
ALGORITHM:
PROGRAM:
import datetime
current_year = datetime.datetime.now().year
Current_age = current_year-Year_of_birth
if(Current_age<=18):
OUTPUT:
Result:
Thus the program voter’s age validity has been executed successfully
10.C) STUDENT MARK RANGE VALIDATION
AIM:
ALGORITHM:
PROGRAM:
Mark = int(input("Enter the Mark: "))
if Mark < 0 or Mark > 100:
print("The value is out of range, try again.")
else:
OUTPUT:
Result:
Thus the program student mark range validation has been executed successfully
11. EXPLORING PYGAME
PYGAME INSTALLATION
In order to install Pygame, Python must be installed already in your system. To check
whether Python is installed or not in your system, open the command prompt and give
the command as shown below.
To install Pygame, open the command prompt and give the command as shown
below:
Result:
BOUNCING BALL
AIM:
To write a python program to create bouncing ball game activity using pygame
PROGRAM:
import pygame
pygame.init()
window_w = 800
window_h = 600
black = (0, 0, 0)
FPS = 120
pygame.display.set_caption("Game: ")
clock = pygame.time.Clock()
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
velocity[0] = -velocity[0]
velocity[1] = -velocity[1]
# DRAW
window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size, block_size])
pygame.display.update()
clock.tick(FPS)
game_loop()
OUTPUT:
Result:
Thus the program bouncing ball game has been executed successfully