You are on page 1of 79

KGiSL INSTITUTE OF TECHNOLOGY

COIMBATORE – 641035
Department of Science & Humanities

GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING


LABORATORY

NAME : ………………………………….
ROLL NO. : ………………………………….
REGISTER NO. : ………………………………….
YEAR & SEMESTER : ………………………………….
KGiSL INSTITUTE OF TECHNOLOGY
ANNA UNIVERSITY::CHENNAI 600 025

DEPARTMENT OF SCIENCE & HUMANITIES

LABORATORY RECORD

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

REGISTER NO. : ………………………………………………………..

Certified that this is bonafide record of work done by the above student in the
Problem Solving and Python Programming Laboratory during the academic year 2021-
2022 / Semester I.

STAFF-IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for the practical examination held on ……………………

INTERNAL EXAMINER EXTERNAL EXAMINER


GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY
INDEX
PAGE MARKS MARKS
EX.NO DATE DESCRIPTION OF THE CONTENT ALLOTTED OBTAINED SIGNATURE
NO.
1A Flowchart for generating Electricity Bill 50

1B Flowchart for generating Sine Series 50


Flowchart for Generating Retail Shop
1C 50
Billing
Flowchart for computing Weight of Steel
1D 50
Bar
Flowchart for computing Electric Current
1E 50
in 3 Phase
2A Exchange values of two variables 50

2B Distance Between two points 50

2C Circulate the N Values 50

3A Number Series 50

3B Number Pattern 50

3C Pyramid Pattern 50

4A Library Management System 50

4B Car Engine Components condition 50

4C Material Requirement Analyzer 50

5A Elements of Civil Structure 50

5B Components of Automobile 50

6A Factorial of a Number 50

6B Largest number in a List 50

6C Area of Shapes 50

7A String Palindrome 50

7B Character count of a string 50

7C Replace a given character 50

8A Student Mark System using Numpy 50

8B Linear Regression using Scipy 50


PAGE MARKS MARKS SIGNATURE
EX.NO DATE DESCRIPTION OF THE CONTENT ALLOTTED OBTAINED
NO.
9A Copy the content from one file to another 50

9B Word Count of a File 50

9C Longest Word in a Text File 50

10A Divide by Zero Exception 50

10B Voter’s Age Validation 50

10C Students Mark Range Validation 50

11 Pygame Basics 50

12 Bouncing a Ball using Pygame 50

Preparation (5)
Observation (25)
Record (15)
Viva (5)
Total (50)
Ex.NO : 1A ELECTRICITY BILL GENERATION
Date
AIM:
To draw a flowchart and develop pseudocode for calculating the electricity bill.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the TNEA consumer Number, Last, bill reading and current bill reading
from the consumer.
Step 3: Calculate the consumer. If consumed is less than or equal to 100, fixed charge
is 0. If its range in from 101 - 102 it rates 1.5 per unit, for range 201 – 500 it rates 3.0 per
unit, for 500 and above ranges it rates 6.5 per unit.
Step 4: Consumed is calculated by subtracting the last bill unit from current bill unit. If
consumed unit is greater than 100, its fixed charge is RS:25, if consumed is greater than 200,
its range of rate is 2.0/0 the fixed charge is RS:35, and if consumed is above 500, its range
will be from 101 – 200 rates RS 2.0/0 and from 201 – 500 rates RS 6/0, its fixed charge is
RS:55.
Step 5: Applicable rate are printed. Slab calculation is done, where unit of charge is the
consumes above 500 U minus 500 from unit of charge, if consumed charge is 201 – 500
range minus 200 from unit of charge, and if consumed charge is between 101 – 200 range
minus 100 from the consumed charge.
Step 6: Slab calculation is done to find the final bill amount, in which we add the range
of unit in which we add the range of unit in which our consumed unit charge falls and its
fixed amount.
Step 7: Print all the statements, which all are need to be visible in the bill and run the
program.
Step 8: End the program.

1
FLOW CHART:

START

INPUT con_num ,
per_read,
current_read

Fixed_charges = 0
S101_200_rate = 1.5
S201_500_rate = 2.5
S500_above_rate = 5

Consumed = current_read_per_read

Consumed>0

Fixed_charge = 0

Consumed>100

2
Consumed>100

Fixed_charges = 25

Consumed>200

Fixed_charges = 35
S101_200_rate = 1.5

Consumed>500

Fixed_charges = 45
S101_200_rate = 2.5
S200_500_rate = 3

3
S101_200_charges = 0
S201_500_charges = 0
S500_above_charges = 0
Units_to_Charge = consumed

S500_above_u = units_to_charge = 500

S500_above_U>0

S500_above_charges = s500_above U* s500_above_rate

DISPLAY “500_above_charges :”
S500_above_charges

Units_to_charge = s500_above_U

S201_500U = units_to_charge_200

4
S201_500_U = 0

S201_500_charge = s201_500_U*s201_s500_rate

DISPLAY “201_500_charges :”,


S201_500_charges

Units_to_charges = s201_500_U

S101_200_U = unites_to_charges_100

S101_200_U>0

S101_200_charges = s101_200_U*s101_200_rate

5
DISPLAY “101_200_charges :”,
S101_200_charges
DLSPLAY”0_100_charges :”,
Fixed_charges

Bill_amount = fixed charges + s101_200_charges + s201_500_charges +


s500_above_charges

DSPLAY ”EB Number :” con_num

DSPLAY ”Units consumed :”,consumed

DISPLAY “Bill Amount :” , bill_amount

STOP

PSEUDO CODE:
BEGIN
INPUT con_num , per_read , current_read
INITIALIZE consumed = current_read_pre_read
INITIALIZE fixed_charge = 0, s101_200_rate =1.5, s201_500_rate = 2.5 AND
s500_above_rate = 5

6
IF consumed>0 :
fixed_charge = 0
END IF
IF consumed>100 :
fixed_charge = 25
END IF
IF consumed>200 :
fixed_charge = 35
s101_200_charge = 3
END IF
IF consumed>500 :
fixed_charge = 45
s101_200_charge = 2.5
s201_500_charge = 3
END IF
INITIALIZE s101_200_charges = 0 , s201_500_charge = 0 AND s500_above_charge = 0
INITIALIZE units_to_charge = consumed
CALCULATE s500_above_U = units_to_charge_500
IF s500_above_U>0 :
S500_above_charges = s500_above_U*s500_above_rate
DISPLAY 500 above charge :
INITIALIZE units_to_charges = units_to_charge_s500_above_U
END IF
CALCULATE s201_500_U = units_to_charge_200
IF s201_500_U>0 :
COMPUTE s201_500_charges = s201_500_U*s201_500_rate
DISPLAY 201_500 charge :
INITIALIZE units_to_charge = s201_500_U
END IF
CALCULATE s101_200_charges = s101_200_U = unites_to_charge_100
IF s101_200_U>0 :
COMPUTE s101_200_charge = s101_200_U*s101_200_rates
DISPLAY 101_200_charges
END IF

7
CALCULATE Bill_amount = fixed_charge+s101_200_charges + s201_500_charges +
s500_charges + s500_above_charges
DISPLAY TAMIL NADU ELECTRICITY BOAED BILL
DISPLAY EB Number :
DISPLAY Units Consumption :
DISPLAY Bill Amount :

RESULT
Thus, flowchart to generate electricity bill was drawn and pseudocode was
successfully.

8
Ex.No : 1B SINE SERIES
Date:
AIM:
To draw flowchart and develop pseudocode for finding the sine series of a given
number for given terms.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a function to find the factorial of the number given as terms.
Step 3: Define another function to find the sine value of the given number.
Step 4 : Get two values fn number of terms and values of sine variable .
Step 5 : Pass the values respectively in the function defined .
Step 6 : Initialize pi value .
Step 7 : Convert the value of sine variables as radians using pi value .
Step 8 : Display the result of sine series .
Step 9 : Stop the program .

9
FLOW CHART :
START

Def factorial(n):

fact=i

for I in range(1,n+1);

fact*=i

return fact

Def sine(x,n):

Sin = 0

for I in range(0,n):

sign=(-1)**i

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

return sine

Pi = 3.14

INPUT “x value in degrees:, x

INPUT “ n terms ”, n

X*=(pi/180)

OUTPUT “x value in radians”, x

OUTPUT “ n terms” , n

STOP

10
PSEUDO CODE :
BEGIN
DEFINE factorial(n):
SET fact = 1
FOR I in range (1 , n+1):
Fact*=i
return fact
END FOR
DEFINE sin (X , n) :
INITIALIZE sine = 0
FOR I in range (0 , n):
Sign = (-1)**1
Sine = sine+(x**(2*i+1))* sign/factorial(2*i+1)
return sine
END FOR
INPUT x, n
INITIALIZE pi = 3.14
CALCULATE x*= (pi/180)
DISPLAY “x value in radians”, x
DISPLAY “sin series „ value is “,round(sin(x , n)2)
END

RESULT
Thus Flowchart for generating Sine Series and pseudocode was developed
successfully.

11
Ex.No: 1C RETAIL BILL SHOPPING
Date:
AIM :
To draw flowchart and develop pseudocode calculate the bill for items purchase in a
retail store.
ALGORITHM :
Step 1 : Start the program .
Step 2 : Get the consumer Name , Customer Mobile Number and Date .
Step 3 : Show the list of items that are available in store.
Step 4 : Get the input for items that are to be purchased .
Step 5 : Get the input from the customer for the produce name , price and quantity
required .
Step 6 : Calculate the total bill for items purchased by multiplying for each quantity
and summary up all the prices .
Step 7 : Print the content of the bill and the amount to be paid .
Step 8 : Stop the program .

12
FLOW CHART :

START

Print Welcome to Super Market

Read Consumer Name , mobile number , Date

Print 1.Fruits 2.Vegetable 3.Cosmetics


4. Grains 5.Oil
6. Bill

Get Input for options to shop

13
Yes Read products
Option Name , Quantity ,
=1 product prize

no

Read products Bill amount += Item Price [ 1c]*


yes Option Item Quantity [1c]
Name , Quantity , =2
product prize
no

Bill amount += Item Price [ 1c]* Read products


Item Quantity [1c] Option Name , Quantity ,
=3 yes product prize

no Bill amount += Item Price [ 1c]*


Read products Item Quantity [1c]
Option
Name , Quantity , =4
Yes
product prize

no

Bill amount += Item Price [ 1c]* Yes Read products


Item Quantity [1c] Option
Name , Quantity ,
=5
product prize

no
Bill amount += Item Price [ 1c]*
Option Item Quantity [1c]
Please wait finalizing your bill =6
Yes

Print Total Bill

14
Thank You for shopping with us visit again

STOP

PSEUDO CODE :
BEGIN
INPUT name , mobile , data
INITIALIZE bill_amount = 0 , items = [] , item quantity = [] , item price = []
DISPLAY MENU
DISPLAY “1.vegetable 2.Fruits 3.Oil 4.Cosmetics 5.Cooking Powders 6.Exit “
INPUT Of
WHILE of in [1,2,3,4,5]:
If op == 1:
INPUT vegetable Name , vegetable prices,vegetable qty
items . append (vegetable Name)
itemprice . append (vegetablr price)
itemqty . append(vegetable qty)
END IF
IF of == 2 :
INPUT fruit Name , fruit prices , fruit qty
items . append (fruit Name)
itemprice . append (fruit price)
itemqty . append (fruit qty)
END IF
IF of == 3 :
INPUT Oil Name , Oil prices , Oil qty
items . append (Oil Name)
itemprice . append (Oil price)
itemqty . append (Oil qty)

15
END IF
IF of == 4 :
INPUT Cosmetic Name , Cosmetic prices , Cosmetic qty
items . append (Cosmetic Name)
itemprice . append (Cosmetic price)
itemqty . append (Cosmetic qty)
END IF
IF of == 5 :
INPUT Cosmetic Name , Cosmetic prices , Cosmetic qty
items . append (Cosmetic Name)
itemprice . append (Cosmetic price)
itemqty . append (Cosmetic qty)
END IF
IF of == 5 :
INPUT Cosmetic Name , Cosmetic prices , Cosmetic qty
items . append (Cosmetic Name)
itemprice . append (Cosmetic price)
itemqty . append (Cosmetic qty)
END IF
END WHILE
DISPLAY “ any other left .please select option or else press 6 to exit “
DISPLAY Menu
DISPLAY “1.vegetable 2.Fruits 3.Oil 4.Cosmetics 5.Cooking Powders 6.Exit “
INPUT op
DISPLAY “Bill”
DISPLAY “ Date : “ , date
DISPLAY “ Name : “ , name
DISPLAY “ Mobile :”, mobile
DISPLAY “ Product Quantity price Bill”
FOR I in range (len(item)) :
DISPLAY (“{0:<20} {1:<14} {2:<10} {3:<5} :format (items[i] , item name[i] , item price
[i] , item qty [i] , ))
CALCULATE bill_amount += (item price [i] * item qty [i])
END FOR

16
DISPLAY “ Total Amount “, bill_amount
END

RESULT
Thus, Flowchart and Pseudocode was developed for Retail Shop Billing successfully.

17
Ex.No : 1D WEIGHT OF THE STEEL BAR
Date:
AIM :
To draw flowchart and generate pseudocode for finding the weight of the steel bar
write a python program.
ALGORITM :
Step 1 : Start the program .
Step 2 : Input steel diameter , steel Length .
Step 3 : Assign a variable D square = steel Diameter * steel Diameter to store square
value of steel Diameter .
Step 4 : Calculate the weight of steel bar perimeter by dividing D square with 162 .
Step 5 : Display weight of steel bar Per Meter .
Step 6 : Calculate weight of steel bar total and Display it .
Step 7 : Stop the program .
FLOW CHART :
START

INPUT Steel Diameter * Steel Diameter

D square = Steel Diameter * Steel Diameter

Weight Perimeter = D square / 162

DISPLAY ‘ Weight of the steel per meter : ‘, Dsquare/162,’kg/m’

Weight = D square * steel length/162

DISPLAY “ Total weight of the steel :”, w, ‘kg’

STOP

18
PSECDO CODE :
BEGIN
INPUT Steel Diameter , Steel Length
CALCULATE D square = Steel Diameter * Steel Diameter
CALCULATE Weight_Per_Meter = D square/162
DISPLAY Weight Per meter
CALCULATE Weight = D square * Steel Length /162
DISPLAY Weight
END

RESULT
Thus, Flowchart and Pseudocode was developed for calculating weight of the steel
bar successfully.

19
Ex.No: 1E COMPUTE ELECTRICAL CURRENT IN THRE PHASE AC
CIRCUIT
Date:
AIM :
To draw flowchart and develop pseudocode for computing electrical current in three
phase AC circuit.
ALGORITHM :
Step 1 : Start the program .
Step 2 : Define a function to calculate root 3 value as newton_methon .
Step 3 : Define a function to calculate three phase compute electric current value .
Step 4 : INPUT voltage ,i(current)
Step 5 : DISPLAY voltage and i(current)
Step 6 : Assign a variable root3 and call the function newton_method and return root3
value from the function .
Step 7 : DISPLAY root3 value .
Step 8 : DISPLAY the computed electric current in the three phase AC circuit by
calling the three phase function and returning the value from the function .
Step 9 : Stop the program .

20
FLOW CHART :

START

def newton_method (num , num I =100) :

x=float(num)

for I in range ( num I ) :

I num = num

Num = 0.5*( num + x/ num)

Break

Return num

Def three phase ( voltage , I , root3) :

Three phase_ I = root3 * voltage * i

Return threephase_i

INPUT voltage , i

DISPLAY voltage , i

Root3 = newton _ method(3)

DISPLAY root3

21
DISPLAY ( ‘ Computer Electric Current in
three phase AC Circuit : ‘, round ( three
phase( voltage , I , root3)) ,’KVA’ )

STOP

PSEUDO CODE :
BEGIN
DEF newton _ method ( num , num = 100 ) :
Assign x = float ( num )
FOR I in range ( num i)
Assign I num = num
CALCULATE num = 0.5 * ( num + x / num)
IF num == num :
BREAK
END IF
END FOR
RETURN num
DEF three phase ( voltage , I , roots ) :
CALCULATE three phase_i = root3* voltage*i
RETURN three phase :
INPUT voltage , i
DISPLAY voltage , i
Assign root3 = newton _ method (3)
DISPLAY root3
DISPLAY round ( three phase ( voltage ,i , root3))
END

22
RESULT
Thus, Flowchart was drawn and pseudocode for computing electric current in 3 phase
successfully.

23
Ex. No: 2A EXCHANGE THE VALUES OF TWO VARIABLES
DATE:
AIM:
To develop a python program for exchanging the values of 2 variables.

ALGORITHM 1: (Using temporary Variable)


Step 1: Start the program.
Step 2: Input 2 values n1 and n2.
Step 3: Initialize temp as n1, then n1 as n2 and n2 as temp.
Step 4: Display n1 and n2.
Step 5: End the program.

ALGORITHM 2: (Using XOR Operation)


Step 1: Start the program.
Step 2: Input 2 values n1 and n2.
Step 3: Initialize n1 as n1 XOR n2, n2 as n1 XOR n2 and then n1 as n1 XOR n2.
Step 4: Display n1 and n2.
Step 5: End the program.

ALGORITHM 3: (Using Function)


Step 1: Start the program.
Step 2: Input 2 values n1 and n2.
Step 3: Define a function.
Step 3.1: Set the values as global variables.
Step 3.2: Initialize n1 as n2 and n2 as n1.
Step 3.3: Display n1 and n2.
Step 4: Call the function.
Step 5: End the program.
ALGORITHM 4: (Using Addition and Afternoon)
Step 1: Start the program.
Step 2: Input 2 values n1 and n2.
Step 3: Initialize n1 as n1+n2, then n2=n1-n2 and n1=n1-n2.
Step 4: Display n1 and n2.

24
Step 5: End the program.
PROGRAM
print("<:<: SWAPPING OF 2 NUMBERS :>:>")
num1=int(input("Enter the value 1:"))
num2=int(input("Enter the value 2:"))
print("*"*40)
print(f"Before swapping \n Num1 = {num1} \n Num2 = {num2}")
print("SWAPPING USING TEMPORARY VARIABLE")
temp=num1
num1=num2
num2=temp
print(f"After swapping \n Num1 = {num1} \n Num2 = {num2}")

print("*"*40)
print(f"Before Swapping \n Num1 = {num1} \n Num2 = {num2}")
print("<:<: SWAPPING USING XOR OPERATOR :>:>")
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
print(f"After swapping \n Num1 = {num1} \n Num2 = {num2}")

print("*"*40)
print(f"Before Swapping \n Num1 = {num1} \n Num2 = {num2}")
def swap():
global num1, num2
print("swap() function called ...")
num1, num2 = num2, num1
swap()
print(f"After swapping \n Num1 = {num1} \n Num2 = {num2}")

print("*"*40)
print(f"Before Swapping \n Num1 = {num1} \n Num2 = {num2}")
print("<:<:SWAPPING USING ADDITION AND DIFFERENCE:>:>")
num1 = num1 + num2

25
num2 = num1 - num2
num1 = num1 - num2
print(f"After swapping \n Num1 = {num1} \n Num2 = {num2}")

OUTPUT:

RESULT
Thus, python program for exchanging values of 2 variables was written, executed and
output is verified successfully.

26
Ex. No: 2B DISTANCE BETWEEN TWO POINTS
DATE:

AIM:
To develop python program for finding the distance between 2 points.

ALGORITHM:
Step 1: Start the program.
Step 2: Input x and y co-ordinates for 2 points A and B.
Step 3: Define newton method function.
Step 3.1: Using square root formula return the value with 2 decimal point.
Step 4: Define distance function.
Step 4.1: Using newton method function, pass the variable to it and return the
output.
Step 5: Display the return value.
Step 6: End the program.

PROGRAM
from math import sqrt
def newton_method(n):
x = float(n)
yn=n
for i in range(100):
yn1=yn
yn = 0.5 * (yn + x/ yn)
if yn==yn1:
break
return round(yn,2)
def dst(pA, pB):
x1, y1 = pA
x2, y2 = pB
dx = x2 - x1
dy = y2 - y1

27
sq=sqrt(dx**2 + dy**2)
return newton_method(sq)
pA = int(input("Enter the x cordinate for PointA : ")), \
int(input("Enter the y cordinate for PointA : "))
pB = int(input("Enter the x cordinate for PointB : ")), \
int(input("Enter the y cordinate for PointB : "))
print("distance between points", dst(pA, pB))

OUTPUT

RESULT
Thus, python program for finding distance between 2 points was written, executed
and output is verified successfully.

28
Ex. No: 2C CIRCULATE THE N VALUES
DATE:

AIM:
To develop python program for circulating N values.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a function named get value with n as formula.
Step 2.1: Using the function get the elements of the list.
Step 3: Define a function named circulate with list as parameter.
Step 3.1: Using the list remove the last element and add it in the first position.
Step 4: Input the number of values inside the list.
Step 5: Display circuit.
Step 6: End the program.

PROGRAM
def circulate(alist):
for i in range(len(alist)):
a=alist.pop(0)
alist.append(a)
print(f"\t\tCirculate {i+1} : {alist}")
return alist
def getvalues(n):
nval=[]
for i in range(n):
v=input(f"Enter the Value {i+1} : ")
nval.append(v)
return nval
n=int(input("Enter the number of values wanted to be circulated:"))
nval=getvalues(n)
print("\nGiven N Values : ", nval)
print("\n","*"*15,"\tCirculate the N Value\t","*"*15,"\n")
circulate(nval)

29
OUTPUT

RESULT
Thus, python program to circulate N values was written, executed and output is
verified successfully.

30
EX.NO: 3A NUMBER SERIES
DATE:

AIM
To develop a Python Program for generating Number Series.

ALGORITHM
Step 1: Start the program.
Step 2: Input the choice and limit from user.
Step 3: If the choice is 1 generate sum of the series 1+2+…+N, if the choice is 2 find
sum of the series (1*1)+(2*2)…+(N*N), if choice is 3 find the sum of the series
1+(1+2)…+(1+2+…N)
Step 4: Stop the program.

PROGRAM
N = int(input("Enter the N Value : "))
choice = int(
input("""
Number Series
1.Sum of the N series - 1+2+3..N
2.Sum of Squares the N series - (1*1)+..N
3.Sum to N terms of the series - 1+(1+2)+..N
\nEnter 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..N : ", sum)
if choice == 2:
for N in range(1, N + 1):
sum += N**2
print("\nSum of Squares the N series-(1*1)+..N : ", sum)
if choice == 3:
for N in range(1, N + 1):

31
for n in range(1, N + 1):
sum += n
print("\nSum to N terms of the series - 1+(1+2)+..N : ", sum)

OUTPUT

RESULT
Thus, Python program to find sum of N series was written, executed and output is
verified successfully.

32
EX.NO:3B NUMBER PATTERN
DATE:

AIM
To develop Python Program for generating Number Patterns.

ALGORITHM
Step 1: Start the program.
Step 2: Input the limit and choice from user.
Step 3: If choice is 1, generate odd number series, if choice is 2 generate even number
series.
Step 4: Stop the program.

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==1:
print(N)
if choice==2:
for N in range(1,N+1):
if N%2==0:
print(N)

33
OUTPUT

RESULT
Thus, Python Program to generate number pattern was written, executed and output is
verified successfully.

34
EX.NO:3C PYRAMID PATTERN
DATE:

AIM
To develop a Python program for generating Pyramid Pattern.

ALGORITHM
Step 1: Start the program.
Step 2: Input the limit from user.
Step 3: Generate the * as pyramid pattern based on the limit.
Step 4: Generate right angle triangle pattern using * based on the limit.
Step 5: Generate the String Pattern using letters based on the limit.
Step 6: Stop the program.

PROGRAM
seriesCount=int(input("Enter the N Value : "))

# Pyramid Pattern
print("\nPyramid Pattern")
k=seriesCount-1
for i in range(0,seriesCount):
for j in range(0,k):
print(end=" ")
k=k-1
for j in range(0, i+1):
print("*",end=" ")
print("\r")

# Star" Right Triangle


print("\nStar Right Triangle ")
for row in range(seriesCount):
for coloumn in range(row+1):
print("*",end=" ")
RT=seriesCount-(row+1)

35
print(""*RT,end=" ")
print("\r")

# Number Pattern
print("\nNumber Pattern")
val=0
for row in range(seriesCount):
for coloumn in range(row+1):
val+=1
print(val,end=" ")
print("\r")

# Upper Case String


StrSeq = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print("\nString Pattern")
val=0
for row in range(seriesCount):
for coloumn in range(row+1):
print(StrSeq[val],end=" ")
val+=1
print("\r")
OUTPUT

36
RESULT
Thus, the python program to generate pyramid pattern was written, executed and
output is verified successfully.

37
EXP NO.:4A LIBRARY MANAGEMENT SYSTEMS
DATE:

AIM:
To develop python program for creating a list of books and give option like add book,
view book, issue book, return book.

ALGORITHM:
STEP1: Start the program
STEP2: Declare a list containing library books.
STEP3: Display the list of option to user and get the selection of items from the user.
STEP4: Based on the selection the item details are asked from user.
STEP5: Step4 is repeated or any option selected by user.
STEP6: The expected result for the specific function is displayed.
STEP7: Stop the program.

PROGRAM
# Library Management System
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)

38
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=IssuedBook.index(getBookName)
BooksCatelogue.append(IssuedBook.pop(BookID))

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

39
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
---------------------------------------------------------------------
KITE Library Management System
---------------------------------------------------------------------
1.Add book
2.Delete book
3.View Book
4.Issue Book
5.Return Book
Enter the choice:3
########################
Available Book List
########################
1.PSPP-1 Available
2.Maths-1 Available
3.English-1 Available
4.Physics-1 Available
5.Chemistry-1 Available

40
RESULT
Thus, the python program to create Library Management Systems was written,
executed and output is verified successfully.

41
EX.NO. 4B CAR ENGINE COMPONENT CONDITION ANALYZER
DATE:

AIM:
To develop python program for calculating the percentage of engine working using lists
or tuples.

ALGORITHM:
STEP1: Start the program
STEP2: Create a list carcomp, with all the components of engine in it.
STEP3: Get the condition of each component in terms of percentage from the user.
STEP4: The engine condition iis calculated by the formula(total/total no.of parts
used)*100.
STEP5: Display the percentage of condition of engine.
STEP6: Stop the program.

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

PartsCondition=[(part,int(input(f"Enter \'{part}\' condition in ( % ): "))) \


for part in EngineParts ]
total=0
for i in PartsCondition:
total+=i[1]
EngineCondition=total//len(PartsCondition)+1

print('\n',"#"*10, 'KT CAR Engine Analyzer Toolkit','#'*10,'\n')


print("Engine Working Percentage :",EngineCondition,"%")

42
OUTPUT

RESULT
Thus, python program to analyze the car component was written, executed and output
is verified successfully.

43
EX.No:4C MATERIALS REQUIREMENT ANALYZER
DATE:

AIM
To develop python program for finding the quantity of materials needed for building.

ALGORITHM
STEP 1: Start the program.
STEP 2: A function „BuiltMatCalculation‟ is created to create a list that calculates the
quantity.
STEP 3: Get the area value from the user.
STEP 4: Materials list, measurement list and values list is created.
STEP 5: Quantity is found by calling BuiltMatCalculation method.
STEP 6: The materials and its quantity and measurement is tabulated and displayed.
STEP 7: Stop the program.

PROGRAM
def BuildMatCalculation(area):
buildmaterial=['Cement Bags','sands','Bricks','Aggregates','steelbars','Flooring Tiles','Paint']
measurement=["50 kg bags","cubic ft","nos","cubic ft","kg","litter"]
Mat_Sqft=[0.4,1.2,11,1.5,4,0.07,0.032]
print(f"\n-----Material Needed for Building {area} sqft House-----\n")
print(f"{'NO':<9}{'Material':<18}{'Quantity':<12}{'Measurement':<9}")
print("-"*50)
for NO,Mat,Qua,Mea in
zip(range(1,len(buildmaterial)),buildmaterial,Mat_Sqft,measurement):
print(f"{NO:<9}{Mat:<18}{round((Qua*area),2):<12}{Mea:<9}")

# Get square feet


area=int(input(("Enter building area in square feet : ")))
#Calculate
BuildMatCalculation(area)

44
OUTPUT

RESULT
Thus, python program to find the material required for constructing a building was
written, executed and output is verified successfully.

45
EX.NO:5A ELEMENTS OF CIVIL STRUCTURE
DATE:

AIM
To develop a python program for analyzing structural elements of a building.

ALGORITHM
Step 1: Start the program.
Step 2: Using List create common elements in the building.
Step 3: Input number of elements and the elements name of the building.
Step 4: based on the elements input display common elements, new elements, all
elements and missing elements in a building.
Step 5: Stop the program.

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:

46
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
### Building Structure Analyzer ###

--- General Civil Structural Elements ---


1 - Plinth_Beam
2 - Plinth
3 - Columns
4 - Damp_Proof_Course
5 - Lintels
6 - Parapet
7 - Roof
8 - Walls
9 - Foundation

47
10 - Beams
11 - Stairs
12 - Floor

Enter the No of Structural Elements in Your House : 7


Enter the Element1: columns
Enter the Element2: foundation
Enter the Element3: beams
Enter the Element4: floor
Enter the Element5: stairs
Enter the Element6: lintels
Enter the Element7: roof

--- Elements in Your Building ---


1 - columns
2 - beams
3 - lintels
4 - stairs
5 - foundation
6 - roof
7 - floor

--- Missing General Elements in Your Building ---


1 - Plinth_Beam
2 - Plinth
3 - Columns
4 - Damp_Proof_Course
5 - Lintels
6 - Parapet
7 - Roof
8 - Walls
9 - Foundation
10 - Beams
11 - Stairs

48
12 - Floor

--- New Elements in Your Building ---


1 - columns
2 - beams
3 - lintels
4 - stairs
5 - foundation
6 - roof
7 - floor

--- Common Elements in Your Building & General Elements ---

--- Not Common Elements in Your Building & General Elements ---
1 - Lintels
2 - Stairs
3 - Plinth_Beam
4 - columns
5 - Columns
6 - Walls
7 - roof
8 - Floor
9 - Plinth
10 - beams
11 - lintels
12 - Foundation
13 - Beams
14 - foundation
15 - floor
16 - Damp_Proof_Course
17 - Parapet
18 - Roof
19 - stairs

49
--- All Elements ---
1 - Plinth
2 - beams
3 - Lintels
4 - lintels
5 - Foundation
6 - Beams
7 - Stairs
8 - foundation
9 - floor
10 - Plinth_Beam
11 - columns
12 - Columns
13 - Damp_Proof_Course
14 - Parapet
15 - Roof
16 - stairs
17 - Walls
18 - Floor
19 – roof

RESULT
Thus, python program to analyze the structural elements of building was written,
executed and output is verified successfully.

50
EX.NO.5B COMPONENTS OF AUTOMOBILE
DATE:

AIM
To develop a python program

ALGORITHM
Step 1: Start the program.
Step 2: Using set create genuine component list.
Step 3: Input the components to be checked.
Step 4: Based on the components display whether it is genuine or not genuine.
Step 5: Stop the program.

PROGRAM
# Genuinity Checker for Components of Automobile
print(" \tAutomobile Genuine Components Checker")
print("%"*50)

#Create a Genuine Approved List of Components


APPROVED_HSN={'HSN0029','HSN0045','HSN0043','HSN0076','HSN098'}
HSNCode=set({})

#Get Automobile Compnent Name and HSN Code


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

#Use Set Operations

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)

51
print("\n\tNot Genuined HSNCodes\n","-"*30)
for sno,code in enumerate(HSNCode.difference(APPROVED_HSN),start=1):
print(sno,code)

OUTPUT

RESULT
Thus, python program to analyze components of automobile was written, executed
and output is verified successfully.

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

AIM
To develop python program for finding factorial of a number.

ALGORITHM
Step 1: Start the program.
Step 2: Input a number from user.
Step 3: Call factorial function.
Step 3.1: In factorial(), if the number is less than 0 return the value 1,
otherwise recursively call the function to find and return the factorial.
Step 4: Display the factorial.
Step 5: Stop the program.
PROGRAM
def factorial(number):
if number<=0:
return 1
else:
return number*factorial(number-1)

print(f"{'*'*30} Factorial of Number {'*'*30}")


number=int(input("\nEnter the number : "))
print(f"\nFactorial of '{number}' is {factorial(number)}\n")

OUTPUT

RESULT
Thus, python program to find factorial of given number was written, executed ansd
output is verified successfully.

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

AIM
To develop a python program for finding largest number in a list.

ALGORITHM
Step 1: Start the program.
Step 2: Input elements from the user.
Step 3: Call bubblesort function
Step 3.1: Display the list.
Step 3.2: Using for loop sort the list in ascending order and return the list.
Step 4: Display the largest number.
Step 5: Stop the program.

PROGRAM
def bubblesort(alist):
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]}")

54
OUTPUT

RESULT
Thus, python program to find the largest element in a list was written, executed and
output is verified successfully.

55
EX.NO:7A STRING PALINDROME
DATE:

AIM
To develop a python program for finding whether given string is palindrome or not.

ALGORITHM
Step 1: Start the program.
Step 2: Input a string from user.
Step 3: Using Slice operator find the reverse of the string.
Step 4: Check whether original string and reverse are equal, if so display it as
palindrome or display it as not palindrome.
Step 5: Stop the program.

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, python program to find whether given string is palindrome or not was written,
executed and output is verified successfully.

56
EX.NO:7B CHARACTER COUNT OF A STRING
DATE:

AIM
To develop a python program for finding character count of a string.

ALGORITHM
Step 1: Start the program.
Step 2: Get the input from the user.
Step 3: Using for loop split the string to find the character and count it.
Step 4: Display the character count.
Step 5: Stop the program.

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, python program to find the count of characters in a string was written, executed
and output is verified successfully.

57
EX.NO:7C REPLACE A GIVEN CHARACTER
DATE:

AIM
To develop a python program for replacing the given character with another character
in a string.

ALGORITHM
Step 1: Start the program.
Step 2: Input replace character and character to be replaced of the string from the user.
Step 3: Using For loop, find the replace character and change it with the input
character.
Step 4: Display the final string.
Step 5: Stop the program.
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, python program to replace the given character was written, executed and output
is verified successfully.

58
EX.NO:8A STUDENTS MARK SYSTEM USING NUMPY, PANDAS AND
MATPLOTLIB
DATE:

AIM
To develop python program for student mark system plot it.

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

PROGRAM
import os
os.environ['MPLCONFIGDIR'] = os.getcwd() + "/configs/"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
d={
'RollNumber':[1,2,3,4],
'StudentName':['kamal','vimal','vinoth','wahi'],
'Score':[64,68,61,86]}
df = pd.DataFrame(d)
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),

59
'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)
rollnumber=d['RollNumber']
names = d['StudentName']
values = d['Score']
fig=plt.figure("KGiSL Institute of Technology")
fig.set_figheight(4)
fig.set_figwidth(10)
plt.subplot(131)
plt.bar(names, values)
plt.ylabel('Score')
plt.xlabel('Student Names')
plt.suptitle('Student Grade Analyzer')
plt.show()

OUTPUT

60
RESULT
Thus, python program to develop student mark system and plot it was written,
executed and output is verified successfully.

61
EX.NO:8B LINEAR REGRESSION IMPLEMENTATION USING SCIPY
DATE:

AIM
To develop a python program for implementing Linear Regression using Scipy.

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 8: The coefficient of determination is displayed and the data is plotted.
Step 9: 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')

62
plt.legend()
plt.show()

OUTPUT

RESULT
Thus, python program to linear regression using scipy was written, executed and
output is verified successfully.

63
EX.NO:9A COPY CONTENTS FROM ONE FILE TO ANOTHER
DATE:

AIM
To develop a python program for copying content of one file to another.

ALGORITHM
Step 1: Start the procedure
Step 2: Creating a text file in read mode using open(filename,mode)function
Step 3: Creating a text file in write mode using open(filename,mode)function
Step 4: Read the contents of file1 using read() function
Step 5: Write the contents of file1 to file2 using write() function
Step 6: Close the file using close()function
Step 7: Stop the procedure
PROGRAM
#method 1
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()
#method 2
import shutil
shutil.copyfile('file2.txt','file3.txt')
print(" 'file2.txt' content Copied to 'file3.txt' using shutil package")
OUTPUT

RESULT
Thus, python program to copy content of one file to another was written, executed and
output is verified successfully.

64
EX.NO:9B WORD COUNT FROM A FILE
DATE:

AIM
To develop a python program to count words in a file.

ALGORITHM
Step 1: Start the procedure
Step 2: import the re module
Step 3: Using import keyword create a text file with contents and read the contents of
the text file
Step 4: Using findall() function count the word count in the text file using looping
statements
Step 5: Using for loop display the word count in the text file
Step 6: Stop the procedure

PROGRAM
import re
words=re.findall('\w+', open('text1.txt').read().lower())
print("number of words in textfile :", len(words))
uniquewords=set(words)
print("number of unique words in textfile :", len(uniquewords))

OUTPUT

RESULT
Thus, python program to count number of words in a file was written, executed and
output is verified successfully.

65
EX.NO:9C LONGEST WORD IN A FILE

AIM
To develop python program for finding longest word in a file.

ALGORITHM
Step 1: Start the procedure
Step 2: import the re module
Step 3: Using import keyword create a text file with contents and read the contents of
the text file
Step 4: Using findall() function find the longest word in the text file using looping
statements and conditional statement
Step 5: Using for loop and if condition display the longest word in the text file
Step 6: Stop the procedure

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
Thus, python program to find longest word in a given file was written, executed and
output is verified successfully.

66
EX.NO:10A DIVIDE BY ZERO EXCEPTION
DATE:

AIM
To develop python program for finding divide by zero exception.

ALGORITHM
Step 1: Start the program.
Start 2: Get the value of n, d and c from the user.
Step 3: Calculate q=n/(d-c) and print
Step 4: Except zero division Error, then print (“Division by Zero”)
Step 5: Stop the program.

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
Thus, python program to find divide by zero exception was written, executed and
output is verified successfully.

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

AIM
To develop python program to validate voter‟s age.

ALGORITHM
Step 1: Start the program.
Step 2: Get Year _ of _ birth from the user.
Step 3: Initialize current year = datetime. Datetime . now() . year Current _ age =
current _ year _ of _ birth
Step 4: Print( “ Your current age “ )
Step 5: If (current age < = 18) then print you are not eligible to vote.
Step 6: Stop the program.

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
except NameError as e:
error=e
finally:
if not error:
for people in peoplelist:
name,age=people.split(' ')
if int(age)>=18:
print(name," - you are 'eligible' for vote in india")
else:
print(name," - you are 'not eligible' for vote in india")
else:

68
print(error)

OUTPUT

RESULT
Thus, python program to validate voter‟s age was written, executed and output is
verified successfully.

69
EX.NO:10C STUDENT MARK RANGE VALIDATION
DATE:

AIM
To develop python program for validating student marks.

ALGORITHM
Step 1: Start the program.
Step 2: Create a file as student mark list with student name, roll number and marks.
Step 3: Import re module, and open the file in try block.
Step 4: The content is read, then in except block check for IO errors.
Step 5: In, finally block if condition is used to check the error, If not the error, the
students marks are checked and grade is allocated using for loop.
Step 6: The error is displayed or the student roll no. grade is displayed.
Step 7: Stop the program.
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)

70
OUTPUT

RESULT
Thus, python program to validate student marks was written, executed and output is
verified successfully.

71
EX.NO:11 PYGAME BASICS
DATE:

AIM
To learn basics of pygame.

ALGORITHM
STEP 1: Import the pygame module
STEP 2: To generate random values from a range import the module ranint from the
package random
STEP 3: Assign width and height values to the window
STEP 4: Set screen color and store the values in tuple
STEP 5: To Initialize pygame window
STEP 6: Create the screen object of specific dimension width and height
STEP 7: Set a font object to the window
STEP 8: Stop the program.

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

72
pygame.init()
screen = pygame.display.set_mode((width, height))
font = pygame.font.Font(None, 24)
running = True

OUTPUT

RESULT
Thus, python program to develop pygame window was written, executed and output is
verified successfully.

73
EX.NO:12 BOUNCING A BALL USING PYGAME
DATE:

AIM
To develop python program for simulating bouncing ball using Pygame.

ALGORITHM
Step 1: Start the program.
Step 2: Import modules sys and pygame.
Step 3: Initialize pygame using init().
Step 4: Initialize the pygame window.
Step 5: Load the image to the pygame window.
Step 6: Using while loop make the image to bounce infinite times.
Step 7: Stop the program.

PROGRAM
import sys, pygame
pygame.init()
size = width, height = 700, 300
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]

74
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()

OUTPUT:

RESULT:
Thus, python program to simulate bouncing using pygame was executed and verified
successfully.

75

You might also like