Ge3171 – Problem Solving and Python Programming Laboratory Manual (2)
Ge3171 – Problem Solving and Python Programming Laboratory Manual (2)
LAB MANUAL
Compiled By:
AP/CSE,
Mannargudi,Thiruvarur Dt,
Tamilnadu.
A.R.J COLLEGE OF ENGINEERING AND TECHNOLOGY,
MANNARGUDI.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
INSTITUTE
VISION
MISSION
MI1:To have in-depth domain knowledge with analytical and practical skills in cutting
edgetechnologies by imparting quality technical education.
DEPARTMENT:
VISION
MISSION
PSO-2: Enrich the ability to design and develop software and qualify for Employment
Higher studies and Research.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
12. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of
technologicalchange.
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY L T P C
0 0 4 2
COURSE OBJECTIVES:
To understand the problem solving approaches.
To learn the basic programming constructs in Python.
To practice various computing strategies for Python-based solutions to real world problems.
To use Python data structures - lists, tuples, dictionaries.
To do input/output with files in Python.
EXPERIMENTS:
Note: The examples suggested in each experiment are only indicative. The lab instructor is
expected to design other problems on similar lines. The Examination shall not be restricted
to the sample experiments listed here.
1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a
motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of
list & tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas,
numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to
another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
TOTAL : 60 PERIODS
COURSE OUTCOMES:
On completion of the course, students will be able to:
CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
TEXT BOOKS:
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition,
O’Reilly Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition,
2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers
and Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python: With
Applications to Computational Modeling and Understanding Data”, Third Edition, MIT Press,
2021.
4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to
Programming”, 2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
EX. NO: 1 SOLVING AND DEVELOPING FLOW CHARTS FOR THE SIMPLE REAL
LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: (EXCHANGE THE VALUES OF TWO VARIABLES)
AIM:
To Draw flow chart for Addition of two numbers, Swapping the values of two variables, Finding
factorial of the number, Biggest of three numbers, Number is ODD or Even etc.,
ALGORITHM
Main function
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
FLOWCHART:
1.2. SIN SERIES
FLOWCHART FOR ELECTRICITY BILLING
COMPUTING FACTORIAL OF GIVEN NUMBER
ALGORITHM
Start
Read N
Initializei = 1 and Fact = 1
While i<=N
Fact=Fact* i
i=i+1 //Increase the value of i by 1
ENDWHILE
Display Fact
End
FLOWCHART
BIGGEST OF THREE NUMBERS:
ALGORITHM:
FLOWCHART
ALGORITHM
Step 1: Start
Step 2: Get value of n.
Step 3: initialize i=1
Step 4: While(i<=n)
Print i value
increment i value by 1
Step 5: Stop
FLOWCHART FOR PRINTING ‘N’ NATURAL NUMBER
SWAPPING ALGORITHM:
Step 1 : Start
Step 2 : Read the value of a, b
Step 3 : Swap the values without using a temporary variable.
a=a+b
b=a-b
a=a-b
Step 4 : Print the value of a, b
Step 5 : Stop
FLOWCHART:
RESULT
Thus the Python program for exchanging the values of two variables using simple
statements and expressions was executed successfully.
EX. NO: 2 (A) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (EXCHANGE THE VALUES OF TWO VARIABLES)
AIM:
To write a Python program to exchange the values of two variables
ALGORITHM:
Step 1: Start the program
Step 2: Read two numbers
Step 3: Assign the second variable to the first variable
Step 4: Assign the first variable to the second variable
Step 5: After assigning of values print the two variables
Step 6: Stop the program
PROGRAM:
a=10
b=20
print("Before Swapping the values are")
print(“Value of a”,a)
print(“Value of b”,b)
a,b=b,a
print("After Swapping the values are ")
print(“Value of a”,a)
print(“Value of b”,b)
OUTPUT:
Before Swapping the values are
Value of a 10
Value of b 20
After Swapping the values are
Value of a 20
Value of b 10
RESULT
Thus the Python program for exchanging the values of two variables using simple
statements and expressions was executed successfully.
EX. NO: 2 (B) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (CIRCULATE THE N NUMBER OF VARIABLES)
AIM:
ALGORITHM:
Step 4: Circulate the ‘n’ number of variables using for Loop and Print the list values
PROGRAM:
b=len(a)
for i in range(b):
print(a[i:]+a[:i])
OUTPUT:
RESULT:
Thus the python program to circulate the n number of variables was executed successfully
EX. NO: 2 (C) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS
DATE: (DISTANCE BETWEEN TWO POINTS)
AIM:
To write a python program to find the distance between the two points.
ALGORITHM:
PROGRAM :
import math
print("Enter value of x1")
x1=int(input())
print("Enter value of x2")
x2=int(input())
print("Enter value of y1")
y1=int(input())
print("Enter value of y2")
y2=int(input())
dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print("The distance between two points is: ",dist)
OUTPUT:
Enter value of x1 6
Enter value of x2 3
Enter value of y1 9
Enter value of y2 8
Distance between two points is: 3.16
RESULT:
Thus the python program to find distance between the two points are executed successfully.
EX. NO: 3 (A) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (NUMBER SERIES)
AIM:
To write a python program to print the number series.
ALGORITHM:
OUTPUT:
Enter value of n 5
1
2
3
4
5
RESULT:
Thus the python program to print the number series has been printed successfully.
EX. NO: 3 (B) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (NUMBER PATTERN)
AIM:
To write a python program to print the number pattern.
ALGORITHM:
PROGRAM:
OUTPUT:
1
12
123
1234
12345
RESULT:
Thus the python program for printing the number pattern is printed successfully.
EX. NO: 3 (C) SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
LOOPS
DATE: (PYRAMID PATTERN)
AIM:
To write a python program to print the pyramid pattern.
ALGORITHM:
Step 1: Start the program
Step 2: Read the value of ‘n’ as input
Step 3: Use the nested for loop for accessing the values for i in range(n)and j in range(i+1).
Step 5: Printing the * pattern after the loop is nested
Step 6: Stop the program .
PROGRAM:
for i in range(n):
for j in range(i+1):
print("* ",end="")
print("\r")
OUTPUT:
ENTER THE INPUT 5
*
**
***
****
*****
RESULT:
Thus the program to print pyramid pattern was printed successfully.
EX. NO: 4 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING LIST AND TUPLES
DATE: (ITEMS PRESENT IN A LIBRARY)
AIM: To write a Python program to print the items present in the library
ALGORITHM:
Step 1: Start the program
Step 2: Create a list and enter some values
Step 3: append a new value and another value in the list
Step 4: Pop one element from the list
Step 5: Convert the popped element as a tuple
Step 6: Print the tuple
Step 7: Stop the program
PROGRAM:
# Lists
l = ["War And Peace","Kanavu Kannugal","Turning Point"]
ind=l.index("Turning Point")
print("Element is present",ind)
# Adding Element into list
l.append("Rich And Poor")
l.append("Indian Girl")
print("Adding New Books", l)
# Popping Elements from list
l.pop()
print("Popped one element from list", l)
print()
# Tuple
t = tuple(l)
# Tuples are immutable
print(" Book Tuples are:", t)
print()
OUTPUT:
Element is present 2
Adding New Books
['War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor', 'Indian Girl']
Popped one element from list
['War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor']
Book Tuples are: ('War And Peace', 'Kanavu Kannugal', 'Turning Point', 'Rich And Poor')
RESULT: Thus, Python program for showing Library items using LIST & TUPLES is executed.
EX. NO: 4 (B) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
LIST AND TUPLES
DATE: (COMPONENTS OF A CAR)
ALGORITHM:
PROGRAM :
l1 = ["Engine","Radiator","Alternator","Brakes"]
c=len(l1)
print (l1)
print("Before Extending",c)
l1.extend(["Steering","Suspension"])
print (l1)
c1 = len(l1)
print ("After Extending",c1)
#converting list to tuple
tu = tuple(l1)
print("Afetr Converting Into Tuple",tu)
sor = sorted(tu)
print ("After Sorting: Components are")
print (sor)
OUTPUT:
RESULT: Thus, the python program for showing Components of automobile using LIST
and TUPLES was executed successfully.
EX. NO: 4 (C) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING LIST AND TUPLES
DATE: (MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING)
AIM:
To write a Python program to print the Materials required for construction of a building
ALGORITHM:
Step 1: Start
Step 2: Create a list and enter some values
Step 3: Print the reversed list using the index number
Step 4: Print the length of the list using built-in len function in python
Step 5: Stop the program
PROGRAM:
Items=["Cement","Sand","Bricks","Tiles","Paint"]
print("The reverse of the list is:",Items[::-1])
del Items[2]
print("The list after deleting an element is:",Items)
OUTPUT:
The reverse of the list is: ['Paint', 'Tiles', 'Bricks', 'Sand', 'Cement']
The list after deleting an element is: ['Cement', 'Sand', 'Tiles', 'Paint']
RESULT:
Thus, the python program for showing Materials required for construction of a building
using SETS was executed successfully.
EX. NO: 5 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE: (COMPONENTS OF AUTOMOBILE USING SETS)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create a set and enter some values
Step 3: Search for a key value in the set
Step 4: If the key value is present in the list, Print true
Step 5: Otherwise Print False
Step 6: Stop the program
PROGRAM:
OUTPUT:
Components of a Car:
{'Clutch', 'Brake', 'Chase', 'Engine', 'Gearbox'}
Key Item Clutch is Present or not: True
Key Item Gear is Present or not: False
RESULT:
Thus, the python program for showing Components of automobile using sets was
executed successfully.
EX. NO: 5 (B) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE: (COMPONENTS OF AN AUTOMOBILE USING DICTONARIES)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create a Dictionary and enter some values
Step 3: Search for a key value in the Dictionary
Step 4: If the key value is present in the Dictionary, Print the value in the dictionary
Step 5: Re-assign the value in the dictionary
Step 6: Print the reassigned value in the dictionary
Step 7: Stop the program
PROGRAM:
dict ={'Gearbox' : "5 Speed",'Brakingsystem' : "ABS", 'Chassis': "10x10 Chassis",'Engine' : "200 CC"}
# reassigning value
dict['Engine'] = "350 CC"
print("The reassinged value is",dict)
OUTPUT:
RESULT:
Thus, the python program for showing Components of an automobile using dictionary
was executed successfully.
EX. NO: 5 (C) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
USING SETS AND DICTIONARIES
DATE : (ELEMENTS OF A CIVIL STRUCTURE USING SETS AND DICTIONARIES)
AIM:
To write a Python program to print the Elements of a civil structure using sets
ALGORITHM:
Step 1: Start
Step 2: Create a set and enter some values
Step 3: Create another set and enter some values in it.
Step 4: Print the Union of the two sets
Step 5: Print the intersection of the two sets
Step 6: Stop the program
PROGRAM:
A={"Foundation","Floors","Beams"}
B={"Roofs","Stairs","Foundation"}
print("The Union is:",A|B)
print("The Intersection is:",A&B)
OUTPUT:
RESULT:
Thus, the python program for showing Elements of a civil structure using SETS was
executed successfully.
EX. NO: 6 (A) IMPLEMENTING PROGRAMS USING FUNCTIONS
(FACTORIAL)
DATE:
ALGORITHM:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact
PROGRAM:
def factorial(n):
if n==0:
return 1
else:
fact=n*factorial(n-1)
return fact
print("Enter a number :")
n=int(input())
print("Factorial of ",n," is ",factorial(n))
OUTPUT:
Enter a number :
5
Factorial of 5 is 120
RESULT:
Thus the given Python program for factorial program using function has been executed
successfully.
EX. NO: 6 (B) IMPLEMENTING PROGRAMS USING FUNCTIONS
(LARGEST NUMBER IN A LIST)
DATE:
AIM:
Write a Python program, to find largest number in a list program using function.
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
Thus the given Python program to find the largest number in a list program
using function has been executed successfully.
EX. NO: 6 (C) IMPLEMENTING PROGRAMS USING FUNCTIONS
DATE: (AREA OF SHAPE)
AIM: Write a Python program, to find area of shape program using function.
ALGORITHM:
Step 1: Define two function as circle and rectangle
Step 2: Get the input of radius for circle function
Step 3: Calculate the Area of Circle and Print the Area of Circle as Output
Step 4: Get the input of Length and Breadth for rectangle function
Step 5: Calculate the Area of Rectangle and Print the Area of Rectangle as Output
Step 6: Stop the program
PROGRAM:
def circle():
print("Finding Area of circle")
print("Enter the radius of circle")
r=int(input())
a=3.14*r*r
print("Area of Circle",a)
def rectangle():
print("Finding area of Rectangle")
l=int(input("Enter the length of rectangle"))
b=int(input("Enter the breath of rectangle"))
a=l*b
print(”Area of Rectangle is”,a)
circle()
rectangle()
OUTPUT:
RESULT: Thus the given Python program to find the area of shape program using function has been
executed successfully.
EX. NO: 7 (A) IMPLEMENTING PROGRAMS USING STRINGS
(REVERSE THE STRING)
DATE:
AIM:
ALGORITHM:
PROGRAM:
s = input("Enter a String:")
print ("The original string is : ",end="")
print (s)
print ("The reversed string is : ",end="")
print(s[::-1])
OUTPUT:
RESULT:
Thus the python program for reverse the string using simple statements and expressions
was executed successfully.
EX. NO: 7 (B) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (PALINDROME OR NOT)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Input a String
Step 3: Compare String is equal to reversed string
Step 4: If the answer is yes
Step 5: Print It is a palindrome
Step 6: If the answer is no, Print It is not a Palindrome
Step 7: Stop the program
PROGRAM:
string=input(("Enter a string:"))
if(string==string[::-1]):
else:
print("Not a palindrome")
OUTPUT:
RESULT:
Thus the python program for check whether the string is palindrome using simple
statements and expressions was executed successfully.
EX. NO: 7 (C) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (TO FIND THE CHARACTER COUNT)
AIM:
To write a Python program to find the Character Count .
ALGORITHM:
Step 1: Start
Step 2: Input a String
Step 3: Get the char=0
Step 4: Using For loop add character values
Step 5: Print the number of Characters.
PROGRAM:
str=input("Enter String:")
char=0
for i in str:
char=char+1
OUTPUT:
RESULT:
Thus the python program to find the character count using simple statements and
expressions was executed successfully.
EX. NO: 7 (D) IMPLEMENTING PROGRAMS USING STRINGS
DATE: (REPLACING THE CHARACTERS IN THE STRING)
ALGORITHM:
PROGRAM:
string1 = "Puthon"
list1 = list(string1)
list1[1] = "y"
string1 = "".join(list1)
OUTPUT:
The new List is: ['P', 'y', 't', 'h', 'o', 'n']
After Joining, The String is Python
RESULT:
Thus the python program to replace the character count using simple statements and
expressions was executed successfully.
EX. NO: 8 (A) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (PANDAS)
AIM:
ALGORITHM:
PROGRAM:
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
print(myvar)
OUTPUT:
Cars Passings
0 BMW 3
1 Volvo 7
2 Ford 2
RESULT:
Thus, the python program for showing Library function (Pandas) was executed
successfully.
EX. NO: 8 (B) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (NUMPY)
AIM:
ALGORITHM:
PROGRAM:
import numpy
print(arr)
OUTPUT:
[1 2 3 4 5]
RESULT:
Thus, the python program for showing Library function (Numpy) was executed
successfully.
EX. NO: 8 (C) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (MATPLOTLIB)
ALGORITHM:
PROGRAM:
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
plt.savefig(sys.stdout.buffer)
OUTPUT:
RESULT:
Thus, the python program for showing Liabrary function (Matplotlib) was executed
successfully.
EX. NO: 8 (D) IMPLEMENTING PROGRAMS USING WRITTEN
MODULES AND PYTHON STANDARD LIBRARIES
DATE: (SCIPY)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Import Scipy library
Step 3: Import Scientific Constants
Step 4: Then print the constant of pi(𝜋)
Step 5: Stop the program
PROGRAM:
print(constants.pi)
OUTPUT:
3.141592653589793
RESULT:
Thus, the python program for showing Liabrary function (Scipy) was executed
successfully.
EX. NO: 9 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
FILE HANDLING
DATE: (COPY FROM ONE FILE TO ANOTHER)
ALGORITHM:
f1=open("D:\GK\PYTHON\GK.txt","r")
f2=open("D:\GK\PYTHON\GK1.txt","w")
for line in f1:
f2.write("\n"+line)
f1.close( )
f2.close( )
OUTPUT:
Content of Source file:
I will try my best.
God is always with me!!
Content of Copied file:
I will try my best.
God is always with me!!
PROGRAM 2:
print("Content of Source file:")
f1=open("D:\GK\PYTHON\GK.txt","r")
print(f1.read( ))
print("Content of Copied file:")
f2=open("D:\GK\PYTHON\GK1.txt","r")
print(f2.read( ))
RESULT: Thus, Python program for copy from one file to another was executed successfully.
EX. NO: 9 (B) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING FILE HANDLING
DATE: (WORD COUNT)
AIM:
ALGORITHM:
PROGRAM:
n=0
f=open("GK.txt",'r')
for line in f:
words=line.split()
n=n+len(words)
print("Number of words:",n)
OUTPUT:
Number of words: 10
RESULT:
Thus, the python program for counting words in a file was executed successfully.
EX. NO: 9 (C) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING FILE HANDLING
DATE: (LONGEST WORD IN A FILE)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read a file
Step 3: Split the lines.
Step 4: Use len variable to find the length of each word
Step 5: Print the longest word.
Step 6: Stop the program
PROGRAM:
def longest_word(filename):
words = infile.read().split()
OUTPUT:
RESULT:
Thus, the python program for counting longest words in a file was executed successfully.
EX. NO: 10 (A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
EXCEPTION HANDLING.
DATE: (DIVIDE BY ZERO ERROR)
ALGORITHM:
PROGRAM:
try :
a=int(input("Enter value of a: "))
b=int(input("Enter value of b: "))
c=a/b
except ValueError:
print("You have entered wrong data")
except ZeroDivisionError:
print("Divide by Zero Error!!!")
else:
print("The result: ",c)
OUTPUT:
Enter value of a: 5
Enter value of b: 0
Divide by Zero Error!!!
Enter value of a: 6
Enter value of b: 3
The result: 2.0
RESULT: Thus, the python program for handling exceptional cases (Divide by zero) was
executed successfully.
EX. NO: 10 (B) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING EXCEPTION HANDLING.
DATE: (VOTER’S AGE VALIDITY)
AIM: To write a Python program to handle exceptional cases (Voter’s age validity)
ALGORITHM:
Step 1: Start
Step 2: Define a Function
Step 3: Input a Variable
Step 4: Check the variable with if condition
Step 5: If it is true then print Eligible to vote
Step 6: Otherwise print Not eligible to vote
Step 7: If the given value is not an int throw error
Step 8: Stop the program
PROGRAM:
try :
age=int(input("Enter your age:"))
except ValueError:
print("You have entered wrong data")
else:
if age>=18:
print("Eligible to vote")
else:
print("Not eligible to vote")
OUTPUT:
RESULT: Thus, the python program for handling exceptional cases (Voter’s age validity) was
executed successfully.
EX. NO: 10 (C) IMPLEMENTING REAL-TIME/TECHNICAL
APPLICATIONS USING EXCEPTION HANDLING.
DATE: (STUDENT MARK RANGE VALIDATION)
AIM:
To write a Python program to handle exceptional cases (Student mark range validation)
ALGORITHM:
Step 1: Start
Step 2: Get the mark inputs
Step 3: Calculate Total and Average of Marks
Step 4: Print the Total and Average
Step 5: If Input mark is not valid Throwback error
Step 6: Stop the program
PROGRAM:
try :
print("Enter Marks Obtained in 5 Subjects: ")
M1 = int(input())
M2 = int(input())
M3 = int(input())
M4 = int(input())
M5 = int(input())
tot = M1+M2+M3+M4+M5
avg = tot/5
except ValueError:
print("You have entered wrong data")
else:
print("Total is",tot)
print("Average is",avg)
if avg>=90 and avg<=100:
print("Your Grade is A")
elif avg>=80 and avg<91:
print("Your Grade is B")
elif avg>=70 and avg<81:
print("Your Grade is C")
elif avg>=60 and avg<71:
print("Your Grade is D")
elif avg>=50 and avg<61:
print("Your Grade is E")
elif avg<50:
print("YOUR ARE FAIL")
OUTPUT:
Enter Marks Obtained in 5 Subjects:
96
52
36
98
89
Total is 371
Average is 74.2
Your Grade is C
RESULT:
Thus, the python program for handling exceptional cases (Student mark range
validation) was executed successfully.
EX. NO: 11
EXPLORING PYGAME TOOL
DATE:
ALGORITHM:
Step 1: Start
Step 2: Install Pygame package
Step 3: Import Pygame package
Step 4: Use Certain functions to create a game
Step 5: Stop the program
PROGRAM:
# -- coding: utf-8 --
import time
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
pygame.display.set_caption('Hello World')
screen.fill([0, 0, 0])
pygame.display.flip()
time.sleep(5)
OUTPUT:
RESULT: Thus, the python program for exploring pygame was executed successfully.
EX. NO: 12
GAME DEVELOPMENT USING PYGAME
DATE: (CAR RACING GAME)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Install Pygame package
Step 3: Import Pygame package
Step 4: Use Certain functions to create a game
Step 5: Stop the program
PROGRAM:
import random
from time import sleep
import pygame
classCarRacing:
def init (self):
pygame.init()
self.display_width =800
self.display_height =600
self.black =(0,0,0)
self.white =(255,255,255)
self.clock = pygame.time.Clock()
self.gameDisplay =None
self.initialize()
definitialize(self):
self.crashed =False
self.carImg = pygame.image.load('.\\img\\car.png')
self.car_x_coordinate =(self.display_width *0.45)
self.car_y_coordinate =(self.display_height *0.8)
self.car_width =49
# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_startx = random.randrange(310,450)
self.enemy_car_starty =-600
self.enemy_car_speed =5
self.enemy_car_width =49
self.enemy_car_height =100
# Background
self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_x1 =(self.display_width /2)-(360/2)
self.bg_x2 =(self.display_width /2)-(360/2)
self.bg_y1 =0
self.bg_y2 =-600
self.bg_speed =3
self.count =0
defcar(self,car_x_coordinate,car_y_coordinate):
self.gameDisplay.blit(self.carImg,(car_x_coordinate, car_y_coordinate))
defracing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width,self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()
defrun_car(self):
whilenotself.crashed:
if(event.type == pygame.KEYDOWN):
if(event.key == pygame.K_LEFT):
self.car_x_coordinate -=50
print("CAR X COORDINATES: %s"%self.car_x_coordinate)
if(event.key == pygame.K_RIGHT):
self.car_x_coordinate +=50
print("CAR X COORDINATES: %s"%self.car_x_coordinate)
print("x: {x}, y: {y}".format(x=self.car_x_coordinate,y=self.car_y_coordinate))
self.gameDisplay.fill(self.black)
self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx,self.enemy_car_starty)
self.enemy_car_starty +=self.enemy_car_speed
ifself.enemy_car_starty >self.display_height:
self.enemy_car_starty =0-self.enemy_car_height
self.enemy_car_startx = random.randrange(310,450)
self.car(self.car_x_coordinate,self.car_y_coordinate)
self.highscore(self.count)
self.count +=1
if(self.count %100==0):
self.enemy_car_speed +=1
self.bg_speed +=1
ifself.car_y_coordinate <self.enemy_car_starty +self.enemy_car_height:
ifself.car_x_coordinate >self.enemy_car_startx andself.car_x_coordinate
<self.enemy_car_startx +self.enemy_car_width orself.car_x_coordinate +self.car_width
>self.enemy_car_startx andself.car_x_coordinate +self.car_width <self.enemy_car_startx
+self.enemy_car_width:
self.crashed =True
self.display_message("Game Over !!!")
pygame.display.update()
self.clock.tick(60)
defdisplay_message(self,msg):
font = pygame.font.SysFont("comicsansms",72,True)
text = font.render(msg,True,(255,255,255))
self.gameDisplay.blit(text,(400- text.get_width()//2,240- text.get_height()//2))
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
defback_ground_raod(self):
self.gameDisplay.blit(self.bgImg,(self.bg_x1,self.bg_y1))
self.gameDisplay.blit(self.bgImg,(self.bg_x2,self.bg_y2))
self.bg_y1 +=self.bg_speed
self.bg_y2 +=self.bg_speed
ifself.bg_y1 >=self.display_height:
self.bg_y1 =-600
ifself.bg_y2 >=self.display_height:
self.bg_y2 =-600
defrun_enemy_car(self,thingx,thingy):
self.gameDisplay.blit(self.enemy_car,(thingx, thingy))
defhighscore(self,count):
font = pygame.font.SysFont("arial",20)
text = font.render("Score : "+str(count),True,self.white)
self.gameDisplay.blit(text,(0,0))
defdisplay_credit(self):
font = pygame.font.SysFont("lucidaconsole",14)
text = font.render("Thanks for playing!",True,self.white)
self.gameDisplay.blit(text,(600,520))
OUTPUT:
RESULT:
Thus, the development of game activity using Pygame (car race) was executed
successfully.