0% found this document useful (0 votes)
3 views

python lab manual (2)

The document outlines various Python programs for different applications including electricity billing, retail shop billing, calculating the weight of a steel bar, and computing electrical current in a 3-phase AC circuit. Each program includes an algorithm, flowchart, and code implementation, demonstrating practical programming skills. Additionally, it covers operations on lists and various patterns using loops and conditionals.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python lab manual (2)

The document outlines various Python programs for different applications including electricity billing, retail shop billing, calculating the weight of a steel bar, and computing electrical current in a 3-phase AC circuit. Each program includes an algorithm, flowchart, and code implementation, demonstrating practical programming skills. Additionally, it covers operations on lists and various patterns using loops and conditionals.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

EX NO: 1 ELECTRICITY BILLING

DATE:

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, calculates the total amount of
consumed =units 0
4. If the unit consumed between101 to 200 units, calculates the total amount
of consumed=(101*1.5)+(unit-100)*2)
5. If the unit consumed between 201 to 500 units ,calculates total amount
of consumed=(101*1.5)+(200-100)*2+(units-200)*3
6. If the unit consumed between 300-350 units ,calculates total amoun of
consumed=(101*1.5)+(200-100)*2+(300-200)*4.6+(units-350)*5
7. If the unit consumed above 350 units, fixed charge – 1500/=
8. Stop the program
Tariff rates in TN

Scheme Unit Per unit(₹)


0 to 100 0-100 0
0 to 200 0-100 0
101-200 1.5
0 to 500 101-200 2
201-500 3
> 500 0-100 0
101-200 3.5
201-500 4.6
>500 6.6

FLOW CHART:
START

Read units of current


consumed

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

#program for calculating electricity bill in Python


Unit = int(input("Enter number of

units : ")) L = [[0],[0,1.5],[0,2,3],

[0,3.5,4.6,6.6]]

Bill = 0

if(Unit>=0 and Unit<=100):

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]

print("Unit :", Unit)

print("Bill : Rs.", Bill)

OUTPUT:

=====

Enter number of units

: 500 Unit : 500

Bill : Rs. 1100

Result:

Thus the program for calculating electricity bill has been executed successfully.
EX NO: 1.B

DATE
:
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, Teashirt, 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:
START

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}

print("Retail Bill Calculator\n")

Bill=int(input("Enter the quantity of the ordered

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

print("Please pay Rs.

%f"%Bill) OUTPUT:

Retail Bill Calculator

Enter the quantity of the ordered

items:3 SHIRT:1

SAREE:1

TEASHIRT:1

TRACKPANT:0

Please pay Rs.1575.000000

Result:

Thus the program for calculating retail shop billing has been executed successfully.
EX NO: 1.C)

DATE :

WEIGHT OF A STEEL BAR

AIM:

To write a python program to calculate weight of a steel bar.

ALGORITHM:

1. Start the program


2. Read the diameter (D) value from user
3. Calculate weight=(D*D)/162
4. Print the weight
5. Stop the program

FLOWCHART:
START

Read Diameter

Calculate

Weight=(D*D)/162

Print

STOP
#program for calculating Weight of a Steel Bar in Python

# Weight of a motor bike

Bike = {"Chopper":315, "Adventure bike":250, "Dirtbike":100, "Touring bike":400,


"Sport bikes":180, "Bagger":340, "Cruiser":250, "Cafe racer":200, "Scooter":115,
"Moped":80 }

B = input("Enter bike : ")

print("Weight of", B, "is", Bike[B],"kg.")

OUTPUT:

Enter bike : Touring bike

Weight of Touring bike is 400 kg.

Result:

Thus the program to calculating Weight of a Steel Bar has been executed
successfully.
EX NO: 1.D)

DATE :

COMPUTE ELECTRICAL CURRENT IN 3 PHASE AC CIRCUIT

AIM:

To write a python program to calculate electrical current in 3 phase AC circuit.

ALGORITHM:

1. Start the program


2. Get the input power in Watts
3. Read the value of power of factor
4. Read the value of Voltage form user
5. Calculate power= *volts*amperes
6. Print the value of Line current
7. Stop the program

FLOWCHART: START

Read Watts,

Calculate

power=√3 *

Print
STOP

PROGRAM:

# Electrical Current in Three Phase AC

Circuit import math

P = eval(input("Enter power (in Watts) : "))

pf = eval(input("Enter power factor (pf<1): "))

VL = eval(input("Enter Line Voltage (in Volts)

: ")) CL = P/(math.sqrt(3)*VL*pf)

print("Line Current =", round(CL,2),"A")

OUTPUT:

python current.py

Enter power (in Watts) : 5000

Enter power factor (pf<1):

0.839 Enter Line Voltage (in

Volts) : 400 Line Current = 8.6

Result:

Thus the program to Compute Electrical Current In 3 Phase Ac Circuit has


been executed successfully.
EX NO: 2.a

DATE :

PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE VALUES


OF TWO VARIABLES

AIM:

To write a python program to exchange the values of two variables.

ALGORITHM:

1. Start the program


2. Read the value of x and y
3. Exchange the values using the assignment statement x,y=y,x
4. Print the values
5. Stop the program

FLOWCHART:

START

Read ,X and
y values

Exchange or Swapping
values x,y =y,x

Print

STOP
PROGRAM:

# Exchange the values of two

variables var1 = int(input("Enter

value : "))

var2 = int(input("Enter value

: ")) print("Original values :

") print("Value 1= ",var1)

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, var2 = var2,

var1 print("Swapped

values : ") print("Value

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:

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:
START

Read the
values of n

Circulate the values in slice


operator

Print

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

('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])

Result:

Thus the program to circulate the values of n variables has been executed
successfully
EX NO: 2.c

DATE:

DISTANCE BETWEEN TWO VARIABLES

AIM:

To write a python program to calculate distance between 2 variables.

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:

Read the values X1,X2,Y1,Y2

Calculate distance

=√((𝑥2 − 𝑥1) ∗∗ 2) − ((𝑦2 − 𝑦1)


STOP
Print
PROGRAM:

# Distance between two

points import math

print("Enter coordinates for Point

1 : ") x1 = int(input("x1 = "))

y1 = int(input("y1 = "))

print("Enter coordinates for point

2 : ") x2 = int(input("x2 = "))

y2 = int(input("y2 = "))

dist = math.sqrt( ((x2-x1)**2) + ((y2-y1)**2) )

print("Distance between given points is",

round(dist,2)) OUTPUT:

Enter coordinates for Point 1 :

x1 = 50

y1 = 758

Enter coordinates for point 2 :

x2 = 25

y2 = 50

Distance between given points is 708.44

Result:

Thus the program to Distance between two points has been executed successfully
EX NO: 3.a

DATE:

PROGRAMS USING CONDITIONALS & ITERATIVE LOOPS

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:
START

Read the
values of n

Calculate sum number


series 12+22+32+….+N2

While

Sum=sum+i*i

Print sum

STOP
PROGRAM:

n = int(input('Enter a

number: ')) sum=0

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:

To write a python program to print number pattern.

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

Using for loop

Print n

STOP
PROGRAM:

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

")) print("Number Triangle : ")

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

for val in range

(1,n+1,1):

print(n, end="

")

print()

OUTPUT:

Enter number of Lines

: 5 Number Triangle :

22

333

4444

55555

Result:

Thus the program to Number pattern has been executed successfully.


EX NO: 3.c

DATE
: PYRAMID PATTERN

AIM:

To write a python program to print number pattern.

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:

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

")) print("Pyramid Star pattern : ")

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

print(" "*(N-n),end="")

print(" * "*((2*n)-1))
OUTPUT:

Enter number of Lines

: 5 Pyramid Star

pattern :

** *

** * * *

** * * * * *

** * * * * * * *

Result:

Thus the program to Pyramid Pattern has been executed successfully.


EX No: 4.A

DATE: OPERATIONS OF LIST

AIM:

To write a python program to implement operations in a library list.

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:

# declaring a list of items in a Library

library

=['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebo

oks'] print('Library: ',library)

print('first element:

',library[0]) print('fourth

element: ',library[3])

print('Items in Library from 0 to 4 index:

',library[0: 5]) library.append('Audiobooks')

print('Library list after append Audiobooks:

',library) print('index of \'Newspaper\':

',library.index('Newspaper')) library.sort()

print('after sorting: ', library);

print('Popped elements is:

',library.pop()) print('after pop(): ',

library); library.remove('Maps')
print('after removing \'Maps\':

',library) library.insert(2, 'CDs')

print('after insert CDs: ', library)

print(' Number of Elements in Library list : ',len(library))

OUTPUT:

('Library: ', ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps', 'Prints',


'Documents', 'Ebooks'])

('first element: ', 'Books')

('fourth element: ', 'Manuscripts')

('Items in Library from 0 to 4 index: ', ['Books', 'Periodicals', 'Newspaper',


'Manuscripts', 'Maps'])

('Library list after append Audiobooks: ', ['Books', 'Periodicals', 'Newspaper',


'Manuscripts', 'Maps', 'Prints', 'Documents', 'Ebooks', 'Audiobooks'])

("index of 'Newspaper': ", 2)

('after sorting: ', ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',


'Newspaper', 'Periodicals', 'Prints'])

('Popped elements is: ', 'Prints')

('after pop(): ', ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',


'Newspaper', 'Periodicals'])

("after removing 'Maps': ", ['Audiobooks', 'Books', 'Documents', 'Ebooks',


'Manuscripts', 'Newspaper', 'Periodicals'])

('after insert CDs: ', ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks',


'Manuscripts', 'Newspaper', 'Periodicals'])

(' Number of Elements in Library list : ', 8)

Result:

Thus the program to Items present in library has been executed successfully.
EX NO: 4.b

DATE: List operations

COMPONENTS OF A CAR

AIM:

To write a python program to implement operations in a car tuple

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:

Car_Main_components = ['Chassis', 'Engine', {'Body':['Steering system','Braking


system','Suspension']}, {'Transmission_System':
['Clutch','Gearbox','Differential','Axle']}]

Car_Auxiliaries = ['car lightening system','wiper and washer system','power door


locks system','car instrument panel','electric windows system','car park system']

def fnPrint(L):

for ele in L:

if(isinstance(ele,dict)):

for k, v in (ele.items()):

print("\t",k, ":", ",

".join(v)) continue

print("\

t",ele) print("Car Main

Components:",)

fnPrint(Car_Main_components)
print("Car

Auxiliaries:")

fnPrint(Car_Auxiliarie

s) OUTPUT:

Car Main Components:

Chassi

Engine

Body : Steering system, Braking system,

Suspension Transmission_System : Clutch,

Gearbox, Differential, Axle

Car Auxiliaries:

car lightening system

wiper and washer

system power door

locks system car

instrument panel

electric windows

system car park

system

Result:

Thus the program to components of a car has been executed successfully.


EX NO:

4.c DATE:

MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING AIM:

To write a python program to implement operations of dictionary.

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

Materials required for construction of a building

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')

ElectricalMaterials = ('Conduit Pipes and Fittings', 'Wires and Cables',


'Modular switches and sockets', 'Electric Panels', 'Switch Gear')

print("Created tuple : ")

print("Building Materials :

",BuildingMaterials) print("Electrical

Materials : ",ElectricalMaterials) #

Accessing elements by index

print("First element in tuple :

",BuildingMaterials[0]) print("Last element in

tuple : ",BuildingMaterials[-1]) # Slicing

print("First 5 elements in tuple : ",BuildingMaterials[0:5])

# length of tuple

print("Length of tuple : ",len(BuildingMaterials))

# Concat, repetition

print("Concatenation operation")

AllMaterials = BuildingMaterials+ElectricalMaterials

print("All materials")

print(AllMaterials)

print("Repetition

operation")

print(AllMaterials*2)

# Membership operator

SearchMaterial = input("Enter material to search : ")


if SearchMaterial in AllMaterials:

print("Material present in

tuple.")

else:

print("Material not present in tuple.")

# Iteration operation

print("Iteration operation")

print("Materials required for construction of a

building: ") for mat in AllMaterials:

print(mat)

OUTPUT:

Created tuple :

Building Materials : ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware


and Fixtures', 'Natural Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand',
'Aggregates', 'Tiles')

Electrical Materials : ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular
switches and sockets', 'Electric Panels', 'Switch Gear')

First element in tuple : Cement

Last element in tuple : Tiles

First 5 elements in tuple : ('Cement', 'Bricks', 'Blocks', 'Wooden Products',


'Hardware and Fixtures')

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

('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', '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')

Enter material to search : Natural

Stones Material present in tuple.

Result:
Thus the program to Materials required for construction of a building has been
executed successfully.
EX NO: 5.A

DATE: OPERATIONS OF SET

COMPONENTS OF AN AUTOMOBILE

AIM:

To write a python program to implement operations on an automobiles set.

ALGORITHM:

1. Start the program


2. Declare set variables car and motorbike to list the components of a car and
motorbike
3. Do the set operations union, intersection, difference and symmetric difference
4. Print the result
5. Stop the program

PROGRAM:

# declaring a set of Components of a car

car =

{'Engine','Battery','Alternator','Radiator','Steering','Break','Seat

Belt'} # declaring a set of Components of a motorbike

motorbike={'Engine','Fuel tank','Wheels','Gear','Break'}

# Elements of the set car

print('Components of Car: ',car)

#Elements of the set

motorbike

print('Components of motorbike: ',motorbike)

#union operation

print('Union of car and motorbike: ',car |

motorbike) #intersection operation

print('Intersection of car and motorbike: ',car & motorbike)


#difference operation

print('Difference operation: ', car - motorbike)

#Symmetric difference

print('Symmetric difference operation: ',car ^ motorbike)

OUTPUT:

('Components of Car: ', set(['Engine', 'Alternator', 'Radiator', 'Seat Belt',


'Battery', 'Break', 'Steering']))

('Components of motorbike: ', set(['Engine', 'Break', 'Wheels', 'Fuel tank', 'Gear']))

('Union of car and motorbike: ', set(['Engine', 'Alternator', 'Gear', 'Radiator', 'Seat
Belt', 'Battery', 'Fuel tank', 'Break', 'Wheels', 'Steering']))

('Intersection of car and motorbike: ', set(['Engine', 'Break']))

('Difference operation: ', set(['Alternator', 'Battery', 'Steering', 'Radiator', 'Seat Belt']))

('Symmetric difference operation: ', set(['Alternator', 'Gear', 'Radiator', 'Seat Belt',


'Battery', 'Fuel tank', 'Wheels', 'Steering']))

Result:
Thus the program to Components of an automobile of a building has been executed
successfully.
EX NO: 5.B

DATE: OPERATIONS OF DICTIONARY

ELEMENTS OF A CIVIL STRUCTURE

AIM:

To write a python program to implement operations of dictionary.

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

PROGRAM:

#declare a dictionary building

building={1:'foundation',2:'floor',3:'beams',4:'columns',5:'roof',6:'stair'

} #Elements in dictionary

print('Elements in dictionary building: ',building)

#length of a dictionary

print('Length of the dictionary building: ',len(building))

#value of the key 5

print('The value of the key

5',building.get(5)) #update key

6 :stair as lift

building.update({6:'lift'})

print('After updation of stair as lift: ',building)


#Add element window in the dictionary

building[7]='window'

print('After adding window: ',building)

#using pop operation to remove element

building.pop(3)

print('After removing element beams from building: ',building)

OUTPUT:

('Elements in dictionary building: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4:


'columns', 5: 'roof', 6: 'stair'})

('Length of the dictionary building:

', 6) ('The value of the key 5',

'roof')

('After updation of stair as lift: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5:
'roof', 6: 'lift'})

('After adding window: ', {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5:


'roof', 6: 'lift', 7: 'window'})

('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

DATE: PROGRAMS USING FUNCTIONS

FACTORIAL OF A NUMBER

AIM:

To write a python program to calculate the factorial of a number.

ALGORITHM:

1. Start the program


2. Read a number from user
3. If number=1, then return 1
4. Otherwise calculate the factorial of that number using recursive function
5. Print the result
6. Stop the program

PROGRAM:

def fnfact(N):

if(N==0):

return

1 else:

return(N*fnfact(N-1))

Num = int(input("Enter Number

: "))

print("Factorial of", Num, "is", fnfact(Num))

OUTPUT

Enter Number : 5

Factorial of 5 is

120 Result:

Thus the program to factorial of a number has been executed successfully.


EX NO: 6 b

DATE:

FINDING LARGEST NUMBER IN A LIST

AIM:

To write a python program to find the largest number in a list.

ALGORITHM:

1. Start the program


2. Read number of elements from user
3. Read the elements of list using for loop
4. Find the largest element from list using max() function
5. Print the result
6. Stop the program

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)

print("Largest element is:",maximum(list))


OUTPUT:

Enter no.of

elements:5 ('Enter',

5, 'elements')

65

78

52

99

56

('Largest element is:', 99)

Result:

Thus the program to finding largest number in a list has been executed successfully.
EX NO: 6 c

DATE: AREA OF SHAPES

AIM:

To write a python program to find the area of shapes.

ALGORITHM:

1. Start the program


2. Get the choice from user
3. If choice is 1, read side value and calculate area of square
4. If choice is 2, read length and breadth value and calculate area of rectangle
5. If choice is 3, read radius and calculate area of circle
6. If choice is 4, read breadth and weight value and calculate area of triangle
7. Print the result
8. Stop the program

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 : "))

l,b = map(int,(input("Enter length and breath of rectangle :

").split())) r = eval(input("Enter circle radius : "))

base,ht = map(int,(input("Enter base and height of triangle :

").split())) print("Area of square =",fnSquare(s))

print("Area of rectangle

=",fnRectangle(l,b)) print("Area of

circle =",fnCircle(r)) print("Area of

triangle =",fnTriangle(base,ht))

OUTPUT:

Enter side of square : 5

Enter length and breath of

rectangle : 5 5 Enter circle radius :

Enter base and height of

triangle : 5 5 Area of square =

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

DATE: PROGRAMS USING STRINGS

a. REVERSE OF A STRING

AIM:

To write a python program to reverse a string

ALGORITHM:

1Start the program

2. Read a string from user

3. Perform reverse operation

4. Print the result

5. Stop the program

PROGRAM:

s=input("Enter a string:")

print("Original string is:",s)

print("Reversed string

is:",s[::-1]) OUTPUT:

Enter a string: 'PYTHON PROGRAMMING'

('Original string is:', 'PYTHON PROGRAMMING')

('Reversed string is:', 'GNIMMARGORP

NOHTYP')

Result:

Thus the program Reverse of a string has been executed successfully.


EX NO: 7 b.

DATE: CHECKING PALINDROME IN A STRING AIM:

To write a python program to check whether a string is palindrome or not.

ALGORITHM:

1. Start the program


2. Read a string from user and store in variable s1
3. Perform reverse operation of s1 and store the reversed string in s2
4. Check whether the strings are equal or not
5. If both are equal print it is a palindrome. Otherwise print it is not a palindrome
6. Stop the program

PROGRAM:

s1=input("Enter a

string:") s2=s1[::-1]

if list(s1)==list(s2):

print("It is a

palindrome") else:

print("It is not a palindrome")

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:

COUNTING CHARACTER IN A STRING

AIM:

To write a python program to count number of characters in a string

ALGORITHM:

1. Start the program


2. Read a string from user
3. Read a substring/ character to count
4. Count the number of occurrence using count() method and print the result
5. Stop the program

PROGRAM:

txt =input("Enter a string: ")

char=input("Enter a character/substring to

count: ") x = txt.count(char)

print(“The no.of times”,char, “occurred is: ”,x)

OUTPUT:

Enter a string: "I love python programming, python is very

interesting subject" Enter a character/substring to count: 'python'

('The no.of times', 'python', 'occurred is:', 2)

Result:

Thus the program counting character in a string has been executed successfully.
Ex No: 7d

Date:

7d. REPLACING CHARACTERS IN A STRING

AIM:

To write a python program to replace characters in a string

ALGORITHM:

1. Start the program


2. Read a string from user
3. Read old string
4. Read new string to replace
5. Replace the old string with new string using replace() method
6. Print the result
7. Stop the program

PROGRAM:

string = input("Enter any

string: ") str1 = input("Enter

old string: ") str2 =

input("Enter new string: ")

print(string.replace(str1,

str2)) OUTPUT:

Enter any string: 'Problem solving and python

programming' Enter old string: 'python'

Enter new string: 'C'

Problem solving and C programming

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.

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

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 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:

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 of the array is zero or not
5. If it contains zero print False otherwise print True
6. Stop the program

PROGRAM:

import numpy as np

x = np.array([1, 2, 3,

4]) print("Original

array:") print(x)

print("Test if none of the elements of the said array

is zero:") print(np.all(x))

x = np.array([0, 1, 2,

3]) print("Original

array:") print(x)

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 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:

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 import numpy as np

xpoints = np.array([0,

6]) ypoints =

np.array([0, 250])

plt.plot(xpoints,

ypoints) plt.show()
OUTPUT:

Result:

Thus the program Matplotlib has been executed successfully

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

1. Start the program


2. Import scipy from python standard library
3. Print specified units like minute, hour, day, etc in seconds using scipy
4. Stop the program

PROGRAM:

from scipy import constants

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 the program Scipy has been executed successfully

.
EX NO:9.A

DATE

COPY FROM ONE FILE TO ANOTHER

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

ALGORITHM:

1. Start the program


2. Import copyfile from python standard libraries
3. Read source and destination file name
4. Copy data from source file to destination file and print ‘file copied successfully’
5. Stop the program

PROGRAM:

from shutil import copyfile

sourcefile = input("Enter source file name: ")

destinationfile = input("Enter destination file

name: ") copyfile(sourcefile, destinationfile)

print("File copied

successfully!")

c=open(destinationfile, "r")

print(c.read())

c.close

()

print()

print()
OUTPUT:

Enter source file name:

'file1.txt' Enter destination file

name: 'file2.txt' File copied

successfully!

ROSE

JASMINE SUN

FLOWER

Result:

Thus the program copy from one file to another has been executed successfully

.
EX NO:9.B

DATE:

WORD COUNT FROM A FILE

AIM:

To write a python program to count number of words in a file.

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:

1. Start the program


2. Open file from the specified path and read the data using read() method
3. Count the number of words using len() method and print the count
4. Stop the program

PROGRAM:

file = open("F:\Data.txt",

"rt") data = file.read()

words = data.split()

print('Number of words in text file :', len(words))

OUTPUT:

Number of words in text file : 36

Result:

Thus the program word count from a file has been executed successfully
9.C) FINDING LONGEST WORD IN A FILE

AIM:

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

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:

1. Start the program


2. Open 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'))

OUTPUT:

['collection']
Result:

Thus the program finding longest word in a file has been executed
successfully
EX No: 10

Date:

DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING

AIM:
To write a python program to handle divide by zero error using exception
handling.

ALGORITHM:

1. Start the program


2. Read the values for n,d and c
3. Calculate Quotient=n/(d-c) in try block
4. If zeroDivisionError arise print Division by Zero
5. Stop the program

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)

except

ZeroDivisionError:

print("Division by

Zero!")
OUTPUT:

Enter the value of n:8

Enter the value of d:4

Enter the value of c:4

Division by Zero!

Enter the value of n:8

Enter the value of d:4

Enter the value of c:2

('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:

To write a python program to check voter’s age validity.

ALGORITHM:

1. Start the program


2. Read year of birth from user
3. Calculate age by subtracting year of birth from current year
4. If Age is less than or equal to 18 print ‘You are eligible to vote’. Otherwise
print ‘You are not eligible to vote’
5. Stop the program

PROGRAM:

import datetime

Year_of_birth = int(input("In which year you took birth:- "))

current_year = datetime.datetime.now().year

Current_age = current_year-Year_of_birth

print("Your current age is ",Current_age)

if(Current_age<=18):

print("You are not eligible to vote")


else:

print("You are eligible to vote")

OUTPUT:

In which year you took birth:- 2004

('Your current age is ', 18)

You are not eligible to vote

In which year you took birth:- 1994

('Your current age is ', 28)

You are eligible to vote

Result:

Thus the program voter’s age validity has been executed successfully
10.C) STUDENT MARK RANGE VALIDATION
AIM:

To write a python program to perform student mark range validation

ALGORITHM:

1. Start the program


2. Read student mark from user
3. If the mark is in between 0 and 100 print “The mark is in the range”
4. Otherwise print “The value is out of range”
5. Stop the program

PROGRAM:
Mark = int(input("Enter the Mark: "))
if Mark < 0 or Mark > 100:
print("The value is out of range, try again.")
else:

print("The Mark is in the range")

OUTPUT:

Enter the Mark: 123

The value is out of range, try again.


Enter the Mark: 95

The Mark is in the range

Result:

Thus the program student mark range validation has been executed successfully
11. EXPLORING PYGAME

PYGAME INSTALLATION

Step 1: Check for Python 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.

Step 2: Check for PIP installation


PIP is a tool that is used to install python packages. PIP is automatically installed
with Python 2.7. 9+ and Python 3.4+. Open the command prompt and enter the
command shown below to check whether pip is installed or not.
Step 3: Install Pygame

To install Pygame, open the command prompt and give the command as shown
below:

pip install pygame

Now, Pygame installed successfully.

Result:

Thus the program py game has been executed successfully


12) GAME ACTIVITY USING PYGAME

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

white = (255, 255, 255)

black = (0, 0, 0)

FPS = 120

window = pygame.display.set_mode((window_w, window_h))

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:

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

quit()

pos_x += velocity[0]

pos_y += velocity[1]

if pos_x + block_size > window_w or pos_x < 0:

velocity[0] = -velocity[0]

if pos_y + block_size > window_h or pos_y < 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

You might also like