GE3171 - Python Manual New
GE3171 - Python Manual New
GE3171 - Python Manual New
Page
Ex.No Date Name of the Exercise Marks
No
Identification and solving of simple real life problems and developing flow charts
a) Electricity Bill
1 b) Sin series
c) Weight of a Motor Bike
d) Weight of a Steel Bar
Basic Python Programs using simple statements and expressions
Aim:
To write a python program to print electricity bill.
Algorithm:
Step 1: Start the program
Step 2: Read the current reading in cr and previous reading in prStep
3: Calculate total consumed by subtracting cr with pr
Step 4: if total consumed is between 0 and 101, print amount to pay is consumed * 2
Step 5: if total consumed is between 100 and 201, print amount to pay is consumed * 3
Step 6: if total consumed is between 200 and 501, print amount to pay is consumed * 4
Step 7: if total consumed is greater than 500, print amount to pay is consumed * 5
Step 8: if total consumed is less than one print invalid reading
Step 9: Stop
Flowchart
Start
Get
the
unit
U
value
Y U N
es o
N
Bill = 0 o
Y
es
Bill =
U*2
Y
Bill =
es
U*3
Prin
t bill
Stop
Program:
cr=int(input("Enter current month reading"))
pr=int(input("Enter previous month reading"))
consumed=cr - pr
if(consumed >= 1 and consumed <= 100):
amount=consumed * 2 print("your
bill is Rs.", amount)
elif(consumed > 100 and consumed <=200):
amount=consumed * 3
print("your bill is Rs.", amount)
elif(consumed > 200 and consumed <=500):
amount=consumed * 4
print("your bill is Rs.", amount)
elif(consumed > 500):
amount=consumed * 5
print("your bill is Rs.", amount)
else:
print("Invalid reading")
O/P:
Enter current month reading 500
Enter previous month reading 200
your bill is Rs. 1200
Result: Thus the python program for generating electricity bill is executed and the results are
Verified
EX. No.: 1b Python program for sin series
Algorithm:
Step 1: Start
Step 2: Read the values of x and n
Step 3: Initialize sine=0
Step 4: Define a sine function using for loop, first convert degrees to radians.
Step 5: Compute using sine formula expansion and add each term to the sum variable.Step 6:
Print the final sum of the expansion.
Step 7: Stop.
Flowchart
Start
Get x and i
;
For j in range (1, i)
Display x
5
Program:
import math
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
print(sine)
O/P:
Enter the value of x in degrees:3
Enter the number of terms:2
0.05235699888420977
Result:
Thus the python program for sin series is executed and the results are verified
6
EX. No.: 1c Weight of a Motor Bike
Algorithm:
Step 1: Start the program
Step 2: Read the value of a mass
Step 3: Calculate the weight of a motor bike by multiplying mass with 9.8 and store it in weightStep 4:
Print the weight
Step 5: Stop
Program:
mass = float(input("Enter the Mass of the MotorBike: "))
Weight =mass*9.8
print(“ The weight of a Motor Bike for a given mass is ”,Weight)
O/P:
Enter the Mass of the MotorBike: 100
The weight of a Motor Bike for a given mass is 980.0000000000001
Result:
Thus the python program to calculate the weight of a motor bike is executed and the
results are verified.
7
EX. No.: 1d Weight of a Steel Bar
Algorithm:
Program:
O/P:
Enter the Diameter of the Rounded Steel Bar:2
Enter the Length of the Rounded Steel Bar:15
Weight of a Steel Bar is 0.3697313285679073
Result:
Thus the python program to calculate the weight of a steel bar is executed and the
results are verified.
8
EX. No.: 2a Exchange the value of two variables
Aim
To implement the pyhton program to swap two variable using simple expression.
Algorithm
Step1: get the input values from the user
Step2: Assign the value of the 1st variable to a temporary variable
Step3: Assign the value of the 2nd variable to the 1st variable
Step4: Assign the value of the temporary vaiable to the 2nd variable.
Step5: print the swapped variable values.
PROGRAM:
print("Swapping using temporary variable")
a = int(input("a = "))
b = int(input("b = "))
print("Before Swapping")
print("a = ", a)
print("b = ", b)
c=a
a=b
b=c
print("After Swapping")
print("a = ", a)
print("b = ", b)
Output
Enter the value for A: 10
Enter the value for B: 20
The Value of A after swapping: 20
The Value of B after swapping: 10
Result
Thus the program to swapping of two variables is executed and the output is obtained
successfully.
9
EX. No.: 2b circulate the values of n variables
Aim
To implement the python program to circulate the values of n-variables using simple expression.
Algorithm
Step1:Get the list of numbers from the user
Step2:Get the number of times the list should circulate
Step3:Then slice the given list into 2 lists
Step4:Add the two separated list.
Step5:Repeat step 3and 4 till the list circulate.
Program
def circulate(A, N):
fori in range(1, N+1):
B = A[i:] + A[:i]
print(“Circulation”, i , “=”, B)
return
i = int(input(“Enter number of values to be entered: ”))
list=[]
for val in range(0,i,1):
element = int(input(“Enter the integer: “))
list.append(element)
n = int(input(“Enter the number of times to circulate the list: “))
circulate(list,n)
Output
Enter number of values to be entered: 5
Enter the integer:11
Enter the integer:21
Enter the integer:31
Enter the integer:41
Enter the integer:51
Enter the number of times to circulate the list:3
Circulation 1 = [21, 31, 41, 51, 11]
Circulation 2 = [31, 41, 51, 11, 12]
Circulation 3 = [41, 51, 11, 12, 13]
Result
Thus the program to implement circulation of values with n-variable is executed and the output is
obtained successfully. 10
EX. No.: 2c Distance Between Two Points
Aim
To implement the python program to find the distance between two points using simple
expression.
Algorithm
Step1:Start the program
Step2:Get the 2 points (x1,x2) and (y1,y2) from the user
Step3:Then calculate the distance between two points using a formula
Step4:display the result to the user using print statement
Step5:Stop the program
PROGRAM:
import math x1=int(input("enter
x1"))y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance = math.sqrt((x2-x1)**2)+((y2- y1)**2)
print(distance)
Output
Enter x1: 4
Enter x2: 6
Enter y1: 0
Enter y2: 6
Distance between (4,6) and (0,6) is: 6.324555320336759
Result
Thus the program to find the distance between 2 points is executed and the output is obtained
successfully. 11
EX. No.: 3a Number Series
Program:
n=int(input(" enter the number of terms for the series "))
i=1
x=0
while(i<=
n):
x=x*2+1
print(x, sep=
"")i+=1
Output
enter the number of terms for the series 5
1
3
7
15
31
Result:
Thus the python program to print numbers series is executed and verified.
12
EX. No.: 3b Number Patterns
Algorithn:
Step 1: Start the program
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to i ;
Step 6: Set j in inner loop using range function and i integer will be initialized to j;
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.
PROGRAM:
n=int(input("enter number of rows needed: "))
for i in range(n):
for j in range(i+1):
print(j+1,end=" ")
print()
OUTPUT:
Enter the number of rows 6
1
22
333
4444
55555
666666
RESULT: 13
Thus the python programs to print number patterns have been done successfully and theoutput is
verified.
EX. No.: 3c Pyramid Pattern
Algorithm:
Step 1: Start the program
Step 2: Read the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = 0 to rows ;
Step 6: Set j in inner loop using range function, j=0 to i+1; Step
7: Print * until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.
PROGRAM:
num=int(input("Enter the number of rows:"))
for i in range(0,num):
for j in range(0,num-i-1):
print(end=" ")
for j in range(0,i+1):
print("*",end=" ")
print( )
OUTPUT:
*
**
***
****
*****
RESULT:
Thus the python programs to print pyramid patterns have been done successfully and the output
is verified. 14
EX. No.: 4a Displaying unique elements in a List
Aim
To implement the python program to display unique elements in a list
Algorithm
Step 1: Get the items of library as input from the user
Step 2: Store the inputs in a list.
Step 3: Append a new item in the list.
Step 4: Add a new item to 3rd index of the list
Step 5: Remove an existing item from the list
Step 6: Remove an existing item from 2nd index of the list
Step 7: Convert the list into tuple
Step 8: Identify an item in the tuple by If condition
Step 9: Stop
PROGRAM:
print("Displaying unique elements in a list")
n = int(input("No of elements in a list: "))
mylist = []
for i in range(1,n+1):
data = int(input("Enter %d element: "%i))
mylist.append(data)
result_list = []
for value in mylist:
count = 0
for i in mylist:
if value == i:
count = count + 1
if count == 1:
result_list.append(value)
print("List of Unique elements in the list are ")
print(result_list)
15
SAMPLE OUTPUT:
Displaying unique elements in a list
No of elements in a list: 10
Enter 1 element: 1
Enter 2 element: 2
Enter 3 element: 3
Enter 4 element: 1
Enter 5 element: 3
Enter 6 element: 5
Enter 7 element: 7
Enter 8 element: 8
Enter 9 element: 2
Enter 10 element: 4
List of Unique elements in the list are
[5, 7, 8, 4]
RESULT:
Thus the python program to display only unique elements in a list has been done successfully and
the output is verified.
16
EX. No.: 4b Finding minimum value in a list
Aim
To implement the python program to find minimum value in a list
Algorithm
Step 1: Get the items from list.
Step 2: Get the items one by one
Step 3: Store the inputs in a list.
Step 4: Find minimum value of the list.
Step 5: Print the minimum value
Step 6: Stop the program
PROGRAM:
print("Minimum Element in a List")
mylist = [10, 5, 20, 3, 25, 50, 1, 89]
min = mylist[0]
for i in mylist:
if i < min:
min = i
print("Elements in the given list:")
print(mylist)
print("Minimum element value is ", min)
SAMPLE OUTPUT:
Minimum Element in a
List Elements in the given
list:
[10, 5, 20, 3, 25, 50, 1, 89]
Minimum element value is 1
RESULT:
Thus the python program to find the minimum value in a list has been done successfully and 17
the output is verified.
EX. No.: 4c Finding multiples of 5 in a tuple
Aim
To implement the python program to find multiples of 5 in a tuple.
Algorithm
Step 1: Get the items from tuple.
Step 2: Get the items one by one
Step 3: Store the inputs in a list.
Step 4: Find multiple of 5 in a tuple.
Step 5: Print the result value
Step 6: Stop the program
PROGRAM:
print("Multiple of 5 in a Tuple")
mytuple = (10, 5, 20, 3, 25, 50, 1, 89)
mylist = []
for i in mytuple:if i%5 ==0:
mylist.append(i)
print("Elements in the given tuple: \n", mytuple)
print("Multiple of 5 in a Tuple: \n", mylist)
OUTPUT:
Multiple of 5 in a Tuple
Elements in the given tuple:
(10, 5, 20, 3, 25, 50, 1, 89)
Multiple of 5 in a Tuple:
[10, 5, 20, 25, 50]
RESULT:
Thus the python program to find multiples of 5 in a tuple has been done successfully and the
output is verified.
18
EX. No.: 4c Library functionality using list
Aim: To write a python program to implement the library functionality using list.
Algorithm
Step 1: Start the program
Step 2: Initialize the book list
Step 3: Get option from the user for accessing the library function
1. Add the book to list 2.Issue a book 3. Return the book 4. View the list of book
Step 4: if choice is 1 then get book name and add to book list
Step 5: if choice is 2 then issue the book and remove from book list
Step 6: if choice is 3 then return the book and add the book to list
Step 7: if choice is 4 then the display the book list
Step 8: otherwise exit from menu
Step 9: Stop the program.
Program:
bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input(" \n 1. add the book to list \n 2. issue a book \n 3. return the book \n 4. view thebook list
\n 5. Exit \n"))
if(ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break
19
Output:
Welcome to library”
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
1
enter the book name NW
['OS', 'MPMC', 'DS', ' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
2
Enter the book to issue NW
['OS', 'MPMC', 'DS']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
3
enter the book to return NW
['OS', 'MPMC', 'DS', ' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
4
['OS', 'MPMC', 'DS', ' NW']
Result:
Thus the python program to implement the library functionality using list is executed
and the results are verified
20
EX. No.: 4d Components of car using list
Aim:
To write a python program to implement the operation of list for components of car.
Algorithm:
Step 1: Start the program.
Step 2: create a list of components for car
Step 3: get single component from user and append into list
Step 4: find the length of the list using len function
Step 5: find the minimum and maximum value of the list
Step 6: print the component using index of the list
Step 7: multiply the list element using multiplication operation
Step 8: check the component exist in the list or not using in operator
Step 9: Stop the program.
Program:
cc=['Engine','Front axle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print(cc)
print("length of the list:",len(cc))
print("maximum of the list:",max(cc))
print("minimum of the list:",min(cc))
print("indexing:",cc[3])
print("Battery" in cc)
print("multiplication of list element:",cc*2)
Output:
Enter the car components:tank
['Engine', 'Front axle', 'Battery', 'transmision', 'tank']length
of the list: 5
maximum of the list: transmision
minimum of the list: Battery
indexing: transmision
True
multiplication of list element: ['Engine', 'Front axle', 'Battery', 'transmision', 'tank', 'Engine','Front
axle', 'Battery', 'transmision', 'tank']
Result
Thus the python program to create a list for components of car and performed the
various operation and result is verified.
21
EX. No.: 4e Material required for construction of a building
Aim:
To write a python program to create a list for materials requirement of construction and
perform the operation on the list.
Algorithm:
Step 1: Start the program.
Step 2: Create a list of construction material.
Step 3: Sort the list using sort function.
Step 4: Print cc.
Step 5: Reverse the list using reverse function.
Step 6: Print cc.
Step 7: Insert y value by using index position.
Step 8: Slice the values using del function with start value and end up value.
Step 9: Print the cc.
Step 10: Print the position of the value by using index function.
Step 11: Print the values in the list of the letter ‘n’ by using for loop and member ship operator.
Step 12: Stop the program.
Program
cc=['Engine','Front axle','Battery','transmision']
cc.sort()
print(cc)
cc.reverse()
print(cc)
cc.insert(0, 'y')
print(cc)
del cc[:2]
print(cc)
print(cc.index('Engine'))
new=[] for
i in cc:
if "n" in i:
new.append(i)
print(new)
22
Output :
Result:
Thus the python program to create a list for construction of a building using list is
executed and verified.
23
EX. No.: 5a Languages using dictionaries
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: dict() is used to create a dictionary.
Step 4: To add a value, update() is used in key value pair.
Step 5: Calculate the total values in the dictionary using len() .
Step 6: Remove the particular key in the dictionary by using pop()
Step 7: Print the keys in the dictionary by using key()
Step 8: Print the values in the dictionary by using values()
Step 9: Print the key value pair in the dictionary using items()
Step 10: Clear the the key value pair by using clear()
Step 11: Delete the dictionary by using del dictionary
Program:
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"} #duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
print(" the length of the languages :",len(Language))
Language.pop(5)
print(" key 5 has been popped with value :",Language)
print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
Language.clear()
print(" The items are cleared in dictionary ",Language)
del Language
print(Language)
24
Output :
Empty Dictionary : {}
Using dict() the languages are : {'two': 'tamil', 1: 'english', 3: 'malayalam'}
the updated languages are : {'two': 'tamil', 1: 'english', 3: 'malayalam', 4: 'hindi', 5: 'hindi'}the length
of the languages : 5
key 5 has been popped with value : {'two': 'tamil', 1: 'english', 3: 'malayalam', 4: 'hindi'}the
keys are : dict_keys(['two', 1, 3, 4])
the values are : dict_values(['tamil', 'english', 'malayalam', 'hindi'])
the items in languages are : dict_items([('two', 'tamil'), (1, 'english'), (3, 'malayalam'), (4,'hindi')])
The items are cleared in dictionary {}
Traceback (most recent call last):
File "C:\Python34\1.py", line 17, in <module>print(Language)
NameError: name 'Language' is not defined
Result:
Thus the python program to implement languages using dictionaries is executed and
verified.
25
EX. No.: 5b Automobile using dictionaries
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: dict() is used to create a dictionary.
Step 4: Get the value in the dictionary using get()
Step 5: adding [key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using popitem().
Step 7: To check whether key is available in dictionary by using membership operator in.
Step 8: Stop the program.
Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is ",auto_mobile.get(2))
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile)
print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile parts")
print(2 in auto_mobile)
O/P:
Empty dictionary {}
Automobile parts : {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'}The
value for 2 is Clutch
Updated auto_mobile {1: 'Engine', 2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}(1,
'Engine')
The current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}Is 2
available in automobile parts
True
Result:
Thus the python program to implement automobile using dictionaries is executed and
verified.
26
EX. No.:5c Elements of a civil structure
Aim:
To write a python program to implement elements of a civil structure using dictionaries.
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: Create a dictionary using dict().
Step 4: To access the value in the dictionary indexing is applied.
Step 5: adding [key] with value to a dictionary using indexing operation..
Step 6: A copy of original dictionary is used by copy ().
Step 7: The length of the dictionary is by len().
Step 8: Print the values of the dictionary by using for loop
Step 9: Stop the program
Program:
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print(" The copy of civil_ele",new)
print(" The length is ",len(civil_ele))
for i in civil_ele:
print(civil_ele[i])
27
Output:
{}
the elements of civil structure are {1: 'Beam', 2: 'Plate'}the
value for key 1 is : Beam
{'three': 'concrete', 1: 'Beam', 2: 'Plate'}
The copy of civil_ele {'three': 'concrete', 1: 'Beam', 2: 'Plate'}
The length is 3
concrete
Beam
Plate
Result:
Thus the python program to implement elements of a civil structure using dictionaries
is executed and verified.
28
EX. No.:5d Library using sets
Algorithm:
Step 1: Start the program
Step 2: Create set {} with string values.
Step 3: To insert a value in a set use add function.
Step 4: To return a new set with distinct elements from all the sets use union ().
Step 5: To returns a set that contains the similarity between two or more sets useintersection().
Step 6: To clear all the values in a set use clear().
Step 7: Stop the program
Program:
Languages
old_books= {"MP","OOAD","NW"}
old_books.add("TOC")
print(old_books)
new_books= {"SE","AI"}
Library = old_books | new_books
print(" Union",Library)
Books1={"MP","OOAD","NW"}
Library = old_books & Books1
print(" Intersection ",Library)
print(old_books.clear())
Output:
{'OOAD', 'MP', 'NW', 'TOC'}
Union {'AI', 'SE', 'OOAD', 'MP', 'NW', 'TOC'}
Intersection {'OOAD', 'MP', 'NW'}
None
Result: Thus the python program to implement library using sets is executed and verified.
29
EX. No.:5e AutoMobile
Algorithm:
Step 1: Start the program
Step 2: Create a set.
Step 3: Update the values in the set by using update()
Step 4: Remove the value in the set using discard () Step
5: Print the values using set()
Step 6: check whether value in the set using membership operator in
Step 7: maximum value in the set using max()
Step 8: minimum value in the set using min()
Step 9: Stop the Program.
Program:
auto_mobile={"Engine","Clutch","GearBox"}
print(auto_mobile) auto_mobile.update(["2","3","4"])
print(auto_mobile)
auto_mobile.discard("2")
print(auto_mobile)
new= set("Engine")
print(new)
print('a' in auto_mobile)
maxi=max(auto_mobile)
print(maxi)
mini=min(auto_mobile)
print(mini)
30
Output:
{'Engine', 'Clutch', 'GearBox'}
{'3', 'Engine', '4', '2', 'Clutch', 'GearBox'}
{'3', 'Engine', '4', 'Clutch', 'GearBox'}
{'n', 'g', 'i', 'E', 'e'}
False
GearBox
3
Result:
Thus the python program to implement automobiles using set is executed and verified.
31
EX. No.:6a Factorial of a number using functions
Aim
To implement the python program to find a factorial of a given number using function
Algorithm
Step1:Get the number from the user to claculate the factorial
Step2:Define a function fact to calculate the factorial of a given number
Step3:Calculate the factorial of the given number
Step4:Store and return the factorial number
Step5:Print the factorial of the given number
Program
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return f
x=int(input(“Enter a number: “))
result = fact(x)
print(“Factorial of ”, x , “is ”, result)
Output
Enter a number:5
Factorial of 5 is 120
Result
Thus the program to calculate the factorial number is executed and the output is obtained successfully.
32
EX. No.:6b Largest number in a list using functions
Aim
To implement the python program to find the largest number from the list.
Algorithm
Step1:Getthe list of number from the user
Step2:Define a largest function to find the largest number among the list
Step3:Compare each and every number in the list
Step4:Store the largest number in one variable
Step5:Repeat Step3 and 4 till all the element in the list is compared
Step6: Finally print the largest number from the list
Program
def largest(x):
max=0
for i in x:
if i>max:
max=i
print(“The largest number in a list is: ”, max)
i = int(input(“Enter number of values to be entered: ”))
list=[]
for val in range(0,i,1):
element = int(input(“Enter the integer: “))
list.append(element)
largest(list)
Output
Enter number of values to be entered:5
Enter the integer:34
Enter the integer:45
Enter the integer:36
Enter the integer:25
Enter the integer:10
The largest number in a list is: 45
Result
Thus the program to find the largest number from the given list is executed and the output is obtained
successfully.
33
EX. No.:6c Area of shape using functions
Aim
To implement the python program to find the area of shape using functions
Algorithm
Step1:Get the shape name to calculate the area from the user
Step2:Get the data from the user according to the shape the area is calculated
Step3:Then call the respective function to calculate the area
Step4:Return the area of shape to the main program
Step5:And display the area of given shape.
Program
def square(l):
area=l*l
return area
def rectangle(l,b):
area=l*b
return area
def triangle(b,l):
area=(1/2)*b*l
return area
print(“Enter the shape from the following list”)
print(“Square = 1”)
print(“Rectangle = 2”)
print(“Triangle = 3”)
Print(“**************”)
user_input=0
while user_input not in (1,2,3):
user_input = int(input(“Enter your choice:”))
if(user_input ==1):
print(“Area of Square”)
length=int(input(“Enter the length of square: ”))
area = square(length)
print(“Area of square is: ”, area)
if(user_input ==2):
print(“Area of Rectangle”)
length=int(input(“Enter the length of rectangle: ”))
width=int(input(“Enter the width of rectangle: ”))
area = rectangle(length,width)
print(“Area of rectangle is: ”, area)
if(user_input ==3):
print(“Area of Triangle”)
length=int(input(“Enter the length of triangle: ”))
base=int(input(“Enter the base of triangle: ”))
area = triangle(length,base)
print(“Area of triangle is: ”, area)
34
Output
Enter the shape from the following list
Square =1
Rectangle =2
Triangle =3
***************
Enter your choice: 2
Area Rectangle
Enter length of rectangle:5
Enter width of rectangle:7
Area of Rectangle:35
Enter the shape from the following list
Square =1
Rectangle =2
Triangle =3
***************
Enter your choice: 1
Area square
Enter length of square:5
Area of Square:25
Enter the shape from the following list
Square =1
Rectangle =2
Triangle =3
***************
Enter your choice: 3
Area Triangle
Enter length of triangle:2
Enter base of triangle:7
Area of triangle:7
Result
Thus the program to find the area of given shape is executed and the output is obtained successfully.
35
EX. No.:7a Reverse of a string:
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string .Step
3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].Step
5: Print a
Step 6: Stop the program
Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!") print(a)
Output:
dlroW ,olleH
Result:
Thus the python program for reversing a string is executed and the results are
verified.
36
EX. No.:7b Palindrome of a string
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method. .Step
3: if string==string[::-1], print “ the string is palindrome ”. Step 4:
else print “ Not a palindrome ”.
Step 5: Stop the program
Program:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
Output:
Enter a string: madam The
string is a palindromeEnter
a string: nice
Not a palindrome
Result:
Thus the python program for palindrome of a string is executed and the results are
verified.
37
EX. No.:7c Character count
Algorithm:
Step 1: Start the program.
Step 2: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment thecount
by 1.
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.
Step 5: Stop the program.
Program:
a=input(" enter the string")
count = 0; #Counts each character except spacefor i in range(0, len(a)):
if(a[i] != ' '):
count = count + 1; #Displays the total number of characters present in the given string
print("Total number of characters in a string: " + str(count));
Output:
Result: Thus the python program for counting the characters of string is executed and theresults
are verified.
38
EX. No.:7d Replace of a string
Algorithm:
Step 1: Start the program.
Step 2: Define a string.
Step 3: Determine the character 'ch' through which specific character need to be replaced.
Step 4: Use replace function to replace specific character with 'ch' character.
Step 5: Stop the program.
Program 1:
string = "Once in a blue moon"ch = 'o' #Replace h with specific character ch
string = string.replace(ch,'h')
print("String after replacing with given character: ")
print(string)
OUTPUT
String after replacing with given character:
Once in a blue mhhn
Program 2:
str = "python is a programming language"
str2 = str.replace("python","C")
print("Old String: \n",str)
print("New String: \n",str2)
OUTPUT
Old String:
python is a programming language
New String:
C is a programming language
Result:
Thus the python program for replacing the given characters of string is executed and
the results are verified.
39
EX. No.:8 a Python Standard Libraries - Data Analysis using pandas
AIM
To implement the program for analysing the data on an array using pandas library.
ALGORITHM
Step 1: Import pandas library.
Step 2: creating data set using array for analysis.
Step 3:dataframe() function is used to extract the data for easy analysis.
Step 4: print the result.
PROGRAM
import pandas as pad
data_1 = {"Countries": ["Bhutan", "Cape Verde", "Chad", "Estonia", "Guinea", "Kenya", "Libya", "
Mexico"],
"capital": ["Thimphu", "Praia", "N'Djamena", "Tallinn", "Conakry", "Nairobi", "Tripoli", "Mexi
co City"],
"Currency": ["Ngultrum", "Cape Verdean escudo", "CFA Franc", "Estonia Kroon; Euro", "Guine
an franc", "Kenya shilling", "Libyan dinar", "Mexican peso"],
"population": [20.4, 143.5, 12.52, 135.7, 52.98, 76.21, 34.28, 54.32] }
data_1_table = pad.DataFrame(data_1)
print(data_1_table)
OUTPUT
Countries capital Currency population
0 Bhutan Thimphu Ngultrum 20.40
1 Cape Verde Praia Cape Verdean escudo 143.50
2 Chad N'Djamena CFA Franc 12.52
3 Estonia Tallinn Estonia Kroon; Euro 135.70
4 Guinea Conakry Guinean franc 52.98
5 Kenya Nairobi Kenya shilling 76.21
6 Libya Tripoli Libyan dinar 34.28
7 Mexico Mexico City Mexican peso 54.32
RESULT
Thus the program for analyzing data using pandas library is executed and output is verified.
40
EX. No.:8b Numpy - Find matrix product
AIM
To implement the program for calculate matrix product using numpy standard libraries.
ALGORITHM
Step 1: create two array of rank 2
Step 2: create two array of rank 1
Step 3: calculate inner product of vectors, matrix and vector product and matrix product.
Step 4: print the result.
PROGRAM
import numpy as nup
K = nup.array([[2, 4], [6, 8]]) # Then, create two arrays of rank 2
R = nup.array([[1, 3], [5, 7]]) # Then, create two arrays of rank 1
P = nup.array([10, 12])
S = nup.array([9, 11])
print ("Inner product of vectors: ", nup.dot(P, S), "\n") # Then, we will print the Inner product of vectors
# Then, we will print the Matrix and Vector product
print ("Matrix and Vector product: ", nup.dot(K, P), "\n")
# Now, we will print the Matrix and matrix product
print ("Matrix and matrix product: ", nup.dot(K, R))
OUTPUT
Inner product of vectors: 222
Matrix and Vector product: [ 68 156]
Matrix and matrix product: [[22 34]
[46 74]]
RESULT
Thus the program for calculate matrix product using numpy standard libraries is executed and output is
verified.
41
EX. No.:8 c Display scattering plot using matplotlib.
AIM
To implement the program for display the scattering plot using matplotlib library.
ALGORITHM
Step 1: Import matplotlib library.
Step 2: creating two data set for two different plots using array.
Step 3:scatter() function is used to plot the graph. Width ,color and size of plot is also specified within the
function.
Step 4: label() function is used to give name for x and y axis.
Step 5: display the plot using plt.show() function.
PROGRAM
import matplotlib.pyplot as plot
# Creating dataset-1
K_1 = [8, 4, 6, 3, 5, 10,
13, 16, 12, 21]
R_1 = [11, 6, 13, 15, 17, 5,
3, 2, 8, 19]
# Creating dataset2
K_2 = [6, 9, 18, 14, 16, 15,
11, 16, 12, 20]
R_2 = [16, 4, 10, 13, 18,
20, 6, 2, 17, 15]
plot.scatter(K_1, R_1, c = "Black",
linewidths = 2,
marker = "s",
edgecolor = "Brown",
s = 50)
plot.scatter(K_2, R_2, c = "Purple",
linewidths = 2,
marker = "^",
edgecolor = "Grey",
s = 200)
42
plt.xlabel ("X-axis")
plt.ylabel ("Y-axis")
print ("Scatter Plot")
plt.show()
OUTPUT
RESULT
Thus the program for display the scattering plot is executed and output is verified.
43
EX. No.:8 d Scipy - Perform an order filter on an array.
AIM
To implement the program for perform an order filter on an array using scipy library.
ALGORITHM
Step 1: Import scipy library.
Step 2: create array using arrange() function.
Step 3: reshape the array using reshape() function.
Step 4: create identity array which is having diagonal element as one.
Step 5: Perform an order filter on an N-D array.
Step 6: print the result.
PROGRAM
from scipy import signal as sg
import numpy as nup
K = nup.arange(45).reshape(9, 5)
domain_1 = nup.identity(3)
print (K, end = 'KK')
print (sg.order_filter (K, domain_1, 1))
44
OUTPUT
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]
[35 36 37 38 39]
[40 41 42 43 44]] KK [[ 0. 1. 2. 3. 0.]
[ 5. 6. 7. 8. 3.]
[10. 11. 12. 13. 8.]
[15. 16. 17. 18. 13.]
[20. 21. 22. 23. 18.]
[25. 26. 27. 28. 23.]
[30. 31. 32. 33. 28.]
[35. 36. 37. 38. 33.]
[ 0. 35. 36. 37. 38.]]
RESULT
Thus the program for perform an order filter on an array using scipy library is executed and output is
verified.
45
EX. No.:9 a) Copy file
Aim: To write a python program to copy the content from one file to another file.
Algorithm:
Step 1: Start the program
Step 2: Open one file called test. txt in read mode.
Step 2: Open another file out. txt in write mode.
Step 3: Read each line from the input file and write it into the output file.
Step 4: Stop the program.
Program:
with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
# read content from first file
for line in firstfile:
# append content to second file
secondfile.write(line)
Output:
Result:
Thus the python program to copy the content from one file to another file is executed
and verified.
46
EX. No.:9b Count no of words
Aim: To write a python program to count number of words in a text file using command linearguments.
Algorithm:
Step 1: Start the program.
Step 2: import sys package.
Step 3: Assign num_words=0.
Step 4: Open text file in reading mode from command line argument sys.argv[1] as f.
Step 5: Split each line from the text and count number of words and store it in num_words.
Step 6: Print the total number of words from num_words.
Step 7: Stop the program.
Program:
import sys
num_words=0
with open(sys.argv[1],"r")as f:
for line in f:
words=line.split()
num_words+=len(words)
print("Number of words")
print(num_words)
1. Type and Save Count program as count.py.
2. Create a text file and type it as “hai how are you” and save it as sample.txt.
3. Copy it in C:\Python34
4. Go to run, type cmd, window will open..
O/P:
Result:
Thus the python program to count number of words in a text file using command line
arguments is executed and verified.
47
EX. No.:9c Longest word
Algorithm:
Step 1: Start the program.
Step 2: By invoking call function, open text file in reading mode as infile.
Step 3: Split the word which was read by using infile.read().split() function and store it in
variable named as words.
Step 4: Calculate the length of each words and store the maximum words in max_len.
Step 5: Using for loop return the maximum word if len(word)==max_len is true.
Program:
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('longest.txt'))
Output:
Result: To write a python program to find the longest word in a text is executed and verified.
48
EX. No.:10a Divide by zero error
Algorithm:
Step 1: Start the program
Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step 6: Stop the program.
Program:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
O/P:
Enter First Number: 432.12
Invalid Input Please Input Integer...
Enter First Number: 43
Enter Second Number: 0
division by zero
Enter First Number: 331 2
Enter Second Number: 4
83.0
Result: Thus the python program for divide by zero error exception is executed and verified.
49
EX. No.:10 b Voter’s age eligibility
Aim: To write a python program to check whether the person is eligible to vote or not
Algorithm:
Step 1: Start the program.
Step 2: Get the input from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the entered data is below zero, print it is “negative number”, else break.
Step 5: If no exception is there, print the result.
Step 6: Stop the program.
Program:
while True:
try:
age=int(input(" Please enter your age: "))
except ValueError:
print(" Sorry,this is not a number")
continue
if(age<0):
print(" Sorry, this is a negative number ")
continue
else:
break
if(age>=18):
print(" you are able to vote ")
else:
print(" you are not able to vote ")
Output:
Please enter yout age: 18
you are able to vote Please
enter yout age: -1
Sorry, this is a negative number
Please enter yout age: abcc Sorry,
this is not a number
Result: Thus the python program to check whether the person is eligible to vote or not is
executed and verified
50
EX. No.:10c Student mark range validation
Algorithm:
Step 1: Start the program
Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program.
Program:
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")
main()
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed
Result: Thus the python program for student mark range validation is executed and verified
51
EX. No.:11 Simulate elliptical using pygame tool
AIM
To write a program to simutale elliptical usingpygame tool.
ALGORITHM
Step 1: Import the necessary header files for the implementation of this pygame.
Step 2: Set the display mode for the screen using screen=pygame.display.set_mode((700,700))
Step 3: Develop the balls with necessary colors. white=(255,255,255) blue=(0,0,255) yellow=(255,255,0)
gray=(200,200,200) black=(0,0,0)
Step 4: Set the radius for sun, moon and their orbit.
Step 5: Set the time for the pygame orbit clock=pygame.time.Clock()
Step 6: Update the earth position.
Step 7:Again update moon position based on earth position.
Step 8: Update the moon and earth angles.
Step 9: Reset the screen and draw the stars, sun, moon and the earth.
Step 10: Set the clock tick as (60) and exit.
PROGRAM
import pygame,sys,time
from pygame.locals import *
from time import *
import math
pygame.init()
screen=pygame.display.set_mode((500,300))
pygame.display.set_caption("Elliptical Orbits")
white=(255,255,255)
blue=(0,0,255)
green=(0,255,0)
black=(0,0,0)
red=(255,0,0)
ellipse_width=200
ellipse_hight=40
ellipse_rect_x=100
ellipse_rect_y=100
ellipse_width_2=400
ellipse_hight_2=80
52
ellipse_rect_x_2=75
ellipse_rect_y_2=85
while True:
for degree in range(360):
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
screen.fill(white)
x = math.cos(degree * 2 * math.pi / 360) * ellipse_width/2
y = math.sin(degree * 2 * math.pi / 360) * ellipse_hight/2
pygame.draw.ellipse(screen, blue, (ellipse_rect_x, ellipse_rect_y,ellipse_width,ellipse_hight), 2)
pygame.draw.circle(screen,green,(int(x)+ellipse_rect_x+ellipse_width/2,int(y)+ellipse_rect_y+ellipse_hight/
2),8,0)
x = math.cos(degree * 2 * math.pi / 360) * ellipse_width_2/2
y = math.sin(degree * 2 * math.pi / 360) * ellipse_hight_2/2
pygame.draw.ellipse(screen, black, (ellipse_rect_x_2, ellipse_rect_y_2,ellipse_width_2, ellipse_hight_2), 2)
pygame.draw.circle(screen,red,(int(x)+ellipse_rect_x_2+ellipse_width_2/2,int(y)+ellipse_rect_y_2+ellipse_
hight_2/2),8,0)
pygame.display.update()
sleep(.06)
OUTPUT
RESULT
Thus the simulation of elliptical curve orbit using pygame is executed and the output is obtained.
53
Ex. No: 12a Bouncing ball game using pygame tool
AIM
To write a program for developing a bouncing ball game using pygame tool.
ALGORITHM
Step 1: Import the necessary files for the implementation of this Pygame.
Step 2: Set the display mode for the screen using
windowSurface=pygame.display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bounce pygame.display.set_caption(“Bounce”)
Step 4: Develop the balls with necessary colors. BLACK=(0,0,0) WHITE=(255,255,255) RED=(255,0,0)
GREEN=(0,255,0) BLUE=(0,0,255)
Step 5: Set the display information info=pygame.display.Info()
Step 6: Set the initial direction as down.
Step 7: Change the direction from down to up.
Step 8: Then again change the direction from up to down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.
PROGRAM
import pygame
import sys
import time
import random
from pygame.locals import *
from time import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y=0
54
# Initial direction is down
direction = 1
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
#print "Drawing at 250,", y
sleep(.006)
y += direction
if y >= sh:
# Changes the direction from down to up
direction = -1
elif y <= 0:
# Changes the direction from up to down
direction = 1
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
OUTPUT
RESULT
Thus the program to implement bouncing ball using pygame tool is executed and verified successfully.
55
Ex. No: 12 b Car race game using pygame tool
AIM
To write a program for developing a car race game using pygame tool.
ALGORITHM
Step1 : create the game window.
Step 2: give title as car race game and change background color.
Step3 : create start and stop button for operating cars.
Step4: include player and enemy image using ‘blit’ function.
Step 5: player and enemy car image can be loaded by using Ingameloop() function.
Step 6: set x and y coordinate value of player image using display.set_mode().
• If changes in x coordinate that represents left to right move
• If changes in y coordinate that representstop to bottom move
Step 7: if button =start then goto step 8
Step 8: keyboard arrow keys represent moving of car direction using pygame.keydown()
• Left arrow indicate left move of the car
• right arrow indicateright move of the car
• up arrow indicateup move of the car
• down arrow indicate down move of the car
56
PROGRAM
import pygame
import time
import random
import os
pygame.init()
screen_width = 400
screen_height = 600
btn_starting_x = 75
nw_gm_y = 400
exit_y = 460
btn_width = 242
btn_height = 50
black_color = (0, 0, 0)
white_color = (255, 255, 255)
red_color = (255, 0, 0)
redLight_color = (255, 21, 21)
gray_color = (112, 128, 144)
green_color = (0, 255, 0)
greenLight_color = (51, 255, 51)
blue_color = (0, 0, 255)
game_layout_display= pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('F1 Race Road Game')
time_clock=pygame.time.Clock()
car_photo = pygame.image.load(os.getcwd() + '\\images/car.png')
left_c = pygame.image.load(os.getcwd() + '\\images/car_left.png')
right_c = pygame.image.load(os.getcwd() + '\\images/car_right.png')
photo_obstacle = pygame.image.load(os.getcwd() + '\\images/obstacle.png')
texture_photo = pygame.image.load(os.getcwd() + '\\images/texture.png')
(c_width, c_height) = car_photo.get_rect().size
(c_left_width, c_left_height) = left_c.get_rect().size
(c_right_width, c_right_height) = right_c.get_rect().size
(t_width, t_height) = photo_obstacle.get_rect().size
(txtwidth, txtheight) = texture_photo.get_rect().size
def high_score_update(dodged):
high_scores = open(os.getcwd()+'\\textfile/high_score.txt', 'w')
temperd = str(dodged)
high_scores.write(temperd)
58
pygame.display.update()
time.sleep(time_sleeping)
def title_msg():
animation_height=screen_height
pygame.mixer.Sound.play(welcome_1)
while animation_height> -600:
game_layout_display.fill(white_color)
things(screen_width / 2 - t_width / 2, animation_height)
animation_height-=1.5
pygame.display.update()
title_message_display(0, 0, black_color)
time.sleep(0.1)
pygame.mixer.Sound.play(welcome_2)
def motion_texture(th_starting):
game_layout_display.blit(texture_photo, (0, th_starting - 400))
game_layout_display.blit(texture_photo, (0, th_starting))
game_layout_display.blit(texture_photo, (0, th_starting + 400))
def crash_function():
pygame.mixer.music.stop()
pygame.mixer.Sound.play(audio_crash)
message_display_screen("YOU CRASHED", 0, 0, red_color, 0)
while True:
playAgain = button("Play Again", btn_starting_x, nw_gm_y, btn_width, btn_height, greenLight_color,
green_color)
exit_game = button("Quit", btn_starting_x, exit_y, btn_width, btn_height, redLight_color, red_color)
for event in pygame.event.get():
if event.type == pygame.QUIT or exit_game == 1 or (event.type == pygame.KEYDOWN and event.key ==
pygame.K_ESCAPE):
pygame.quit()
quit()
59
if playAgain== 1 or (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE):
looping_gameplay()
pygame.display.update()
time_clock.tick(15)
small_txt = pygame.font.Font('freesansbold.ttf',20)
TxtSurf, TxtRect = text_objects(messages, small_txt, white_color)
TxtRect.center = ((x + wid / 2), (y + hei / 2))
game_layout_display.blit(TxtSurf, TxtRect)
def welcome_gameplay():
welcome = True
game_layout_display.fill(white_color)
title_msg()
exit_game=0
while welcome:
for event in pygame.event.get():
if event.type == pygame.QUIT or exit_game == 1 or (event.type == pygame.KEYDOWN and event.key ==
pygame.K_ESCAPE):
pygame.quit()
quit()
playGame = button("New game", btn_starting_x, nw_gm_y, btn_width, btn_height, greenLight_color,
green_color)
exit_game = button("Quit", btn_starting_x, exit_y, btn_width, btn_height, redLight_color, red_color)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit_game = 1
if playGame or (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE):
welcome = False
60
pygame.display.update()
time_clock.tick(15)
def counting_three_two_one():
counting = 3
pygame.mixer.music.pause()
pygame.mixer.Sound.play(audio_ignition)
while counting >= 0:
game_layout_display.blit(image_background, bckgrndRect)
car(screen_width * 0.40, screen_height * 0.6, 0)
if counting == 0:
message_display_screen ("GO!", 0, 0, green_color, 0.75)
pygame.mixer.music.play(-1)
else:
message_display_screen (str(counting), 0, 0, red_color, 0.75)
counting -= 1
time_clock.tick(15)
def gameplay_paused():
pygame.mixer.music.pause()
pause = True
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key ==
pygame.K_ESCAPE): ###############or quit_game == 1
pygame.quit()
quit()
message_display_screen("pause", 0, 0, blue_color, 1.5)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
pygame.mixer.music.unpause()
return
pygame.display.update()
time_clock.tick(15)
def looping_gameplay():
pygame.mixer.music.play(-1)
display = 0
width_x=(screen_width * 0.4)
height_y=(screen_height * 0.6)
ch_x=0
61
th_st_x = random.randrange(8, screen_width - t_width - 8)
th_st_y = -600
th_speed = 5
tracking_y = 0
tracking_speed = 25
dodg=0
direction = 0
highest_score_txtfile = open(os.getcwd()+'/textfile/high_score.txt','r')
high_score = highest_score_txtfile.read()
gameExit = False
counting_three_two_one()
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key ==
pygame.K_ESCAPE):
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
ch_x = -10
direction = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
ch_x = 10
direction = 1
if event.key == pygame.K_SPACE:
gameplay_paused()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_a or
event.key == pygame.K_d:
ch_x = 0
direction = 0
width_x+=ch_x
game_layout_display.blit(image_background, bckgrndRect)
motion_texture(th_st_y)
things(th_st_x, th_st_y)
th_st_y += th_speed
car(width_x,height_y,direction)
things_dodged(dodg, high_score, th_speed)
if width_x> screen_width - c_width or width_x< 0:
crash_function()
if th_st_y> screen_height:
62
th_st_y = 0 - t_height
th_st_x = random.randrange(0, screen_width)
dodg += 1
th_speed += 1
if dodg> int(high_score):
high_score_update(dodg)
if height_y< th_st_y+t_height-15 and width_x> th_st_x-c_width-5 and width_x< th_st_x+t_width-
5:
crash_function()
pygame.display.update()
time_clock.tick(60)
welcome_gameplay()
looping_gameplay()
pygame.quit()
quit()
OUTPUT
RESULT
Thus the program to implement car racing using pygame tool is executed and verified successfully.
63