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

PSPP - Record Mech

Quantity If op==6 PRINT name,mobilenum,date PRINT Item,Qty,Price Calculate bill_amount PRINT bill_amount STOP PROGRAM name=input("Enter Customer Name: ") mobilenum=input("Enter Mobile Number: ") date=input("Enter Date: ") bill_amount=0 Items=[] Qty=[] Price=[] print("1. Fruits\n2. Vegetables\n3. Cosmetics\n4. Grains\n5. Oil\n6. Print Bill") choice=int(input("Enter your choice: ")) while(choice!=6
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)
247 views

PSPP - Record Mech

Quantity If op==6 PRINT name,mobilenum,date PRINT Item,Qty,Price Calculate bill_amount PRINT bill_amount STOP PROGRAM name=input("Enter Customer Name: ") mobilenum=input("Enter Mobile Number: ") date=input("Enter Date: ") bill_amount=0 Items=[] Qty=[] Price=[] print("1. Fruits\n2. Vegetables\n3. Cosmetics\n4. Grains\n5. Oil\n6. Print Bill") choice=int(input("Enter your choice: ")) while(choice!=6
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/ 132

KGISL Institute Of Technology -KITE

Coimbatore – 641 035.


(Approved by AICTE & Affiliated to Anna University, Chennai-25)

Department of Mechanical Engineering

NAME : …………………………………………….……

REG NO : ………………………………………………….

SUBJECT : …………………………………………….……

COURSE : …………………………………………….……

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

BATCH : …………………………………………….…….
KGISL Institute Of Technology - KITE
Coimbatore – 641 035.

(Approved by AICTE & Affiliated to Anna University, Chennai-25)

NAME :

CLASS :

UNIVERSITY REG NO :

Certified that, this is a bonafide record of practical work


done by..................................................................................................of
Mechanical Engineering branch.......................................................... in
……………….……………………..……………………. Laboratory,
during …………… Semester of academic year 2021 - 2022 .

Faculty in charge Head of the Department

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


at KGiSL Institute of Technology, Coimbatore – 641 035.

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

CIRCULATE THE VALUES OF N


2.b
VARIABLES

2.c DISTANCE BETWEEN TWO POINTS

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 ELEMENTS OF A CIVIL STRUCTURE

5.b COMPONENTS OF AUTOMOBILE

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.: ELECTRICITY BILL GENERATION
Date:

AIM
To write a Python program to calculate electricity bill.

ALGORITHM

Step 1: Start the procedure


Step 2: Get TNEB number, last bill meter reading and current bill meter reading from the user
consumed . The units to be charged should be the units consumed – 100. The fixed charge is equal to
20
Step 3: The difference between last bill meter reading and current bill meter reading is the units

Step 4: If units to charge is in range 100 - 200 the charges is equal to product of (unit of charge –
100) and 1.5 + fixed charge
Step 5: If units to charge is in range 100 – 200 the charges is equal to product of (unit to charge –
100) and 1.5 + fixed charge
Step 6: If units to charge is in range 201 – 500 the charges is equal to sum of (100*1.5) and
product of (unit to charge – 100) with 4 and fixed charge

Step 7: Display the bill amount which is equal to sum of fixed charge and charge for range (100
- 500)
Step 8: Stop the procedure
FLOWCHART

START

Read Ebnum , previous


reading , current reading

Consumed=current reading
– previous reading

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

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

If Cost=(100*2)+((consumed
consumed>200 -200)*3)
and
consumed<=50 Fixed charges=30
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
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 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(" ")
OUTPUT

RESULT

The above program for calculating electricity bill is executed and the output is verified
successfully.
Ex no: RETAIL STORE BILLING
Date:

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

READ op

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

If op==2 READ product Item.apppend(Vegetablename)


name, quantity Price.append(Vegetableprice)
,price Qty.append(VegetableQty)
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 product
Price.append(Oilprice)
name, quantity
,price Qty.append(OilQty)

IC in
range
(len(item

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

Bill_amount=Price[IC]
*Qty[IC]
PRINT
Bill_amount

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

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

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


OUTPUT
RESULT
The above program for calculating retail shop bill is executed and the output is verified
successfully.
Ex no.: SINE SERIES
Date:

AIM
To write an 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
FLOWCHART

START

START
Factorial(n)

Factorial(n)

Sin(n)
Fact=1

Pi=3.14

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

Print x
Fact*=1

Print sin(x,n)
Return Fact

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

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


OUTPUT

RESULT
The above program for finding sine series is executed and the output is verified successfully.
Ex no.: WEIGHT OF A STEEL BAR
Date:

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
FLOWCHART

START

Read SteelDiameter,
SteelLen

Dsquare=
SteelDiameter*SteelDiameter

Weight_of_steel_per_meter
= Dsquare/162

Total_weight_of_steel=( Ds
quare*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)

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


OUTPUT

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

THREEPHASE AC CIRCUIT
Ex.no:

Date:

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.

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

START

Newton_method(num,nu
m_iters=100)

READ a

i in range
(num_iter

Iternum=num

Num=0.5*(num+a/num)

Num==
Break
iternum

Return num

STOP
START
START

Newton_method(num
,num_iters=100)
Threephase(voltag
e,current,root3)

Threephase(volta
ge,current,root3) Kva=voltage*current
*root3

Read
voltage,current

Return kva

Print
voltage,current
STOP

Root3=newton_method
(3)

Print threephase
(voltage,current,r
oot3)

STOP
PROGRAM
def newton_method(number, number_iters = 100):

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

RESULT
The above program for computing electrical current in three phase AC circuit is executed and
output is verified successfully.
Ex no: EXCHANGE THE VALUE OF TWO VARIABLES
Date:

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


FLOWCHART
START

Read V1, V2

temp = V1

V1 = V2

V2 = temp

START
print V1, V2

swap_functio
V1 = V1^V2 n(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

V1 = V1 – V2
OUTPUT

RESULT
The python program to exchange the value of given variables was executed and verified
successfully.
Ex No.: DISTANCE BETWEEN TWO POINTS
Date:

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.
PROGRAM
def newton_method(number):

x = float(number)

yn=number

for i in range(100):

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

newton_method distance_between(pointA,poin
tB)
(number, number_iters = 100)

distance_between(pointA,poin x1,y2=pointA
tB)
x2,y2=pointB

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

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

return
round(root_2,2)
STOP

STOP
OUTPUT

RESULT
The above python program to find distance between two points was executed and verified
successfully.
Ex no.: CIRCULATE THE N VALUES
Date:

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

START

Read n

Get n values (n)

list1 = get Nvalues(n)

Print lis1

Circulate (Nvalues)

Circulate (list1)

STOP
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)
FLOWCHART

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
OUTPUT

RESULT
The python program to get an input from user and circulate N values was executed and
verified successfully.
Ex no.: NUMBER SERIES
Date:

AIM
To write a program to find the number series.

ALGORITHM

Step 1: Start the procedure.Step 2: Get number of the elements as input from the user.
Step 3: Choose anyone N series from the options.
Step 4: If the choice is 1, then use for loop and range function to find 1+2+3+……….+N.
Step 5: If the choice is 2 , then use for loop and range function to find
1^2+2^2+3^2+....+N^2.
Step 6: If the choice is 3,then use loop and range function to find
1+(1+2)+(1+2+3)+……N.
Step 7: Display the result.
Step 8: Stop the procedure.
PROGRAM:
N = int(input("Enter a number of a element:"))

choice = int(input("""

Number Series

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)


OUTPUT

RESULT
The above program for finding the number is executed and the output is verified
successfully.
Ex no: NUMBER PATTERN
Date:

AIM
To write a program to find the number pattern.

ALGORITHM

Step 1:Start the procedure.


Step 2:Get the number from the user.
Step 3:Choose anyone number pattern series.
Step 4: If choice is odd number N series pattern , use for loop and
range function , display the series 1+3+5+………+N.
Step 5: If choice is even number N series pattern, use for loop and
range function , display the series 2+4+6+……….+N.
Step 6:Stop the procedure.
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):

if n%2!=0:

print(n)

if choice == 2:

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

if n%2 == 0:

print(n)
OUTPUT

RESULT
The above program coding has been executed and the output is verified successfully.
Ex no: PYRAMID PATTERN
Date:

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

ALGORITHM

Step 1:Start the procedure.


Step 2:Get the number of elements as input from the user.
Step 3:Generate the following right angle triangle pyramid pattern ,
 Pyramid pattern
 Star right triangle
 Number pattern
 String pattern
Step 4:Use sum of N terms of the series method and use for loop and range function.
Step 5:Display the pyramid patterns.
Step 6:Stop the procedure.
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
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
The above program has been executed and the output is verified successfully.
Ex no.: LIBRARY MANEGMENT SYSTEM
Date:

AIM
To write a program for the library management system.

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

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)

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


OUTPUT

RESULT

The above program for the library management system is executed and output
verified successfully.
Ex no: CAR ENGINE COMPONENT ANALYZIER
Date:

AIM
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,"%")
OUTPUT

RESULT
The above program for checking the working condition of car engine component in
percentage is executed and the output is verified successfully.
Ex no.: MATERIALS REQUIREMENT ANALYZER
Date:

AIM
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 Mat calculation()

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, Steel bars = 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]

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

RESULT

The above the programme for the materials required to construct the building for the given
area is executed and the verified successfully.
Ex no: COMPONENTS OF AUTOMOBILE
Date:

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

Step6: Display the Genuine HSN code and non Genuine HSN code.

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

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
The above program coding has been followed and the output has been verified successfully.
Ex no: ELEMENTS OF A CIVIL STRUCTURE

Date:

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

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)
OUTPUT
RESULT
The above program is executed and output is verified successfully.
Ex.no: FACTORIAL OF A NUMBER

Date:

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

RESULT

The above program for calculating factorial of a number is executed and the output is verified
successfully.
Ex no.: LARGEST NUMBER IN A LIST

Date:

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]}")


OUTPUT

RESULT

The above program for finding largest number in a list is executed and the output is verified
successfully.
Ex no: AREA OF SHAPE

Date:

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

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


OUTPUT

RESULT

The above program for calculating area of the shape is executed and the output is verified
successfully.
Ex no.: CHECKING PALINDROME IN A STRING
Date:

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
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
The above program has been executed and output has been verified successfully.
Ex no.: COUNTING CHARACTER IN A STRING
Date:

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

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
The above program has been executed and the output has been verified successfully.
Ex no.: REPLACING A CHARACTER IN A STRING
Date:

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

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
The above program has been executed and the output has been verified successfully.
Ex no.: STUDENT MARK SYSTEM USING NUMPY AND PANDA
Date:

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

ALGORITHM

Step 1: Start the Procedure


Step 2: Import the modules os, matplotlib, pandas, numpy from standard library
Step 3: By using pandas, the assigned student details is analyzed.
Step 4: A dictionary with student details is created
Step 5: By using dataframe method, the dict is converted into dataframe .
Step 6: By using figure function in pyplot module of matplotlib, a new figure is created.
Step 7: The figure is displayed by using show method in pyplot module.
Step 8: Stop the Procedure

INSTALLING PACKAGES
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={

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

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

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

RESULT
The above program for printing student mark system using numpy and panda is executed and
the output is verified successfully.
Ex no.: LINEAR REGRESSION USING SCIPY
Date:

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

ALGORITHM

Step 1: Start the Procedure


Step 2: Import the modules os, matplotlib, pandas, numpy from standard library
Step 3: x and y values are displayed using random method from numpy module.
Step 4: A dictionary with x and y values are created
Step 5: By using dataframe method, the dict is converted into dataframe .
Step 6: Calculate a linear least squares regression for two sets (x,y) of measurements.
Step 7: Linear regression is performed using stats.lineregress.
Step 7: The coefficient of determination is displayed and the data is plotted.
Step 8: Stop the Procedure
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()
OUTPUT
RESULT
The above program for printing linear regression using scipy is executed and the output is
verified successfully.
Ex no: COPY THE CONTENT FROM ONE FILE TO ANOTHER FILE
Date:

AIM
To Find Copy the Content from One File to another File 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")


OUTPUT

RESULT
The Python Program is executed and output verified successfully.
Ex no.: WORD COUNT
Date:

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

print("number of unique words in textfile :", len(uniquewords))


OUTPUT

RESULT
The above program is executed and output is verified successfully.
Ex no.: LONGEST WORD IN A TEXT FILE
Date:

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:
The above program is executed and output has been verified successfully.
Ex no: DIVIDE BY ZERO ERROR
Date:

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


OUTPUT

RESULT
The python program is executed and the output is verified.
Ex no: VOTERS AGE VALIDATION
Date:

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.


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

RESULT
The python program is executed and the output is verified.
Ex no: STUDENTS MARK RANGE VALIDATION
Date:

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

ALGORITHM

Step 1:Create a text file as studentmarklist with student name, roll number and marks

Step 2 :Import the re module

Step 3:Open the studentmarklist text file in try block

Step 4:Read the content of the studentmarklist text file.

Step 5:In except block check for IO Error

Step 6:In finally block use if condition for check the error.

Step 7:If not error, Check the students marks and allocate the grade using For Loop. Else

. display the error

Step 8: Display the Students roll number and grade


PROGRAM
import re

print(f"{'*'*30} Student Mark Range Validation {'*'*30}\n")

try :

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

RESULT
The python program is executed and the output is verified.
Ex no: PYGAME TOOL BASICS
Date:

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

PROCEDURE

1) Import the pygame module


2) To generate random values from a range import the module ranint from the package
random
3) Assign width and height values to the window
4) Set screen color and store the values in tuple
5) To Initialize pygame window
6) Create the screen object of specific dimension width and height
7) Set a font object to the window

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

2.Extract the zar file

3.Open command prompt


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
OUTPUT

RESULT
The above program has been executed and output is verified successfully.
Ex no: BOUNCING BALL USING PYGAME
Date:

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

ALGORITHM

Step 1: Import and initialize pygame with pygame.init()


Step 2: Create a graphical screen (Surface) with pygame.display.set_mode()
Step 3: Load ball image and define the rectangle around the image
Step 4: Inside the infinite loop, move the ball by (2,2) pixels (speed) in x,y coordinates
Step 5: If the ball goes out of the screen boundary, reverse the direction of speed
Step 6: Fill the screen with black, before displaying the next position of the ball to avoid
the trail of the ball visible in the animation.
Step 7: Draw the ball in its next position on the screen using Surface.blit() method.
Step 8: The pygame.display.flip() method makes everything we have drawn on the screen
Surface become visible.
Step 9: If user triggers quit() event (close button), the simulation stops.
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)'''

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()
OUTPUT

RESULT
The above program has been executed and output is verified successfully

You might also like