0% found this document useful (0 votes)
106 views60 pages

Ge3171 PSPP Record

Python programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views60 pages

Ge3171 PSPP Record

Python programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

T.J.

S ENGINEERING
COLLEGE
(Approved by AICTE & Affiliated to Anna University, Chennai)
Peruvoyal, (Near Kavaraipettai), Gummidipoondi Taluk,
Thiruvallur District-601206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

NAME :

REGISTER NO. :

SEMESTER :
T.J.S ENGINEERING
COLLEGE
(
Approved by AICTE & Affiliated to Anna University, Chennai)
Peruvoyal, (Near Kavaraipettai), Gummidipoondi Taluk,
Thiruvallur District-601206

NAME : ……………………………………………

DEPARTMENT : ……………………………………………

SUBJECT CODE /TITLE : ………………..………..…………………

YEAR/SEM : ……………………………………………

DATE OF EXAMINATION : …………………………………..……….

REGISTER NUMBER : ………………………………………..….

Certified that this is the bonafide record of practical work done by the aforesaid student in the
during the year

Laboratory in charge Head of the Department

Internal Examiner External Examiner


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION:

To create knowledge pool in the field of computer science and engineering to empower the students to meet
the challenges of the society

MISSION:

Prepare the students with strong fundamental concepts, analytical capabilities, programming and problem
solving skills.

Bringing an Eco-System to provide new cutting edge technologies required to meet the challenges.

Imparting necessary skills to become continuous learners in the field of Computer Science and Engineering
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

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:
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, replacingcharacters)
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.

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.

CO’s-PO’s & PSO’s MAPPING

CO PO PO PO PO PO PO PO PO PO PO10 PO PO PSO1 PSO2 PSO3


1 2 3 4 5 6 7 8 9 11 12
1 3 3 3 3 2 - - - - - 2 2 3 3 -
2 3 3 3 3 2 - - - - - 2 2 3 - -
3 3 3 3 3 2 - - - - - 2 - 3 - -
4 2 2 - 2 2 - - - - - 1 - 3 - -
5 1 2 - - 1 - - - - - 1 - 2 - -
6 2 2 - - 2 - - - - - 1 - 2 -
AVg. 2 3 3 3 2 - - - - - 2 2 3 3 -
1 - low, 2 - medium, 3 - high, ‘-' - no correlation
INDEX
Date of Page Date of Sign of faculty
Ex No Title
Experiment No Submission
1. Identification and solving of simple real life or scientific or technical problems, and developing flow
charts for the same
1 (a) Electricity Billing
1 (b) Retail shop billing
1 (c) Sin series
1 (d) Weight of a motorbike

1 (e) Weight of a steel bar


Compute Electrical Current in Three
1 (f)
Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions

2 (a) Exchange the values of two variables

2 (b) Circulate the values of n variables

2 (c) Distance between two points

3. Scientific problems using Conditionals and Iterative loops.


3 (a) Number series,

3 (b) Number Patterns

3 (c) Pyramid pattern

4. Implementing real-time/technical applications using Lists, Tuples.


4 (a) Items present in a library

4 (b) Components of a car

Materials required for construction of a


4 (c)
building operations of list & tuples
5. Implementing real-time/technical applications using Sets, Dictionaries
5 (a) Language

5 (b) components of an automobile

5 (c) Elements of a civil structure

6. Implementing programs using Functions.


6 (a) Factorial

6 (b) largest number in a list

6 (c) Area of shape


INDEX

Date of Page Date of Sign of faculty


Ex No Title
Experiment No Submission
7. Implementing programs using Strings.
7 (a) Reverse
7 (b) Palindrome
7 (c) Character count
7 (d) Replacing characters

8. Implementing programs using written modules and Python Standard Libraries

8 (a) Pandas

8 (b) Numpy

8 (c) Matplotlib

8 (d) Scipy

9. Implementing real-time/technical applications using File handling.


9 (a) Copy from one file to another

9 (b) Word count

9 (c) Longest word

10. Implementing real-time/technical applications using Exception handling.


10 (a) Divide by zero error

10 (b) Voter’s age validity

10 (c) Student mark range validation


11. Exploring Pygame tool.
11 Exploring Pygame tool

12. Developing a game activity using Pygame.


12 (a) Bouncing ball

12 (b) Car race


EX NO:1(a) IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE PROBLEMS
ELECTRICITY BILLING
DATE:
ecord Notes

AIM
To draw a flowchart to solve compute Electricity billing.
Ac circuit.

FLOWCHART

RESULT

Thus, a flowchart for electricity billing has been produced successfully.

1
EX NO:1(b)

RETAIL SHOP BILLING


DATE:

AIM

To write an algorithm and flowchart to solve retail shop billing.

ALGORITHM

Step1: Start
Step2: Update the list of items purchased on database
Step3.If shopping complete means calculate total
Step4: If shopping not completed purchase remaining items
Step4: Cash payment is done after calculating the total amount
Step5: Stop
FLOWCHART
Start

Purchase Items

No

Yes
After yes
Shoppin
g

Calculate total

Cash payment

Stop

RESULT

Thus, an algorithm and flowchart for retail shop billing has been produced successfully.

2
EX NO:1(c)

SINE SERIES
DATE:

AIM

To write an algorithm and flowchart to solve Sin series.

ALGORITHM

Step 1:Start
Step 2: Read x,n
Step 3:Calculatex=x*3.14159/180
Step 4: t=x
Step 5 : Sum=x
Step 6: Check condition using While i<=n
Step 7: t=t*(-1)*x*x)/(2*i*2i+1))
Step 8 : sum=sum+t
Step 9 :i=i+1
Step 7: Print y,sum
Step 3: Stop

3
FLOWCHART

RESULT

Thus an algorithm and flowchart for sinseries has been produced successfully.

4
EX NO:1(d)

WEIGHT OF MOTOR BIKE


DATE:

AIM

To write an algorithm and flowchart to solve Weight of a motor bike.

ALGORITHM

Step 1:Start
Step 2:Heigt=Input "Height in Feet"
Step 3:Weight=Input "weight in Kilogram"
Step 4:x=(Weight/Height*Height)
Step 5:Print "Motor bike weight"-->x
Step 6:Stop
FLOWCHART

Start

Input Height, Weight

yes

x=(Weight/Height*Height)

Print Motor bike

Stop

RESULT

Thus, an algorithm and flowchart for weight of motor bike has been produced successfully.

5
EX NO:1E

WEIGHT OF STEEL BAR


DATE:

AIM

To write an algorithm and flowchart to solve weight of a Steel Bars.

ALGORITHM

Step1:start
Step2:Read the variables Diameter and length need to calculate the weight.
Sep3:computethe weight using formula W=D^2*L/162
Step4: Print the weight of steelbar
Step5:stop

FLOWCHART

Start

Read the variables D,L

W=D^2*L/162

PRINT WEIGHT

STOP

RESULT

Thus, an algorithm and flowchart for above program has been produced successfully.

6
EX NO:1F

ELECTRIC CURRENT THREE PHASE AC CIRCUIT


DATE:

AIM

To write an algorithm and flowchart to solve simple real life problems for electric current three phase
Ac circuit.

ALGORITHM

Step1: Start
Step2: Read the variables P,V and PF values
Step3: Assign the values to variables
Step4: Compute the electric current for three phase AC circuit using
Formula : I = P/(V * PF * 1.73)
Step5: print the electric current I Value
Step 6: Stop

FLOWCHART
start

Read the variables P,V and

I= P/(V * PF * 1.73)

Print I

stop

RESULT

Thus, an algorithm and flowchart for above program has been produced successfully.

7
EX NO:2(a)
EXCHANGE OF TWO VALUES

DATE:

AIM

To write a program for exchange values of two values.

ALGORITHM

Step1: Start
Step2: Read the variables x,y
Step3: Assign the values to variables
Step4: Perform swapping operations
Step5: print the value of after swapping
Step 6: Stop

PROGRAM

x=5
y=10
temp=x
x=y
y=temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)

OUTPUT

The value of x after swapping:10


The value of y after swapping:5

RESULT

Thus, the exchange of two values has been executed and verified successfully.

8
EX NO:2(b)
CIRCULATE THE VALUE OF N VARIABLES
DATE:

AIM

To write a program for circulate the value of n variables

ALGORITHM

Step1: Start
Step2: Read the variables x,y
Step3: Assign the values to variables
Step4: Perform swapping operations
Step5: print the value of after swapping
Step 6: Stop

PROGRAM
no_of_terms = int(input("Enter number of values : "))

list1 = []

forv al in range(0,no_of_terms,1):

ele = int(input("Enter integer : "))

list1.append(ele)

print("Circulating the elements of list ", list1)

for val in range(0,no_of_terms,1):


ele = list1.pop(0)

list1.append(ele)

print(list1)

9
OUTPUT

Enter number of values : 3

Enter integer : 6

Enter integer : 7

Enter integer : 8

Circulating the elements of list [6, 7, 8]

[7, 8, 6]

[8, 6, 7]

[6, 7, 8]

RESULT

Thus, the program for circulate the value of n variables has been executed and verified successfully.

10
EX NO:2(c)
DISTANCE BETWEEN TWO POINTS
DATE:

AIM

To write an algorithm and program for Distance between two points.

ALGORITHM

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


Step2:Use a for loop where the value of i ranges between the values of 1 and n.
Step3: Print the value of i and ‘+’ operator while appending the value of i to a list.
Step 4: Then find the sum of elements in the list.
Step 5: Print ‘=’ followed by the total sum.
Step 6: Exit.

PROGRAM

x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

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 for distance between two points has been verified successfully.

11
EX NO:3(a)
NUMBER SERIES

DATE:

AIM

To write an algorithm and program for number series.

ALGORITHM

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


2. Use a for loop where the value of i ranges between the values of 1 and n.
3. Print the value of i and ‘+’ operator while appending the value of i to a list.
4. Then find the sum of elements in the list.
5. Print ‘=’ followed by the total sum.
6. Exit.

PROGRAM

n=int(input("Enter a number: "))


a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()

OUTPUT

Enter a number: 6
1 + 2 + 3 + 4 + 5 + 6 = 21

RESULT

Thus, the program for number series has been verified successfully

12
EX NO:3(b)
NUMBER PATTERN

DATE:

AIM

To write a python program for number pattern.

ALGORITHM

Step1: Start

Step2: Print the number pattern using for loop.

Step3:Inner for loop is used to print the pattern upto n values.

Step4: Print j+1 values till the end value.

Step5:Stop.

PROGRAM

for i in range(5):
for j in range(5):
print(j+1, end=' ')
print()

OUTPUT
12345
12345
12345
12345
12345

RESULT

Thus, the program for number pattern has been verified successfully.

13
EX NO:3C
PYRAMID PATTERN

DATE:

AIM

To write an algorithm and program for pyramid pattern.

ALGORITHM

Step1: Start
Step2: Using two for loops print the number pattern in pyramid structure.
Step3: For loop is used to print numbers upto 2*i+1 values.
Step4: Print the numbers upto k+1 till end
Step5:Stop.

PROGRAM

for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for k in range(2 * i + 1):
print(k + 1, end='')
print()

OUTPUT

1
123
12345
1234567
123456789

RESULT

Thus, the program for pyramid pattern has been verified successfully

14
EX NO:4(a)
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS
ITEMS PRESENT IN ALIBRARY
DATE:

AIM
To write a python program items present in library using list .

PROGRAM

list=["phy","che","mat","eng","tam"]
for i in range(0,4,1):
print(list[i])
list.insert(3,"computer")
print(list)
print("computer" not in list)
list.remove("eng")
print(list)
print(list.index("mat"))
print(list.count("eng"))
print("tam" in list)

OUTPUT

phy
che
mat
eng
['phy', 'che', 'mat', 'computer', 'eng', 'tam']
False
['phy', 'che', 'mat', 'computer', 'tam']
2
0
True

RESULT

Thus, the program for List items presents in the library has been verified successfully.

15
EX NO:4(b)
COMPONENTS OF A CAR
DATE:

AIM
To write a python program Components of a car using List .

PROGRAM

car_components=["Engine","battery","light","frontaxle","brakes"]
print(car_components)
car_components.insert(4,"radiator")
car_components.insert(3,"alternator")
print(car_components)
car_components.append("trunk")
car_components.append("air filter")
print(car_components)
car_components.pop(1)
print(car_components)
print(car_components[:-4])
car_components.extend("seat","windowframe","mirror")
print(car_components)

OUTPUT

['Engine', 'battery', 'light', 'front axle', 'brakes']


['Engine', 'battery', 'light', 'alternator', 'front axle', 'radiator', 'brakes']
['Engine', 'battery', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter']
['Engine', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter']
['Engine', 'light', 'alternator', 'front axle']
['Engine', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter', 'seat', 'window
frame', 'mirror']

RESULT:
Thus, the Components of a car has been executed and verified successfully

16
EX NO:4(c)
CONSTRUCTION FOR BUILDING
DATE:

AIM
To write a python program items present in library using list .

Construction for building

materials=("Cement bags","sand","aggregates","bricks")
material2=("steel bars","paint")
print(materials)
mat3 = (materials+material2)
print(mat3)
print(materials[:3])
print(material2[1])
print(len(materials))
print(len(material2))
print(max(materials))
print(min(materials))
print(cmp(materials,material2))

Output

('Cement bags', 'sand', 'aggregates', 'bricks')


('Cement bags', 'sand', 'aggregates', 'bricks', 'steel bars', 'paint')
('Cement bags', 'sand', 'aggregates')
paint
4
2
sand
Cement bags
-1

RESULT:
Thus, the Construction of a building has been executed and verified successfully

17
EX NO:5(a)
LANGUAGES
DATE:

AIM
To write a python program Languages using dictionary.

PROGRAM

language1={"tamil","english","telgu"}
language2={"hindi","urudu","malayalam","telgu"}
print(language1)
print(language2)
language1.add("spanish")
print(language1)
language2.add("kanada")
print(language2)
print(language1&language2)
print(language1|language2)
lang3=language1.difference(language2)
print(lang3)

OUTPUT

set(['tamil', 'telgu', 'english'])


set(['malayalam', 'hindi', 'urudu', 'telgu'])
set(['spanish', 'tamil', 'telgu', 'english'])
set(['malayalam', 'kanada', 'hindi', 'urudu', 'telgu'])
set(['telgu'])
set(['urudu', 'telgu', 'kanada', 'spanish', 'hindi', 'english', 'malayalam', 'tamil'])
set(['english', 'tamil', 'spanish'])

RESULT:

Thus, the Languages has been executed and verified successfully

18
EX NO:5(b)
COMPONENTS OF AUTOMOBILE
DATE:

AIM
To write a python program item present in library using list

PROGARAM

com1={"steering wheel","gear","tyre","radiator"}
com2={"sensor","wheel","brake"}
print(com1)
print(com2)
print(com1|com2)
com3=com1.difference(com2)
com2.add("light")
print(com2)

OUTPUT

set(['steering wheel', 'radiator', 'gear', 'tyre'])


set(['wheel', 'brake', 'sensor'])
set(['wheel', 'steering wheel', 'brake', 'gear', 'radiator', 'sensor', 'tyre'])
set(['wheel', 'brake', 'sensor', 'light'])

RESULT:

Thus, the Components of Automobile has been executed and verified successfully

19
EX NO:5(c)
ELEMENTS OF A CIVIL STRUCTURE
DATE:

AIM

To write a python program Elements of a Civil structure using Dictionary.

PROGRAM

ele1={1:"foundation",2:"floor"}
ele2={1:"walls",2:"beams",3:"roof",4:"stair"}
print(ele1)
print(ele2)
print(ele1[1])
print(ele2[3])
print(ele1.get(2))
ele1[2]="cement"
print(ele1)
print(ele2.pop(2))

OUTPUT

{1: 'foundation', 2: 'floor'}


{1: 'walls', 2: 'beams', 3: 'roof', 4: 'stair'}
foundation
roof
floor
{1: 'foundation', 2: 'cement'}
beams

RESULT:

Thus, the Elements of a Civil structure has been executed and verified successfully

20
EX NO:6(a)
FACTORIAL
DATE:

AIM

To write a program for factorial of 'n' numbers.

ALGORITHM

Step1: Start
Step2: Use factorial function to calculate the value.
Step3:If n==1 and n==0 return 1.
Step4:Get the value of num to print the values of factorial.
Step4:Call the factorial function.
Step5:Stop

PROGRAM

def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1);
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))

OUTPUT

Factorial of 5 is 120

RESULT

Thus, the Factorial program has been executed and verified successfully

21
EX NO:6(b)

LARGEST NUMBER IN LIST


DATE:

AIM

To write a program for largest number in list.

PROGRAM

# printing the last element


def largest(list):
large= list[0]
for i in list:
if i>large:
large=i
return large
#list
list=[3, 9, 7, 3, 6, 5, 7, 24, 6]
print("largest in ",list,"is")
print(largest(list))

OUTPUT

largest in [3, 9, 7, 3, 6, 5, 7, 24, 6] is 24

RESULT

Thus, the program for largest number in list has been verified successfully.

22
EX NO:6(c)
AREA OF SHAPE
DATE

AIM

To write a program for area of shape.

PROGRAM

# Python program to find Area of a circle

deffindArea(r):
PI = 3.142
return PI * (r*r);

# Driver method
num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num));

OUTPUT

Enter r value:5
Area is 78.550000

RESULT

Thus, the program for area of shape has been verified successfully.

23
EX NO:7(a)
STRING REVERSE
DATE:

AIM

To write a program for string reverse operation.

PROGRAM

defreverse(s):
str=""
for i ins:
str=i +str
return str
s ="Pavithra"
print("The original string is : ",end="")
print(s)
print("The reversed string(using loops) is : ",end="")
print(reverse(s))

OUTPUT

The original string is : Pavithra


The reversed string(using loops) is : arhtivaP

RESULT

Thus, the program for string reverse has been verified successfully.

24
EX NO:7(b)

STRING PALINDROME
DATE:

AIM

To write a program for string palindrome operation.

PROGRAM

string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")

OUTPUT

Enter a letter:COMPUTER
The letter is not a palindrome
Enter a letter:MALAYALAM
The letter is a palindrome

RESULT

Thus, the program for string palindrome has been verified successfully.

25
EX NO:7 (c)

COUNT THE CHARACTERS IN STRING


DATE:

AIM

To write a program for count the characters in string operation.

PROGRAM

test_string ="Geeksforgeeks is best Computer Science Portal"

# printing original string


print("The original string is : "+test_string)

# using split()
# to count words in string
res =len(test_string.split())

# printing result
print("The number of words in string are : "+str(res))
print("The number of words in string are : ", len(test_string))

OUTPUT

The original string is :Geeksforgeeks is best Computer Science Portal


The number of words in string are : 6
The number of words in string are : 45

RESULT

Thus, the program for count the characters in string has been verified successfully.

26
EX NO:7 (d)
REPLACE CHARACTERS

DATE:

AIM

To write a program for replace characters in string operation.

PROGRAM

input_string = "This is PythonForBeginners.com. Here, you can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

OUTPUT

The original string is:


This is PythonForBeginners.com. Here, you can read python tutorials for free.
Output String is:
ThIs Is PythonForBegInners.com. Here, you can read python tutorIals for free.

RESULT

Thus, the program for replace characters in string has been verified successfully.

27
EX NO:8(a)
PANDAS

DATE:

AIM

To write a program for replace characters in string operation.

PROGRAM

import pandas as pd
df = pd.DataFrame({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)

OUTPUT

X Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83

RESULT

Thus, the program for pandas has been verified successfully.

28
EX NO:8(b)
NUMPY

DATE:

AIM

To write a program for replace characters in string operation.

PROGRAM

importnumpy as np

# Create the following rank 2 array with shape (3, 4)

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

print(a)

#Slicing in array

print(a.shape)

b = a[1:, 2:]
print(b)

OUTPUT

[[ 1 2 3 4]

[ 5 6 7 8]

[ 9 10 11 12]]

(3, 4)

[[ 7 8]
[11 12]]

RESULT

Thus, the program for numpy has been verified successfully.

29
EX NO:8(c)
MATPLOT

DATE:

AIM

To write a program for Matplot.

PROGRAM

importmatplotlib.pyplot as plt

# Data labels, sizes, and colors are defined:

labels = 'Broccoli', 'Chocolate Cake', 'Blueberries', 'Raspberries'

sizes = [30, 330, 245, 210]

colors = ['green', 'brown', 'blue', 'red']

# Data is plotted:

plt.pie(sizes, labels=labels, colors=colors)

plt.axis('equal')

plt.title('Pie Plot')
plt.show()

OUTPUT

RESULT

Thus, the program for Matplot has been verified successfully.

30
EX NO:8(d)
SCIPY

DATE:

AIM

To write a program for Scipy.

PROGRAM

From scipy.optimize import root


from math import cos

defeqn(x):
return x + cos(x)

myroot = root(eqn, 0)

print(myroot.x)

OUTPUT

RESULT

Thus the program for scipy has been verified successfully

31
EX:NO: 9(a)
IMPLEMETING REAL TIME APPLICATION USING FILE HANDLING
COPY FROM ONE FILE TO ANOTHER FILE
DATE:

AIM

To write a python program for copy the contents of one file to another file.

ALGORITHM

Step1: Start
Step2: Read the existing file.
Step3: Copy the contents of file from first file to second file by using write keyword.
Step4: View the contents of second file.
Step5: Stop

PROGRAM

print("Enter the Name of Source File: ")


sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")

32
OUTPUT

RESULT

Thus, the given program was executed successfully.

33
EX:NO: 9(b)
IMPLEMETING REAL TIME APPLICATION USING FILE HANDLING
WORD COUNT
DATE: s, the python program to copy the contents of one file to another file was created
and executed.

AIM

To write a python program for count the words in a file.

ALGORITHM

Step1: Start
Step2: Open the existing file to read in read mode.
Step3: Split the lines in a file using split( ) method.
Step4: Calculate the number of words in a file by performing,
number_of_words += len(lines)
Step5: Print the total number of words in a file.
Step6: Stop.

PROGRAM

number_of_words = 0
# Opening our text file in read only
# mode using the open() function
with open('SampleFile.txt','r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = file.read()
# Splitting the data into separate lines
# using the split() function
lines = data.split()
# Adding the length of the
# lines in our number_of_words
# variable
number_of_words += len(lines)
# Printing total number of words
print(number_of_words)

34
OUTPUT

RESULT

Thus, the python program to count the words in file has been created and executed
successfully.

35
EX:NO: 9(c)
IMPLEMETING REAL TIME APPLICATION USING FILE HANDLING
LONGEST WORD
DATE:

AIM
To write a python program to find the longest word in a file.

ALGORITHM

Step1: Start.
Step2: Open the existing file to read the contents of file.
Step3: The words in the lines are splitted using function split( ).
Step4: Maximum length of word in each line will be calculated,
max_len=len(max(words, key=len))
Step5: Check the length of word is equal to maximum length,
return[word for word in words iflen(word)==max_len]
Step6: Print the longest word in a file.
Step7. Stop.
PROGRAM

deflongest_word(filename):
withopen(filename,'r')asinfile:
words=infile.read().split()
max_len=len(max(words, key=len))
return[word for word in words iflen(word)==max_len]
print(longest_word('test.txt'))

OUTPUT
['w3resource.com.']

RESULT:

Thus, the python program to find the longest word in a file was created and
executed successfully.

36
EX:NO: 10(a)
IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
DIVIDE BY ZERO
DATE:

AIM

To write a python program for exception handling to perform divide by zero.

ALGORITHM

Step1: Start.
Step2: Get the two values by using variables num1 and num2.
Step3: Calculate the result by performing division operation.
Result= num1/num2
Step4: Print the result.
Step5: Otherwise if any invalid input print “Input Please Input Integer..."
Step6: If any value is divided by zero it throws zero division error.
Step7: Stop.

PROGRAM
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
exceptValueError as e:
print("Invalid Input Please Input Integer...")
exceptZeroDivisionError as e:
print(e)

37
OUTPUT

Enter First Number: 45


Enter Second Number: 0
division by zero

RESULT

Thus, the python program for exception handling to perform divide by zero has been
created and executed successfully.

38
EX:NO: 10(b)
IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
VOTERS AGE VALIDITY
DATE:

AIM
To write a python program for check the Voters age validity.

ALGORITHM

Step1: Start
Step2: Get the value of age.
Step3: Check if age is greater than 18.
Step4: Print eligible to vote.
Step5: Otherwise print not eligible to vote.
Step6: If any error occur means print an error occurred.
Step7: Stop

PROGRAM

def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
#display exception's default error message
exceptValueError as err:
print(err)
except:
print("An Error occured")
print("rest of the code...")
main()

39
OUTPUT

rest of the code...


Enter your ageTHIRTY
> THIRTY
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

RESULT
Thus, the python program to check the Voters age validity has been created and
executed successfully.

40
EX:NO: 10(c)
IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
STUDENT MARK RANGE VALIDATION
DATE:

AIM
To write a python program to check the validation of student marks using exception
handling.

ALGORITHM
Step1: Start.
Step2: Read the values of s1,s2,s3,s4.
Step3: Calculate total and average using formula
avg=(s1+s2+s3+s4)/4
Step4: Check if average greater than 50 print pass.
Step5: Otherwise print fail.
Step6: If any error occur means print value error.
Step7: Stop.

PROGRAM

s1=int(input("enter s1"))
s2=int(input("enter s2"))
s3= int(input("enter s3"))
s4=int(input("enter s4"))
avg=(s1+s2+s3+s4)/4
try:
if(avg>50):
print("pass")
else:
print("fail")
except:
print("valueerror")

41
OUTPUT

enter s18
enter s20
enter s37
enter s48.9
Traceback (most recent call last):
File "<string>", line 4, in <module>
ValueError: invalid literal for int() with base 10: '8.9'

RESULT

Thus, the python program for student mark validation has been created and executed
successfully.

42
EX:NO: 11
EXPLORING PYGAME TOOL
DATE:

AIM
To develop the games using python installation package by exploring Pygame tool.

EXPLORING PYGAME 1 - DISCOVERING THE LIBRARY


Game development is one of the most common reasons to start to study programming.
The pygame library as tool and I will start by the most basic principles of game development
until the creation of a single player pong like game.

PYGAME
Pygame is a set of Python modules designed to make games. It uses SDL which is a
cross-platform library that abstracts the multimedia components of a computer as audio and
video and allows an easier development of programs that uses this resources.
INSTALLATION

Before starting the installation process you must have python installed at your system.
In case you don’t have it check this installation guide first.
The pygame installation itself can be different from an OS and can be checked for more
details at its [official install guide]
(http://www.pygame.org/wiki/GettingStarted#Pygame Installation).
But, to install it into a Debian based system such as Ubuntu you must first make sure
its dependencies are installed:
$ sudo apt-get build-dep python-pygame

After that install pygame at your virtualenv:


$ pip install pygame

Or syste
$ sudo pip install pygame
m wide:
Hello World
As usual, when we are learning something new in programming we start as small as possible
to check it everything is working properly before proceeding with the studies.
To make that let’s create a file called hello.py with the following content:

43
-*- coding: utf-8 -*-
import time
importpygame
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)
Then we just need to run it:

$ python hello.py
So the result will be this:

The three first lines are common to the most programs written in python. At the first line,
we define the file encoding used by the python interpreter which was utf-8. This line is most
common at codes written in python 2 that has non ASCII characters, if you are using python 3
you probably won’t use it because utf-8 is the default encoding already. The second and third
code lines are importing the python libraries that will be responsible for all the magic.

The command pygame.init() starts all modules that need initialization inside pygame.

At pygame.display.set_mode we create an area for the game window at the size of


640x480 pixels, followed by pygame.display.set_caption were we set the value “Hello World”
to our window title.

44
With the window created we can use the command fill from screen to fill it with the
black color. The colors are passed on a list of three elements that represent the values from
RGB. Each value can go from 0 to 255. You can change the values to see by yourself the
window changing its color.

The command pygame.display.flip represents an important concept to pygame and


game development itself. When we use commands to draw at the screen, we are actually
drawing a virtual surface at the memory that represents a portion of our actual screen. To make
that drawing visible to the user we need to send it to the actual screen, and we do it in these
two separate steps to prevent from displaying incomplete frames to the user. It is like drawing
at a board and then “flipping it” to people see what we drew.

And then, to finish the command sleep from the library time makes the program to wait
5 seconds before finish the execution. Otherwise, the program would close before we see the
result.

RESULT
`Thus, the Pygame tool for development of gaming application using python has been
explored and developed successfully.

45
EX NO:12 (a)
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE
BOUNCING BALL
DATE :

AIM

To write a python program to simulate bouncing ball using pygame tool.

ALGORITHM

Step 1: Import pygame module.


Step 2: Call pygame.init() to initiate all imported pygame module.
Step 3: Set the screen size in terms of pixels using pygame.display.set_mode((400, 300)
Step 4.If there is any event in pygame queue.
a. Get the event from the pygame queue
b. If event types is pygame.QUIT then set done=true
Step 5. Else, Draw the circle update the screen display with new circle to bring bouncing effect.
Step 6. Call sys.exit() to uninitialized all the pygame modules.

PROGRAM

importpygame
frompygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
ifevent.type == pygame.QUIT:
done = True
pygame.draw.circle(screen, (255,255,255), [100, 80], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [100, 80], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [150, 95], 10, 0)
pygame.display.update()

46
pygame.draw.circle(screen, (0,0,0), [150, 95], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [250, 150], 10, 0)
pygame.display.update()
pygame.display.update()
for event in pygame.event.get():
ifevent.type == QUIT:
pygame.quit()
sys.exit()

OUTPUT:

RESULT:

Thus, the python program for bouncing ball in Pygame has been executed
successfully.

47
EX NO:12 (b)
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE
CAR GAME
DATE

AIM

To write a python program to simulate car game using Pygame tool.

ALGORITHM

Step1: Start.
Step2: Install pip pygame, py-m pip install-U pygame-user",py-m pip install pygame.
Step3: Intializes all the imported pygame modules.
Step4: Takes a tuple or a list as its parameter to create a surface (tuple preferred)
Step5: By using update( ),quit( ),Surface fill( ) functions used to develop the gaming
applications with its parameters.
Step6: Time clock and event get functions used to perform the action on time.
Step7: Stop.

PROGRAM

importpygame, random, sys ,os,time


frompygame.locals import *
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3
def terminate():
pygame.quit()

48
sys.exit()
defwaitForPlayerToPressKey():
while True:
for event in pygame.event.get():
ifevent.type == QUIT:
terminate()
ifevent.type == KEYDOWN:
ifevent.key == K_ESCAPE: #escape quits
terminate()
return
defplayerHasHitBaddie(playerRect, baddies):
for b in baddies:
ifplayerRect.colliderect(b['rect']):
return True
return False
defdrawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('car race')
pygame.mouse.set_visible(False)
# fonts
font = pygame.font.SysFont(None, 30)
# sounds
gameOverSound = pygame.mixer.Sound('music/crash.wav')
pygame.mixer.music.load('music/car.wav')
laugh = pygame.mixer.Sound('music/laugh.wav')
# images
playerImage = pygame.image.load('image/car1.png')

49
car3 = pygame.image.load('image/car3.png')
car4 = pygame.image.load('image/car4.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('image/car2.png')
sample = [car3,car4,baddieImage]
wallLeft = pygame.image.load('image/left.png')
wallRight = pygame.image.load('image/right.png')
# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) -
30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT /
3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
if not os.path.exists("data/save.dat"):
f=open("data/save.dat",'w')
f.write(str(zero))
f.close()
v=open("data/save.dat",'r')
topScore = int(v.readline())
v.close()
while (count>0):
# start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop
score += 1 # increase score
for event in pygame.event.get():

50
ifevent.type == QUIT:
terminate()
ifevent.type == KEYDOWN:
ifevent.key == ord('z'):
reverseCheat = True
ifevent.key == ord('x'):
slowCheat = True
ifevent.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
ifevent.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
ifevent.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
ifevent.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
ifevent.type == KEYUP:
ifevent.key == ord('z'):
reverseCheat = False
score = 0
ifevent.key == ord('x'):
slowCheat = False
score = 0
ifevent.key == K_ESCAPE:
terminate()
ifevent.key == K_LEFT or event.key == ord('a'):
moveLeft = False
ifevent.key == K_RIGHT or event.key == ord('d'):
moveRight = False
ifevent.key == K_UP or event.key == ord('w'):
moveUp = False

51
ifevent.key == K_DOWN or event.key == ord('s'):
moveDown = False
# Add new baddies at the top of the screen
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
ifbaddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =30
newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(random.choice(sample), (23, 47)),
}
baddies.append(newBaddie)
sideLeft= {'rect': pygame.Rect(0,0,126,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallLeft, (126, 599)),
}
baddies.append(sideLeft)
sideRight= {'rect': pygame.Rect(497,0,303,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallRight, (303, 599)),
}
baddies.append(sideRight)
# Move the player around.
ifmoveLeft and playerRect.left> 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
ifmoveRight and playerRect.right< WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
ifmoveUp and playerRect.top> 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
ifmoveDown and playerRect.bottom< WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
for b in baddies:
if not reverseCheat and not slowCheat:

52
b['rect'].move_ip(0, b['speed'])
elifreverseCheat:
b['rect'].move_ip(0, -5)
elifslowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 128, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)
drawText('Rest Life: %s' % (count), font, windowSurface,128, 40)
windowSurface.blit(playerImage, playerRect)
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])

pygame.display.update()
# Check if any of the car have hit the player.
ifplayerHasHitBaddie(playerRect, baddies):
if score >topScore:
g=open("data/save.dat",'w')
g.write(str(score))
g.close()
topScore = score
break
mainClock.tick(FPS)
# "Game Over" screen.
pygame.mixer.music.stop()
count=count-1
gameOverSound.play()
time.sleep(1)
if (count==0):

53
laugh.play()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT /
3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80,
(WINDOWHEIGHT / 3) + 30)
pygame.display.update()
time.sleep(2)
waitForPlayerToPressKey()
count=3
gameOverSound.stop()

OUTPUT

RESULT

Thus, the program for Car game using py game has been executed successfully.

54

You might also like