0% found this document useful (0 votes)
18 views107 pages

Emailing PYTHON LAB MANUAL (1 TO 50)

B.E B.Tech python record

Uploaded by

kvj1999.2000
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)
18 views107 pages

Emailing PYTHON LAB MANUAL (1 TO 50)

B.E B.Tech python record

Uploaded by

kvj1999.2000
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/ 107

SHREENIVASA ENGINEERING COLLEGE

(Approved by AICTE and Affiliated to Anna University)


B.Pallipatti, Bommidi, Pappireddipatti (Tk), Dharmapuri Dt, Tamilnadu-635 301

Department of Science and Humanities

GE3171 – PROBLEM SOLVING AND PYTHON


PROGRAMMING

NAME : …………………………………………….…….
REG NO : …………………………………………………..
COURSE : …………………………………………….…….

SEMESTER : …………………………………………….…….

BATCH : …………………………………………….……..
SHREENIVASA ENGINEERING COLLEGE
(Approved by AICTE and Affiliated to Anna University)
B.Pallipatti, Bommidi, Pappireddipatti (Tk), Dharmapuri Dt, Tamilnadu-635 301

NAME :

CLASS :

UNIVERSITY REG NO:

Certified that, this is a bonafide record of practical work


done by ……………………………………………………...… of
Department of Computer science and Engineering branch in
……………….……………………...………………………. Laboratory,
during …………… Semester of academic year 2022 - 2023.

Faculty in charge Head of the Department

Submitted during Anna University Practical Examination held on ………….…….

Internal Examiner External Examiner


INDEX
PAGE SIGN OF
S NO DATE NAME OF THE EXPERIMENT MARKS
NO FACULTY

1 DEVELOPING FLOWCHART

1.a ELECTRICITY BILL GENERATION

1.b RETAIL SHOP BILLING

1.c SINE SERIES

1.d WEIGHT OF A STEEL BAR

COMPUTE ELECTRICAL CURRENT IN


1.e
THREE PHASE AC CIRCUIT

2 PROGRAMS USING SIMPLE STATEMENTS

EXCHANGE THE VALUES OF TWO


2.a
VARIABLES

2.b DISTANCE BETWEEN TWO POINTS

CIRCULATE THE VALUES OF N


2.c
VARIABLES

3 PROGRAMS USING CONDITIONALS AND ITERATIVE STATEMENTS

3.a NUMBER SERIES

3.b NUMBER PATTERN

3.c PYRAMID PATTERN

4 OPERATIONS OF LISTS AND TUPLES

4.a LIBRARY MANAGEMENT SYSTEM


4.b COMPONENTS OF A CAR

MATERIALS REQUIRED FOR


4.c
CONSTRUCTION OF A BUILDING

5 OPERATIONS OF SETS AND DICTIONARIES

5.a COMPONENTS OF AUTOMOBILE

5.b ELEMENTS OF A CIVIL STRUCTURE

6 PROGRAMS USING FUNCTIONS

6.a FACTORIAL OF A NUMBER

6.b LARGEST NUMBER IN A LIST

6.c AREA OF SHAPE

7 PROGRAMS USING STRING

7.a CHECKING PALINDROME IN A STRING

7.b COUNTING CHARACTERS IN A STRING

7.c REPLACING CHARACTERS IN A STRING

8 PROGRAMS USING MODULES AND PYTHON STANDARD LIBRARIES

STUDENT MARK SYSTEM USING NUMPY


8.a
AND PANDAS

8.b LINEAR REGRESSION USING SCIPY

9 PROGRAMS USING FILE HANDLING


COPY THE CONTENT FROM ONE FILE TO
9.a
ANOTHER FILE

9.b WORD COUNT

9.c LONGEST WORD

10 PROGRAMS USING EXCEPTION HANDLING

10.a DIVIDE BY ZERO ERROR

10.b VOTERS AGE VALIDATION

10.c STUDENT MARK RANGE VALIDATION

11 PYGAME TOOL BASICS

12 BOUNCING BALL GAME USING PYGAME


EX.NO: 1 A
DATE: ELECTRICITY BILL GENERATION

AIM
To write a Python program to calculate electricity bill.

ALGORITHM
Step1: START
Step2: Read TNEB consumer number, last bill meter reading and current bill meter reading
as input.

Step3: Calculate consumed units:


consumed <- cur_reading-last_reading

Step4: IF (consumed <= 100 AND consumed>=0) then


fixed <- 0 slab1 <- 0 PRINT
(fixed) bill <- slab1+fixed
IF (consumed <= 200 AND consumed >=101) then
fixed <- 20
slab1 <- (consumed-100)*1.5
PRINT (slab1)
PRINT (fixed) bill
<- slab1+fixed
IF (consumed <= 500 AND consumed >=201) then
fixed <- 20 slab1 <- 0 PRINT
(slab1) slab2 <- 100*2 PRINT
(slab2)
slab3 <- (consumed-200)*3.0

PRINT (slab3)

PRINT (fixed)
bill <- slab1+slab2+slab3+fixed IF
(consumed > 500) then
fixed <- 50
slab1 <- 0 PRINT
(slab1) slab2 <-

1
100*3.5 PRINT
(slab2) slab3 <-
300*4.60 PRINT
(slab3)
slab4 <- (consumed-500)*6.60
PRINT (slab4)
PRINT (fixed)
bill <- slab1+slab2+slab3+slab4+fixed Step5:
Store the value of bill and display it.
Step6: Stop

PSEUDOCODE
TASK: Calculate electricity bill

BEGIN
READ TNEB consumer number, last bill meter reading and current bill meter reading
COMPUTE consumed units
Consumed=cur_reading-last_reading
END consumed units
IF (consumed <= 100 AND consumed>=0) THEN
fixed = 0 slab1 = 0 PRINT
(fixed) bill = slab1+fixed

END IF

IF (consumed<= 200 AND consumed >=101) THEN


fixed = 20 slab1 =
(consumed-100)*1.5
PRINT (slab1)

PRINT (fixed) bill

=slab1+fixed

END IF
IF (consumed <= 500 AND consumed >=201) THEN
fixed = 20 slab1 =
0 PRINT (slab1)
slab2 = 100*2 PRINT
2
(slab2) slab3 = (consumed-
200)*3.0
PRINT (slab3)
PRINT (fixed) bill =
slab1+slab2+slab3+fixed

END IF
IF (consumed > 500) THEN
fixed = 50 slab1 = 0
PRINT (slab1) slab2 =
100*3.5 PRINT (slab2)
slab3 = 300*4.60 PRINT
(slab3) slab4 = (consumed-
500)*6.60
PRINT (slab4)
PRINT (fixed)

3
END IF

bill = slab1+slab2+slab3+slab4+fixed

END TASK

FLOWCHART

START

Read Ebnum, previous reading ,


current reading

Consumed=current reading – previous reading

Cost=0
If consumed<=100
Fixed charges=0

Cost=(consumed -
If consumed>100 and 100)*1.5
consumed<=200
Fixed charges=20

If
Cost=(100*2)+((consumed
consumed>200
-200)*3)
and
consumed<=500 Fixed charges=30

4
PRINT bill

END

5
If Cost=(100*3.5)+(300*4.6)
+((consumed-500)*6.6)
consumed>500
Fixed charges=50

DISPLAY
consumed,cost,fixed

Bill_amount = cost+fixed
charges

DISPLAY
bill_amount

STOP

6
PROGRAM
eb_no=int(input("Enter the TNEB Number:"))

last_reading=int(input("Enter the last bill meter reading:")) current_reading=int(input("Enter

the current bill meter reading:")) consumed=current_reading-last_reading

print("-------SlabCalculations-------")

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

fixed=0 slab1=0 print("Slab

1-100 charge:",slab1)

print("Fixed charges",fixed)

bill=slab1+fixed

if (consumed<=200 and consumed>=101 ):

fixed=20 slab1=(consumed-

100)*1.50 print("Slab 1-100

charge:",slab1) print("Fixed

charges",fixed) bill=slab1+fixed

if (consumed<=500 and consumed>=201):

fixed=30 slab1=0 print("Slab

1-100 charge:",slab1) slab2=100*2

print("Slab 101-200 charge:",slab2)

slab3=(consumed-200)*3

print("Slab 201-500 charge:",slab3)

print("Fixed charges",fixed)

bill=slab1+slab2+slab3+fixed if

(consumed>500):

fixed=50 slab1=0 print("Slab 1-100

charge:",slab1) slab2=100*3.5

print("Slab 101-200 charge:",slab2)

slab3=300*4.6 print("Slab 201-500

charge:",slab3) slab4=(consumed-

500)*6.60 print("Slab greater than 500


7
charge",slab4) print("Fixed

charges",fixed)

bill=slab1+slab2+slab3+slab4+fixed

print(" TamilNadu Electricity Board ")

print("---------------------------------")

print("EB Number:",eb_no) print("Units

consumed",consumed)

print("Bill amount: Rs.",bill) print("----------------------------------")

8
OUTPUT

9
RESULT
Thus the program for calculating electricity bill is executed and output is verified
successfully.

10
EX.NO: 1 B
DATE: RETAIL STORE BILLING

AIM
To write a Python program to calculate retail store bill.

ALGORITHM
Step1: Start

Step2: Read name, mobile number and today’s date as input.

Step3: Set bill_amount<- 0 and create 3 empty lists Items, Qty and Price.

Step4: Get the choice from user and get the item name, price and quantity and append to their
respective lists.

Step5: To print the bill, print the customer’s name, mobile number and date. Then print the
product, quantity, price and bill of the respective item. Finally calculate total bill by adding all
the bill of the product chosen by user.

Step6: Stop

PSEUDOCODE
TASK: To calculate retail store bill

BEGIN

READ name, mobile number and today’s date

SET bill_amount=0

INTIALIZE Items=[], Qty=[], Price=[]

GET input from the user and append it to the list

PRINT bill_amount

END END TASK

11
FLOWCHART

START

Declare variables name,


mobilenum and date.

READ name
,mobilenum and date

Bill_amount=0

Item=[ ]

Qty=[ ] Price=[ ]

PRINT 1.Fruits
2.Vegetables 3.Cosmetics
4.Grains 5.Oil 6.Print the

READ op

If op==1 Item.apppend(Fruitname)
READ product
Price.append(Fruitprice)
name, quantity
Qty.append(FruitQty)
,price

If op==2 Item.apppend(Vegetablename
READ product
)
name, quantity
Price.append(Vegetableprice)
,price
Qty.append(VegetableQty)

12
If op==3 Item.apppend(Cosmeticsname)
READ product Price.append(Cosmeticsprice)
name, quantity Qty.append(CosmeticsQty)
,price

If op==4
READ product Item.apppend(Grains name)
name, quantity Price.append(Grains price)
,price Qty.append(GrainsQty)

If op==5 Item.apppend(Oilname)
READ Price.append(Oilprice)
product name, Qty.append(OilQty)
quantity ,price

IC in
range
(len(items)

PRINT
Item[IC],Qty[IC],Price
[IC],Price[IC]*Qty[IC
]

Bill_amount=Price[IC]
*Qty[IC]

13
PRINT
Bill_amount

STOP

14
PROGRAM
print("\t\tWelcome to \n***Kannan Departmental Store***")

print(" ------------------------------------")

name=input("Enter the customer name: ")

mobile=input("Enter the customer mobile number: ")

date=input("Enter todays date: ") bill_amount=0

Items=[]

Qty=[] Price=[]

print("***********Menu*************")

print('''

1. Fruits

2. Vegetables

3. Cosmetics

4. Grains

5. Oil

6. Exit

''')

op=int(input("Enter the option:"))

while op in [1,2,3,4,5]: if op==1:

FruitName=(input("Enter the Fruit Name : "))

Items.append(FruitName)

FruitPrice=float(input("Enter the Price(KG) : "))

Price.append(FruitPrice)

FruitQty=int(input("Enter the Quantity(KG) : ")) Qty.append(FruitQty) if op==2:

VegetableName=(input("Enter the Vegetable Name : "))

Items.append(VegetableName)

VegetablePrice=float(input("Enter the Price(KG) : "))

Price.append(VegetablePrice)

15
VegetableQty=int(input("Enter the Quantity(KG) : "))

Qty.append(VegetableQty) if op==3:

CosmeticName=(input("Enter the Cosmetic Name : "))

Items.append(CosmeticName)

CosmeticPrice=float(input("Enter the Price(unit) : "))

Price.append(CosmeticPrice)

CosmeticQty=int(input("Enter the Quantity(unit) : "))

Qty.append(CosmeticQty) if op==4:

GrainsName=(input("Enter the Grain Name : "))

Items.append(GrainsName)

GrainsPrice=float(input("Enter the Price(KG) : "))

Price.append(GrainsPrice)

GrainsQty=int(input("Enter the Quantity(Kg) : "))

Qty.append(GrainsQty) if op==5:

OilName=(input("Enter the Oil Name : "))

Items.append(OilName)

OilPrice=float(input("Enter the Price(Litre) : "))

Price.append(OilPrice)

OilQty=int(input("Enter the Quantity(Litre) : "))

Qty.append(OilQty) print("Do you have another item ,If yes print the

options or else enter 6")

print('''

1. Fruits 2. Vegetables

3. Cosmetics 4. Grains

5. Oil 6. Exit

''')

op=int(input("Enter the option:"))

print("\n*************Bill************") print("***Kannan

Departmental Store***")

print("----------------------------------------")
16
print("Date:%s"%date) print("Name of the

customer: %-20s"%name) print("Mobile

Number : %2s"%mobile)

print("-----------------------------------------")

print("Product\tQuantity\tPrice\tBill") for

IC in range(len(Items)):

print("{0:<10} {1:<8} {2:<7}


{3:<3}".format(Items[IC],Qty[IC],Price[IC],Price[IC]*Qty[IC]))

bill_amount+=(Price[IC]*Qty[IC])

print("-----------------------------------------")

print(f"Total bill: Rs.{bill_amount}")

print("-----------------------------------------") print("Thank

you... Visit Again!!!")

17
OUTPUT

18
RESULT
Thus the program for calculating retail shop bill is executed and output is
verifiedsuccessfully.

19
EX.NO: 1 C
DATE: SINE SERIES

AIM
To write a python program to calculate the sine series of a given number and terms.

ALGORITHM
Step1: Start

Step2: Define a fuction to find the factorial of a number given as terms

Step3: Define another function to find sine value of the given number

Step4: Get two variables for number of terms and value for sine variable

Step5: Pass the values respectively in the function defined

Step6: Initialize pi value

Step7: Convert the value of sine variables as radians using pi values

Step8: Display the result of sine series

Step9: Stop

PSEUDOCODE
TASK: To calculate the sine series

BEGIN

DEFINE a function to calculate factorial of the given number

DEFINE a function to calculate the sine series of the given number

READ sine, number of terms

PASS the values into the function

SET pi=3.14

PRINT the value of sine series

END END TASK

FLOWCHART

20
START

START
Factorial(n)

Factorial(n)

Sin(n)

Fact=1

Pi=3.14

i in
range(1,n+1)
Read x,n

Print x
Fact*=1

Print sin(x,n)
Return Fact

END
STOP

21
START

Sin(x,n)

Sine=0

j in
range(0,n)

Sign=(-1)**j

Sine=Sine+((X**(2.0*j+1))/factorial(2*j+1))*Sign

Return sine

STOP

PROGRAM
#Factorial of Given Number

def factorial(n):

res = 1

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

res *= i return res #sine function def sin(x,n):

sine=0 for i in range(0,n): sign=(-1)**i

sine=sine+((x**(2.0*i+1))/factorial(2*i+1))*sign

return sine
22
OUTPUT

23
#Get a inputs of degree and range from the user

x=int(input("Enter the value of x in degrees:")) n=int(input("Enter

the number of terms:"))

#Pi Value pi=22/7

#to convert degrees to radians you multiply the degrees

x*=(pi/180) print("the x value in radians=",x)

print("the value of sine series of ",n,"terms is =", round(sin(x,n),2))

RESULT
Thus the program for finding sine series is executed and output is verified successfully.

24
EX.NO: 1 D
DATE: WEIGHT OF A STEEL BAR

AIM
To write a Python program to find the total weight of the given steel bar.

ALGORITHM
Step1: Start

Step2: Read SteelDiameter, SteelLength as input

Step3: Assign variable Dsquare <-SteelDiameter*SteelLength

Step4: Calculate weight of steel bar per meter by dividing Dsquare with 162

Step5: Display weight of steel bar per meter

Step6: Calculate total weight of steel bar and display it

Step7: Stop

PSEUDOCODE
TASK: To find the total weight of a steel bar

BEGIN

READ steeldiameter, steellength,

SET Dsquare=steelDiameter*steelLength

COMPUTE weight of steelbar

Weightofsteelpermeter=Dsquare/162

END weight of steelbar

PRINT Weightofsteelpermeter

COMPUTE total weight

TotalWeightofSteel=(Dsquare*steelLength)/162

END total weight

PRINT TotalWeightofSteel

END

END TASK

25
FLOWCHART

START

Read SteelDiameter,
SteelLen

Dsquare=
SteelDiameter*SteelDiameter

Weight_of_steel_per_meter
= Dsquare/162

Total_weight_of_steel=(
Dsquare*SteelLen)/162

PRINT
Total_weight_of_steel

STOP

PROGRAM
SteelDiameter = int(input("Enter The Length of the Steel Diameter(mm):"))

SteelLen = int(input("Enter The Length of the Steel length(METER):"))

Dsquare = SteelDiameter * SteelDiameter

WeightofSteelPerMeter = Dsquare / 162 e =

"{:.2f}".format(WeightofSteelPerMeter)

26
OUTPUT

27
print("Weight Of Steel Bar per Meter:", e, "kg/m")

TotalWeightofSteel = (Dsquare * SteelLen) / 162

f = "{:.2f}".format(TotalWeightofSteel)

print("Total Weight Of Steel Bar:", f, "kg")

RESULT
The above program for finding the total weight of the given steel bar is executed and output is
verified successfully.

28
EX.NO: 1 E COMPUTEELECTRICAL CURRENT IN THREE
DATE: PHASE AC CIRCUIT

AIM
To write a Python program to compute electrical current in three phase AC circuit.

ALGORITHM
Step1: Start

Step2: Define a function to calculate root 3 value as Newton method Step3:

Define a function to calculate three phase electric current value

Step 4: Read voltage, current as input.

Step5: Display voltage and current.

Step6: Assign a variable root3 and call the function newton method and return root3 value
from the function.

Step 7: Display root 3 value

Step8: Display the calculated electric current in three phase electric AC current

Step9: Stop

PSEUDOCODE
TASK: To compute electrical current in three phase AC circuit

BEGIN

DEFINE function to calculate root3 value as newton number

DEFINE function to calculate three phase electric current

READ volage, current

PRINT voltage, current

PRINT root3

PRINT calculated electric current

END END TASK

FLOWCHART

29
START

Newton_method(num,num
_iters=100)

READ a

i in range
(num_iters)

Iternum=num

Num=0.5*(num+a/num)

Num==
Break
iternum

Return num

STOP

30
START
START

Newton_method(num,
num_iters=100)
Threephase(voltage,
current,root3)

Threephase(voltag
e,current,root3) Kva=voltage*current
*root3

Read
voltage,current

Return kva

Print
voltage,current
STOP

Root3=newton_method
(3)

Print threephase
(voltage,current,
root3)

STOP

PROGRAM
def newton_method(number, number_iters = 100):

31
a = float(number) for i in

range(number_iters):

iternumber=number number = 0.5 *

(number + a/ number) if

number==iternumber:

break

return number

def threephase(voltage,current,root3):

kva=voltage*current*root3

return kva

voltage = int(input("Enter the voltage: ")) current

= int(input("Enter the current: ")) print("Input

Voltage :",voltage,"Volts") print("Input current

:",current,"Amps")

root3=newton_method(3)

print("Computed Electrical Current in Three Phase AC


Circuit:",round(threephase(voltage,current,root3)),"KVA")

RESULT
Thus the program for computing electrical current in three phase AC circuit is executed and
output is verified successfully.

32
OUTPUT

33
EX.NO: 2 A
DATE: EXCHANGE THE VALUE OF TWO VARIABLES

AIM
To write a python program to exchange the value of given variables.

ALGORITHM
Step 1:Start

Step 2: Read variables V1 and V2 as input.

Step 3: Swapping using

i. Temporary variable ii.


XOR operator iii. Swap –
function iv. Addition and
Subtraction
Step 4: Initialize a temporary variable and swap values.

Step 5: Using XOR (^) operator swap the values.

Step 6: Define a function and swap the values.

Step 7: Using addition and subtraction swap the values.

Step 8: Stop

34
START

Read V1, V2

temp = V1

V1 = V2

V2 = temp

START
print V1, V2

swap_function(
V1 = V1^V2 V1,V2)
V2 = V1^V2

V1 = V1^V2
V1, V2 = V2,V1

print V1, V2

Return V1, V2

swap_function(V1,V2)

STOP
swap = swap_func(V1,V2)

V1 = swap[0]

V2 = swap[1]

print V1, V2

V1 = V1 + V2

V2 = V1 - V2
35 V2
V1 = V1 –
FLOWCHART
PROGRAM
print("Enter two values to swap")

V1 = int(input("Enter the Value-1 : " )) V2 =

int(input("Enter the Value-2 : ")) print("*"*40)

print("Before Swapping V1 is ",V1," V2 is

",V2) print("Swapping using temporary

variable...") temp = V1

V1 = V2 V2 = temp print("Value of V1 is {V1} and\nValue of V2 is

{V2}".format(V1=V1, V2=V2)) print("*"*40) print("Before Swapping V1 is

",V1," V2 is ",V2) print("Swapping using XOR operator...")

V1 = V1 ^ V2

V2 = V1 ^ V2 V1

= V1 ^ V2

print("Value of V1 is {V1} and\nValue of V2 is {V2}".format(V1=V1, V2=V2))

print("*"*40) print("Before Swapping V1 is ",V1," V2 is ",V2) def swap_func():

global V1, V2

print("swap_func function called...") V1, V2 = V2, V1 swap_func()

print("Value of V1 is {V1} and\nValue of V2 is {V2}".format(V1=V1, V2=V2))

print("*"*40)

print("Before Swapping V1 is ",V1," V2 is ",V2) print("Swapping

using Addition and difference...")

V1 = V1 + V2

V2 = V1 - V2 V1 = V1 - V2 print("Value of V1 is {V1} and\nValue of V2 is

{V2}".format(V1=V1, V2=V2))

36
RESULT
Thus, the program to exchange the value of given variables was executed and
output is verified successfully.

37
OUTPUT

38
EX.NO: 2 B
DATE: DISTANCE BETWEEN TWO POINTS

AIM
To write a python program to find distance between two points.

ALGORITHM
Step 1: Start

Step 2: Read point A, point B as input.

Step 3: Define a function newton_method to find root of the number.

Step 4: Define a function distance_between to calculate distance between two points.

Step 5: Assign a variable root_2 to call newton_method.

Step 6: Display the distance between two points.

Step 7: Stop

39
FLOWCHART
START

newton_method

(number, number_iters = 100)

Read x

i in range
(newton_method)
False

iternumberTrue
= number

number = 0.5 * (number + x/ number)

number == iternumber True


Break

False
return number

STOP

40
START START

newton_method distance_between(pointA,point
B)
(number, number_iters = 100)

distance_between(pointA,point x1,y2=pointA
B)
x2,y2=pointB

read
distx=x2-x1
pointA,pointB
disty=y2-y1

print root_2=newton_method(distx**2+disty**
distance_between 2)
(pointA,pointB

return
round(root_2,2)
STOP

STOP

PROGRAM
def newton_method(number):

x = float(number)

yn=number

for i in range(100):

41
yn1=yn yn

= 0.5 * (yn + x/ yn)

if yn==yn1:

break

return round(yn,2) def

distance_between(pointA, pointB):

x1, y1 = pointA

x2, y2 = pointB

distx = x2 - x1

disty = y2 - y1

return newton_method(distx**2 + disty**2) pointA =

int(input("Enter Xcordinate(x1) for PointA : ")), \

int(input("Enter Ycordinate(y1) for PointA : ")) pointB =

int(input("Enter Xcordinate(x2) for PointB : ")), \

int(input("Enter Ycordinate(y2) for PointB : "))

print(f"Distance Between Two points of {pointA, pointB} -> ", distance_between(pointA,


pointB))

RESULT
Thus, the python program to find distance between two points was executed and output is
verified successfully.

42
OUTPUT

43
EX.NO: 2 C
DATE: CIRCULATE THE VALUES OF N VARIABLES

AIM
To write a python program to get an input from user and circulate N values.

ALGORITHM
Step 1: Start

Step 2: Read n from the user.

Step 3: Create empty list, N values = []

Step 4: Get values from the user and append it to the list.

Step 5: Return the list and display.

Step 6: Pass the values from the user and print the values.

Step 7: Circulate the N values from the user and print the values.

Step 8: Print the circulated list in every circulation.

Step 9: Stop

44
FLOWCHART
START

Read n

Get n values (n)

list1 = get Nvalues(n)

Print lis1

Circulate (Nvalues)

Circulate (list1)

STOP

45
START
START

Get n values (n)


Get n values (n)

Nvalues = []
i in range (n)

False
i in range (n)

b = Nvalues[0]

Nvalues.pop(0)
True
Read a Nvalues.append(b)

Print N values
Nvalues.append(a)

STOP
Return N values

STOP

46
OUTPUT

47
PROGRAM
def circulate(alist): for i in

range(len(alist)):

first=alist.pop(0) alist.append(first)

print(f"Circulate {i+1} : {alist}")

return alist

def GetNValues(n):

NValues=[]

for i in range(n):

Value=input(f"Enter the Value {i+1} : ")

NValues.append(Value) return NValues

n=int(input("Enter Number of Values Want to circulate :"))

NValues=GetNValues(n)

print("\nGiven N Values : ", NValues) print("*"*15,"Circulate

the N Value","*"*15) circulate(NValues)

RESULT
Thus, thepython program to get an input from user and circulate N values was executed and
output is verified successfully.

48
EX.NO: 3 A
DATE: NUMBER SERIES

AIM
To write a program to find the number series.

ALGORITHM
Step 1: Start
Step 2: Read n value from the user
Step 3: Assign sum is 0
Step 4: IF choice == 1 THEN

FOR n in range(1,n+1)

sum <-sum+n

PRINT(sum) THEN

IF choice == 2 THEN

FOR n in range(1,n+1) THEN

sum<-sum+n**2

PRINT(sum)

IF choice == 3 THEN

FOR n in range(1,n+1) THEN

sum <- sum+N

PRINT(sum) Step
5: Stop

PROGRAM:
N = int(input("Enter a number of a element:")) choice

= int(input("""

Number Series

49
1.sum of the n=N series - 1+2+3+4...........N

2.sum of squares of the N series - (1*1)+(2*2)+(3*3)...........N

3.sum of N terms of the series - 1+(1+2)+........N

\n Enter your choice : """

sum = 0

if choice == 1:

for N in range(1,n+1)

sum +=N

print("\nsum of the N series - 1+2+3+4.........N:",sum)

if choice == 2:

for N in range(1,n+1)

sum +=N**2

print("\nsum of the (1*1)+(2*2)+(3*3)...........N :",sum)

if choice == 3:

for N in range(1,n+1)

sum +=N

print("\nsum of the terms of the series - 1+(1+2)+..........N:",sum)

RESULT
Thus, the above program for finding the number is executed and the output is verified
successfully.

50
OUTPUT

51
AIM
EX.NO:
DATE:
3B
NUMBER PATTERN

To write a program to find the number pattern.

ALGORITHM
Step1: Start

Step2: Take a value from the user and store it in a variable n.

Step3: IF choice ==1 THEN

FOR n in range(i,n+1) THEN

IF n%2! = 0 THEN

PRINT(n)

IF choice == 2 THEN

FOR n in range(1,n+1) THEN

IF N%2 == 0 THEN

PRINT(n) Step4:
Stop

PROGRAM
n = int(input("Enter the N value:)) choice

= int(input('''

Number Pattern

1.ODD Number N series pattern

2.EVEN Number N series pattern

\nEnter your choice:''')) if choice

== 1:

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

52
if n%2!=0:

print(n) if choice == 2:

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

if n%2 == 0:

print(n)

OUTPUT

RESULT
Thus, the program coding has been executed and output is verified successfully. 3 C
PYRAMID PATTERN

To write a program to find the pyramid pattern in python.

53
AIM
EX.NO:
DATE:
ALGORITHM
Step1: Start

Step2: Get the (N) height value of the pyramid rows from the user.

Step3: In the loop , we iterate from i = 0 to i = rows.

Step4: The second loop runs from j = 0 to i+1 .

Step5: Once the inner loop ends and we print new line and start printing * in a new line.

PROGRAM
N = int(input("Enter the N value:"))
print("\nPyramid pattern") for row
in range(N): for column in
range(row+1):
print("*",end=" ")

print("\n") print("\nStar
right triangle") for row in range(N):
for column in range(row+1):
print("*",end=" ")

RN = N-(row+1)

print("_"*RT, end=" ")


print("\r")

print("\nNumber pattern")
number = 1 for row in
range(N+1):

for column in range(1,row+1):


print(number, end=" ")
number+=1

54
print("\n") print("\nstring pattern")

asciivalue = 65 for row in range(N): for

column in range(0, row+1): alphabate =

chr(asciivalue) print(alphabate, end=' ')

asciivalue += 1

OUTPUT

RESULT
Thus, the programto find the pyramid pattern has been executed andoutput is verified
successfully.

4A
LIBRARY MANAGMENT SYSTEM

To write a program for the library management system.

55
AIM
EX.NO:
DATE:
ALGORITHM

Step 1: START

Step 2: READ the choice in the list from the user as an input.

Step 3:Declare the list of options in library like Add Book, View Book, Issue book,

Return book and Delete book

Step 4:Display the list of options to the user.

Step 5:Get the selection of items

Step 6:Based on the selection ask the item details

Step 7:Repeat step 4 for all the options selected by the user.

Step 8: Display, based on the options selected by the user

Step 9: STOP

PROGRAM
print("_"*50) print("\n"," "*10,"KiTE Library

Management System") print("_"*50)

BooksCatelogue=["PSPP","Maths I","English","Physics","Chemistry"] IssuedBook=[]

choice=int(input(('''

1.Add Book

2.Delete Book

3.View Book list

4.Issue Book

5.Return Book

Enter the choice : ''')))

56
while choice: if choice==1:

print("#"*20) print("

"*5,"Add Book")

print("#"*20)

getBookName=input("Enter Book Name : ")

BooksCatelogue.append(getBookName)

if choice==2:

print("#"*20) print("

"*5,"Delete Book")

print("#"*20)

getBookName=input("Enter Book Name : ")

BooksCatelogue.remove(getBookName) if

choice==3:

print(" "*5,"#"*20)

print("Available Book List")

print("#"*20)

for sno,book in enumerate(BooksCatelogue,start=1):

print(sno,"-",book,"-",BooksCatelogue.count(book),"Available")

if choice==4: print("#"*20) print(" "*5,"Issue Book")

print("#"*20)

57
getBookName=input("Enter Book Name : ")

IssuedBook.append(getBookName)

BooksCatelogue.remove(getBookName) if

choice==5: print("#"*20)

print(" "*5,"Return Book")

print("#"*20)

getBookName=input("Enter Book Name : ")

BookID=BooksCatelogue.index(getBookName)

BooksCatelogue.pop(BookID)

print("_"*50)

print("\n"," "*10,"KiTE Library Management System")

print("_"*50)

choice=int(input('''

0.Exit

1.Add Book

2.Delete Book

3.View Book list

4.Issue Book

5.Return Book

Enter the choice : '''))

58
OUTPUT

RESULT
Thus, the program for library management system is executed and output is verified
successfully.

4B

59
AIM
EX.NO:
DATE:
COMPONENTS OF A CAR

To write the program to check the working condition of car engine components in
percentage.

ALGORITHM

Step 1: START

Step 2:Declare the list of Engine Parts.

Step 3:Get the condition of parts in percentage.

Step 4:Calculate the total condition of parts.

Step 5:Calculate the Engine condition using the formula.


Engine Condition <-total / total number of parts used

Step 6:Display the Engine Working Condition in percentage.

Step 7: STOP

PROGRAM

# Car Engine Components Condition Analyzer


print("#"*10, 'KT CAR Engine Analyzer Toolkit','#'*10,'\n')
EngineParts=['engine cylinder block ', 'combustion chamber', 'cylinder head', ' pistons', '
crankshft', 'camshaft', 'timing chain', ' valvetrain', 'valves', 'rocker arms', 'pushrods/lifters',
'fuel injectors', 'spark plugs']
Parts_Condition=[(part,int(input(f"Enter \'{part}\' condition in ( % ): "))) \
for part in EngineParts ]
total=0 for i in
Parts_Condition:
total+=i[1]
Engine_Condition=total//len(Parts_Condition)+1 print('\n',"#"*10,
'KT CAR Engine Analyzer Toolkit','#'*10,'\n') print("Engine
Working Percentage :",Engine_Condition,"%")

60
OUTPUT

RESULT

61
AIM
EX.NO:
DATE:
Thus, the above program for checking the working condition of car engine component in
percentage is executed and output is verified successfully.
4C MATERIALS REQUIRED FOR CONSTRUCTION OF
A BUILDING

To write the programme for the materials required to construct the building for the given area.

ALGORITHM
Step 1: START

Step 2: READ the building area in sqft as input from the user.

Step 3: Define a function Build Matcalculation ()

Step 4: Use List for Building Materials.

Step 5:Use List for the Measurements of Building Materials.

Step 6: Use the below value for per sqft calculation

(Cement=0.4, Sand = 1.2, Bricks = 11, Aggregates = 1.5, Steelbars = 4, Flooring Tiles = 0.07)
Step 7:Calculate the Materials requirement use formula

Quantity = Builtup area * Value of Building Materials

Step 8:Display the Quantity of Materials needed for building.

Step 9: STOP

PROGRAM

def BuildMatCalculation(AREA):
BUILDING_MATERIALS=['CEMENT BAGS','SANDS','BRICKS','AGGREGATES',
'STEEL BAR','FLOORING TILES']

MEASUREMENT_OF_BUILDING_MATERIALS=['50 KG BAGS','CUBIC
ft','nos','CUBIC ft','KG','LITTER']

Sqft_Calculation=[0.4,1.2,11,1.5,4,0.07]

62
print("-----MATERIALS NEEDED FOR BUILDING ",AREA," Sqft HOUSE-----")

print(f"{'NO':<9}{'MATERIALS':<18}{'QUANTITY':<12}{'MEASUREMENT':<9}")

print("-"*50)

for NO,MATERIALS,QUANTITY,MEASUREMENT in
zip(range(1,len(BUILDING_MATERIALS)),BUILDING_MATERIALS,
Sqft_Calculation,MEASUREMENT_OF_BUILDING_MATERIALS):

print(f"{NO:<9}{MATERIALS:<18}{round((QUANTITY*AREA),2):<12}
{MEASUREMENT:<9}")

print("-"*50)

AREA=int(input(("Enter building area in square feet : ")))


BuildMatCalculation(AREA)

OUTPUT

63
AIM
EX.NO:
DATE:

RESULT
Thus, the aboveprogram for the materials requirement to construct the building for the given
area is executed and output is verified successfully.
5A
COMPONENTS OF AUTOMOBILE

To write a program to check the genuine automobile components

ALGORITHM
Step1: START

Step2: Use Set to Create a Genuine Approved list of Components.

Step3: Get the number of Automobile components you to Check and their HSN code.

Step4: Use input () function for how many components wants to check

Step5: Use Intersection and difference operations to check the genuinity.

Step 6: Display the Genuine HSN code and non-Genuine HSN code.

Step 7: STOP

PROGRAM
print(" \tAutomobile Genuine Components Checker") print("%"*50)

APPROVED_HSN={'HSN0029','HSN0045','HSN0043','HSN0076','HSN098'}

HSNCode=set({})

ComponentCount=int(input("How many Components want to check ? - ")) for

GC in range(1,ComponentCount+1):

64
HSNCode.add(input(f"Enter the HSNCode of Component {GC}: "))

print("\n\tGenuined HSNCodes\n","-"*30) for sno,code in

enumerate(HSNCode.intersection(APPROVED_HSN),start=1):

print(sno,code) print("\n\tNot Genuined HSNCodes\n","-"*30) for sno,code

in enumerate(HSNCode.difference(APPROVED_HSN),start=1):

print(sno,code)

OUTPUT

RESULT
Thus, the above program to check the genuine automobile components is executed and the output is
verified successfully.

65
EX.NO: 5 B DATE: ELEMENTS OF CIVIL STRUCTURE

AIM
To write a program to find the elements of civil structure

ALGORITHM
Step1: START

Step2: Declare Sets for general elements

Step3: Define operations for the elements of civil structure

Step4: Use def keyword for defining a operation function

Step5: Use Dictionary for elements given as input

Step6: Compare the input elements with the General elements

Step7: Use for loop and if else conditional statements

Step8: Display the Elements in your building, Missing Elements, New Elements, Common
elements,uncommon elements and All the Elements.

Step9: Use operations of Sets and print () statement

Step10: STOP

PROGRAM
print(" ### Building Structure Analyzer ### \n")

General_Elements={'Roof','Parapet','Lintels','Beams','Columns','Damp_Proof_Course'
,'Walls','Floor','Stairs','Plinth_Beam','Foundation','Plinth'}

def op(elements): for NO,GE in

enumerate(elements,start=1): print(NO,'-',GE)

print(" --- General Civil Structural Elements ---")

op(General_Elements)

No_Elements=int(input("\nEnter the No of Structural Elements in Your House : "))

Elements={} for Get_Element in range(1,No_Elements+1):

66
Element=input(f"Enter the Element{Get_Element}: ")

if Element in Elements: Elements[Element]+=1

else:

Elements[Element]=1 print("\n --- Elements in Your Building ---")

op(set(Elements.keys())) print("\n --- Missing General Elements in Your

Building ---") op(General_Elements-set(Elements.keys())) print("\n --- New

Elements in Your Building ---") op(set(Elements.keys())-General_Elements)

print("\n --- Common Elements in Your Building & General Elements --- ")

op(set(Elements.keys())&General_Elements) print("\n --- Not Common

Elements in Your Building &General Elements ---")

op(set(Elements.keys())^General_Elements) print("\n --- All Elements ---")

op(set(Elements.keys())|General_Elements)

67
OUTPUT

RESULT
Thus, the above programto find the elements of civil structure is executed and output is verified
successfully.

68
EX.NO:
DATE:
6A
FACTORIAL OF A NUMBER

AIM
To write a program to calculate factorial of a number.

ALGORITHM
Step 1: START

Step 2: Read a number n.

Step 3: Initialize variables: i

= 1, fact = 1

Step 4: IF i<=n go to step 5 otherwise go to step 8

Step 5: Calculate fact = fact*I

Step 6: Increment the I by 1(i=i+1) and go to step 4

Step 7: print fact

Step 8: STOP

PROGRAM
#factorial print("*"*20,"Factorial of Number

","*"*20) def factorial(num):

if num==1:

return num

else:

return num*factorial(num-1)

num=int(input("Enter the number:"))

print(f"Factorial of '{num}'is",factorial(num))

69
OUTPUT

RESULT
Thus, the above program for calculating factorial of a number is executed and output is
verified successfully.

70
EX.NO:
DATE:
6B
LARGEST NUMBER IN A LIST

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

ALGORITHM
Step 1: START

Step 2: Create the list and get the elements from the user.

Step 3: Define a user defined function like bubblesort().

Step 4: Return the sorted list.

Step 5: Store and display the larget number from the sorted list.

Step 6: STOP

PROGRAM
def bubblesort(list):

print(alist) indexes =

range(len(alist)) for idx in

indexes: for nidx in

indexes[idx:]: if

alist[idx] > alist[nidx]:

alist[idx], alist[nidx] = alist[nidx], alist[idx]

print("inter", alist) return alist alist=list(map(int,(input("Enter

the list of elements : ").split()))) sorted_list=bubblesort(alist)

print(f"Largest number in a list is : {sorted_list[-1]}")

71
OUTPUT

RESULT
Thus, the above program for finding largest number in a list is executed and output is verified
successfully.

72
EX.NO:
DATE:
6C
AREA OF SHAPE

AIM
To write a program to calculate Area of shapes.

ALGORITHM
Step 1: START

Step 2: Display the option and get the input as option number from the user.

Step 3: Create a user defined function for calculating the area of the shape.

Step 4: Inside the function, calculate the area of shapes, Square = a*a

Rectangle = a*b

Circle = 3.14*(r*r)

Triangle = ½*(b*h)

Parallelogram = b*h

Isosceles trapezoid = ½ (a + b)*h

Rhombus = ½*(d1)*(d2)

Kite = ½*(d1)*(d2)

Step 5: Call the function name and display the output.

Step 6: STOP

PROGRAM
def square(x):

return x**2 def

rectangle(l,w):

return l*w def

circle(r,pi=3.14):

return pi*(r**2) def

73
triangle(b,h):

return b*h*(1/2) def

parallelogram(b,h):

return b*h def

isosceles_trapezoid(a,b,h):

return (1/2)*(a+b)*h

def rhombus_kite(d1,d2):

return (1/2)*d1*d2

print(f"{'*'*30} Area of Shape {'*'*30}") choice=int(input("""

1.square

2.rectangle

3.circle

4.triangle

5.parallelogram

6.isosceles trapezoid

7.rhombus

8.kite

Enyer the Choice : """))

if choice==1:

x=int(input("Enter the 'x' value of square : "))

print(f"Area of Square : {square(x)}") if

choice==2:

l,w=input("Enter the 'length' and 'breadth' value of rectangle : ").split()

74
print(f"Area of Rectangle : {rectangle(float(l),float(w))}") if

choice==3:

r=int(input("Enter the 'radius' value of circle : "))

print(f"Area of circle : {circle(r)}") if choice==4:

b,h=input("Enter the 'base' and 'height' value of triangle : ").split()

print(f"Area of triangle : {triangle(float(b),float(h))}") if choice==5:

b,h=input("Enter the 'base' and 'height' value of parallelogram : ").split()

print(f"Area of triangle : {parallelogram(float(b),float(h))}") if choice==6:

a,b,h=input("Enter the 'upper','lower' and 'height' value of isosceles_trapezoid : ").split()

print(f"Area of Square : {isosceles_trapezoid(float(a),float(b),float(h))}") if choice==7:

d1,d2=input("Enter the 'distance 1' and 'distance 2' value of rhombus : ").split()

print(f"Area of Square : {rhombus_kite(float(d1),float(d2))}") if choice==8:

d1,d2=input("Enter the 'distance 1' and 'distance 2' value of kite : ").split()

print(f"Area of Square : {rhombus_kite(float(d1),float(d2))}")

75
OUTPUT

76
RESULT
Thus, the above program for calculating area of the shape is executed and output is verified
successfully.

EX.NO: 7 A
DATE: CHECKING PALINDROME IN A STRING OF SHAPE

AIM
To write a program check the give string is palindrome or not.

ALGORITHM
Step 1: Start

Step 2: Read the string from the user

Step 3: Calculate the length of the string

Step 4: Initialize rev = “ ” [empty string]

Step 5: Initialize i = length - 1 Step

6: Repeat until i>=0:

6.1: rev = rev + Character at position ‘i’ of the string

6.2: i = i – 1

Step 7: IF string = rev THEN

7.1: Print “Given string is palindrome”

Step 8: ELSE

8.1: Print “Given string is not palindrome”

Step 9: Stop

77
PROGRAM
string=input ("Enter the string : ")

rstring=string [::-1] if

string==rstring:

print (f" The given string '{string}' is Palindrome") else:

print (f" The given string '{string}' is not Palindrome")

OUTPUT

RESULT
Thus, the aboveprogram to check the give string is palindrome or nothas executed and output
has been verified successfully.

EX.NO: 7 B
DATE: COUNTING CHARACTERS IN A STRING

AIM
To write a program to find the character count of a string.

ALGORITHM
Step 1: start

Step2: Get String as input from the user

Step3: Use Looping Statement to count the characters in the given String

Step4: Display the Characters count.

Step5: print () function

78
Step 6:stop

PROGRAM
string=input("Enter the string : ")

charCount=0

for word in string.split(): charCount+=len(word)

print("Number of Character in a String : ",charCount)

OUTPUT

RESULT
Thus, the above program to find the character count of a string has executed and output has
been verified successfully.

EX.NO: 7 C
DATE: REPLACING A CHARACTERS IN A STRING

AIM
To write a program to replace a character in a string.

ALGORITHM
Step 1: Start

Step 2:Get String as input from the user Step

3:Get the Letter to be changed from the user.

Step 4:Get the Letter to be replaced from the user.

Step 5:Replace the Letters using looping and Conditional statements.

Step6:Display the replaced string.

Step 7:Use print () function

79
Step 8: Stop

PROGRAM
string=input("Enter the string : ") print("The Given String :

", string) charChange=input(("Which Letter you want to

change ? - ")) repString=input(("Which Letter you want to

replace ? - "))

stringlist=list(string) for idx in

range(len(stringlist)): if

stringlist[idx]==charChange:

stringlist[idx]=repString

ReplacedString=" " print("Number of Character in a String :

",ReplacedString.join(stringlist))

OUTPUT

RESULT
Thus, the above programto replace a character in a string has been executed and output has
been verified successfully.

80
EX.NO: 8 A STUDENT MARK SYSTEM USING NUMPY AND
DATE: PANDAS

AIM
To write a Python program to print the student mark system using numpy and panda library.

INSTALLING PACKAGES

81
PROGRAM
import os os.environ['MPLCONFIGDIR'] = os.getcwd() +

"/configs/" import pandas as pd import numpy as np import

matplotlib import matplotlib.pyplot as plt

#code here d

={

'RollNumbe

r':[1,2,3,4],

'StudentName':['kamal','vimal','vinoth','wahi'],

82
'Score':[64,68,61,86]} df

= pd.DataFrame(d)

# converting dict to dataframe

# Keys get converted to column names and values to column values

#get grade by adding a column to the dataframe and apply np.where(), similar to a nested if

df['Grade'] = np.where((df.Score < 60 ),

'F', np.where((df.Score >= 60) & (df.Score <= 69),

'D', np.where((df.Score >= 70) & (df.Score <= 79),

'C', np.where((df.Score >= 80) & (df.Score <= 89),

'B', np.where((df.Score >= 90) & (df.Score <= 100),

'A', 'No Marks')))))

df_no_indices = df.to_string(index=False)

print(f"{'*'*30}KGiSL Institute of Technology{'*'*30}")

print('\tStudent Grade Analyzer') print(df_no_indices)

#print(df)

#Graphical Representation using Matplotlib

rollnumber=d['RollNumber'] names =

d['StudentName']

values = d['Score']

#fig = plt.figure("YourWindowName")

fig=plt.figure("KGiSL Institute of Technology")

fig.set_figheight(4) fig.set_figwidth(10)

plt.subplot(131)

plt.bar(names, values)

83
OUTPUT

84
RESULT
Thus, the above program for printing student mark system using numpy and pandas is
executed and the output is verified successfully.

85
AIM
EX.NO:
DATE:
8B
LINEAR REGRESSION USING SCIPY

To write an python program to print linear regression using scipy library.

PROGRAM
import os

os.environ['MPLCONFIGDIR'] = os.getcwd() + "/configs/"

from scipy import stats import numpy as np import pandas

as pd import matplotlib.pyplot as plt

x = np.random.random(10) y

= np.random.random(10)

df = pd.DataFrame({'x':x,'y':y}) print(df) slope, intercept,

r_value, p_value, res = stats.linregress(x,y) print ("\n r-

squared:", r_value**2)

fig=plt.figure("KiTE PSPP Scipy Package Demo")

plt.suptitle('Linear Regression') plt.plot(x, y, 'o',

label='original data') plt.plot(x, intercept + slope*x,

'r', label='fitted line') plt.legend() plt.show()

86
OUTPUT

RESULT
Thus, the above program for printing linear regression using scipy is executed and the output
is verified successfully.

87
AIM
EX.NO:
DATE:
A
9 COPYTHE CONTENT FROM ONE FILE TO
ANOTHER FILE

To FindCopy the Content from One File to anotherFile of a Given Number and Terms

ALGORITHM
Step1: START
Step2: Open one file called file 1.txt in read mode.
Step3: Open another file 2. txt in write mode.
Step4: Read each line from the input file 1 and Copy into the output file 2
Step5: Read each line from the input file 2 and Copy into the output file 3 Step6:
STOP

PROGRAM
of1=open('file1.txt','r') of2=open('file2.txt','w+')

content=of1.read() of2.write(content) print(" 'file1.txt'

content Copied to 'file2.txt' using R/W") of1.close()

of2.close()

import shutil

shutil.copyfile('file2.txt','file3.txt') print(" 'file2.txt' content Copied

to 'file3.txt' using shutil package")

88
OUTPUT

RESULT
Thus, the Python Programto findCopy the Content from One File to anotherFile of a Given
Number and Termis executed and output verified successfully.

9B
WORD COUNT

To write a program to word count in a file.

ALGORITHM
Step1:START

Step2:Import the module re

Step3:To Open and Read the text1.txt

Step4:For the Word in the file to Display the count of the word

Step5:For the Unique words in the file to Display the count of the word

Step6:STOP

PROGRAM
import re words=re.findall('\w+',

open('text1.txt').read().lower()) for word in words:

print(word) print("number of words in textfile :",

len(words))

uniquewords=set(words) for

uniqueword in uniquewords:

print(uniqueword)

89
AIM
EX.NO:
DATE:
print("number of unique words in textfile :", len(uniquewords))

RESULT
Thus, the above programto word count in a file is executed and output is verified
successfully.

90
Th

EX.NO: 9 C
DATE: LONGEST WORD IN A TEXT FILE

AIM
To Write a Program for finding longest word in a Text file

ALGORITHM
Step1:START

Step2:Import re

Step3:To Open and Read text.txt file

Step4:To Find the Longword in the text file

Step5:For Word in the file and Length of the word is to the file to Display the Word

Step6:STOP PROGRAM
import re words=re.findall('\w+',

open('text1.txt').read().lower()) longword=words[0]

for word in words: if

len(word)>len(longword):

longword=word print("Longest word in

textfile : ", longword)

OUTPUT

RESULT:
us, the above program to find longest word in a text file is executed and output has been
verified successfully.
EX.NO: 10 A
DATE: DIVIDE BY ZERO ERROR

91
AIM
To write program to divide by zero error by exception handling.

ALGORITHM

Step1:START

Step2: Get the value of dividend.

Step3: Get the value of divisor.

Step4: Try if quotient=dividend/divisor.

Step5: Print the quotient.

Step6: Except, print zero division error.

PROGRAM
print(f"{'*'*30} Division Operation {'*'*30}")

dividend=int(input("\nEnter the dividend : "))

divisor=int(input("\nEnter the divisor : ")) try:

quotient=dividend/divisor

op=quotient except

ZeroDivisionError as error:

op=error finally:

print(f"\nDivision operation result of {dividend}/{divisor} : {op}")

92
Th

OUTPUT

RESULT
us, the python programto divide by zero error by exception handling is executed and
output is verified.

EX.NO: 10 B
DATE: VOTER’S AGE VALIDATION

AIM
To write a python program to check voter age validity.

ALGROTHM
Step1:START.

Step2: Get year and birth, current year and current age.

Step3: Print the age.

Step4: If current age is <=18 then print you are not eligible to vote Step5:

Else print you are not eligible to vote.

93
PROGRAM
print(f"{'*'*30} Voter ID Validation System {'*'*30}\n")

try :

fo=open('peoplelist.txt','r')

peoplelist=fo.readlines()

error=None except IOError

as e:

error=e finally: if not

error: for people in

peoplelist:

name,age=people.split(' ')

if int(age)>=18:

print(name," - you are 'elgible' for vote in india")

else:

print(name," - you are 'not elgible' for vote in india")

else

print(error)

OUTPUT

94
Th

RESULT
us, the python programto check voter age validity is executed and output is verified.
EX.NO: 10 C
DATE: STUDENT MARK RANGE VALIDATION

AIM
To write a python program to perform students marks range validation.

ALGORITHM
Step1:START

Step2: Get mark.

Step3: If mark is <0 or >100 then print that the value is out of range and try again.

Step4: Else print that the mark is in range.

PROGRAM
import re print(f"{'*'*30} Student Mark Range Validation

{'*'*30}\n")

try :

95
fo=open('studentmarklist.txt','r')

studentmarklist=fo.readlines()

error=None except IOError as e:

error=e

finally: if

not error:

for student in studentmarklist[1:]:

RollNumber,Name,MarksPercentage=tuple(re.findall('\w+',student))

if int(MarksPercentage)>70: print(RollNumber," - 'pass'")

else:

print(RollNumber," - 'fail'")

else:

print(error)

OUTPUT

96
Th

RESULT
us, the python program to perform students marks range validation is executed and output
is verified.
EX.NO: 11
DATE: PYGAME TOOL BASICS

AIM
To write a program to create pygame using pygame library.

INSTALLING PACKAGES
1.Go to this link to install pygame www.pygame.org/download.html.

2.Extract the zar file

3.Open command prompt

97
PROGRAM
import pygame from

pygame.locals import * from

random import randint width

= 500 height = 200

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

YELLOW = (255, 255, 0)

MAGENTA = (255, 0, 255)

CYAN = (0, 255, 255)

BLACK = (0, 0, 0)

GRAY = (150, 150, 150)

WHITE = (255, 255, 255)

dir = {K_LEFT: (-5, 0), K_RIGHT: (5, 0), K_UP: (0, -5), K_DOWN: (0, 5)}

pygame.init() screen =

pygame.display.set_mode((width, height)) font =

pygame.font.Font(None, 24) running = True

98
OUTPUT

RESULT
Thus, the above programto create pygame using pygame library has been executed and output
is verified successfully.
EX.NO: 12
DATE: BOUNCING BALL USING PYGAME

AIM
To write a program to bounce a ball using pygame library.

PROGRAM
import sys, pygame pygame.init()

# Screen and Window setup screen_size =

screen_width, screen_height = 720, 320

'''logo = pygame.image.load("logo.png")

pygame.display.set_icon(logo)'''

99
pygame.display.set_caption("Bouncing Ball")

screen = pygame.display.set_mode(screen_size)

black = (0, 0, 0) # Ball setup ball

= pygame.image.load("1.jpg")

ball_rect = ball.get_rect()

ball_speed = [1, 1] # Game Loop

while True: for event in

pygame.event.get(): if

event.type == pygame.QUIT:

pygame.quit()

sys.exit()

# Ball update ball_rect = ball_rect.move(ball_speed)

if ball_rect.left < 0 or ball_rect.right > screen_width:

ball_speed[0] = -ball_speed[0] if ball_rect.top < 0

or ball_rect.bottom > screen_height:

ball_speed[1] = -ball_speed[1]

# Screen update

screen.fill(black)

screen.blit(ball, ball_rect)

pygame.display.flip()

100
OUTPUT

RESULT
Thus, the above program to bounce a ball using pygame library has been executed and output
is verified successfully

101

You might also like