0% found this document useful (0 votes)
200 views53 pages

Ge3171 PSPP Lab Manual Final

The document describes a laboratory record for a student. It contains fields for student name, register number, semester, branch, and signatures of the lab incharge and head of department. It also lists experiments conducted in the GE 3171 - Problem Solving and Python Programming laboratory.

Uploaded by

dhasamalika
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)
200 views53 pages

Ge3171 PSPP Lab Manual Final

The document describes a laboratory record for a student. It contains fields for student name, register number, semester, branch, and signatures of the lab incharge and head of department. It also lists experiments conducted in the GE 3171 - Problem Solving and Python Programming laboratory.

Uploaded by

dhasamalika
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/ 53

J.K.K.

NATTRAJA
COLLEGE OF ENGINEERING & TECHNOLOGY
(Affiliated to Anna University, Chennai)
KUMARAPALAYAM-638 183.

Department of.....................................................................Laboratory Record


Name…………………………………………………………………………......
Register No………………………..……..Semester………………..…………….
Branch:…………………………………………………………………………….
Certified that this bonfide record of work done by above student of
the………………………………………………………………………………….
Laboratory during the year 20 -20

Signature of lab incharge Signature of Head of the Department

Submitted for the Practical Examination held on…………………………………...

INTERNAL EXAMINER EXTERNAL EXAMINOR


GE 3171 –PROBLEM SOLVING AND PYTHON PROGRAMING LABORATORY

YEAR & SEMESTER: I & I

LIST OF EXPERIMENTS

EX.NO List of Experiments

Developing flow charts


a) Electricity Billing
b) Retail Shop Billing
c) Sin Series
1. d) Weight of a Motorbike
e) Weight of a Steel Bar
f) Compute Electrical Current in Three Phase AC Circuit
Programs Using Simple Statements
a) Exchange the values of two variables
2. b) Circulate the values of n variables
c) Distance between two points
Programs Using Conditionals and Iterative Statements
a) Number Series
3. b) Number Patterns
c) Pyramid Pattern

a) Operations of Lists (Items present in a library/Components of acar/


Materials required for construction of a building)
4. b) Operations of Lists and Tuples (Items present in a library/Components
of a car/ Materials required for construction of a building)
a) Operations of Sets (Language, components of an automobile, Elements
ofa civil structure, etc)
5. b) Operations of Dictionaries (Language, components of an automobile,
Elements of a civil structure, etc)
Programs Using Functions
a) Factorial of a Number
6. b) Largest Number in a list
c) Area of Shape
Programs using Strings.
a) Reversing a String
b) Checking Palindrome in a String
7. c) Counting Characters in a String
d) Replacing Characters in a String

ii
Programs Using modules and Python Standard Libraries
a) Pandas
b) Numpy
8. c) Matplotlib
d) Scipy
Programs using File Handling.
a) Copy from one file to another,
9. b) Word count
c) Longest word
Programs Using Exception handling.
a) Divide by zero error
10. b) Voter’s age validity
c) Student mark range validation

11. Exploring Pygame tool.

Developing a game activity using Pygame like bouncing ball.


12.

iii
CONTENTS
Page
S.No. Date Name of the Experiment Marks Sign
No.
1 Developing flow charts

A. Electricity Billing
B. Retail Shop Billing
C. Sin Series
D. Weight of a Motorbike
E. Weight of a Steel Bar
F. Compute Electrical Current in Three Phase
AC Circuit
2 Programs Using Simple Statements

A. Exchange the values of two variables


B. Circulate the values of n variables
C. Distance between two points
Programs Using Conditionals and Iterative
3 Statements

A. Number Series
B. Number Patterns
C. Pyramid Pattern
A. Operations of Lists (Items present in a
4 library/Components of acar/ Materials required
for construction of a building)
B. Operations of Lists and Tuples (Items
present in a library/Components of a car/
Materials required for construction of a building)
A. Operations of Sets (Language,
5 components of an automobile,
Elementsofa civil structure, etc)
B. Operations of Dictionaries (Language,
components of an automobile,Elements of a civil
structure, etc)
6 Programs Using Functions
A. Factorial of a Number
B. Largest Number in a list
C. Area of Shape

iv
7 Programs using Strings.

A. Reversing a String
B. Checking Palindrome in a String

C. Counting Characters in a String

D. Replacing Characters in a String


Programs Using modules and Python Standard
8
Libraries
A. Pandas
B. Numpy
C. Matplotlib
D. Scipy

9 Programs using File Handling.

A. Copy from one file to another,

B. Word count

C. Longest word

10 Programs Using Exception handling.


A. Divide by zero error
B. Voter’s age validity
C. Student mark range validation

11 Exploring Pygame tool.


Developing a game activity using Pygame like
12
bouncing ball.

v
Ex.No 1.A
Developing flow charts for Electricity Billing
Date:

Aim:
To write a algorithm and draw flowchart for Electric Billing.

Algorithm:

Step1: Start the program

Step2: Read input n.

Step3: Check n<=100. If yes, then print amt =0. Then go to step7.

Step4: Check n<=200 is True, then calculate amt= (n-100)*1.5 and go to step 7.If no go to step5

Step5: Check n<=500.If yes, then calculate amt=200+ (n-200)*3 and go to step7.If no go to step6

Step6: Calculate amt= (100*3.5)+(300*4.6)+(n-500)*6.6

Step7: Print the amount of EB bill

Step8: Stop the program.

1
Flowchart:

Start

Read units
<=200

<=100 <=200 <=500 >500


Units
=?

Amount =100*0
Amount= (100*0)+(200-
100)*3.5+(500-200)*4.6
+(unit-500)*6.6
Amount =(100*0)+ Amount =
(unit-100)*1.5 (100*0)+ (200-100)*2+

(unit-200)*3

Print Amount

Stop

Result:

Thus, the given program successfully executed and practically verified.

2
Ex.No 1.B
Developing flow charts for Retail Shop Billing
Date:

Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.

Algorithm:

Step1: Start the program.

Step2: Read the Tax=0.18 and Rate_of_item.

Step3: Display the quantities

Step4: Read the quantities

Step5: Calculate cost using the formula, cost= Rate_of_item*quantity+ Rate_of_item*quantity+……

Step6: Calculate the BillAmount= cost+ cost*tax

Step7: Print the Bill amount.

Step8: Stop the program.

3
Flowchart:

Start

Tax=0.18

Rate_ of_ item

Display Quantities

Read Quantities

Cost=Rate _of_ item* quantity+


Rate _of_ item*quantity+……….

Bill Amount=Cost+ Cost*tax

Print Bill Amount

stop

Result:

Thus, the given program successfully executed and practically verified.

4
Ex.No 1.C
Developing flow charts for Sin Series
Date:

Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.

Algorithm:

Step1: Start the program.

Step2: Read x, n

Step3: Calculate x using the formula, x=x*3.14159/180.

Step4: Compute t=x and sum=x.

Step5: Compute i=1,for i in range(1,n).

Step6: Calculate t using the formula,t=(t*(-1)*(x*x)/(2*i(2*i+1))

Step7: Increment Sum=Sum+t

Step8: Print sum as sine(x)

Step9: Stop the program.

5
Flowchart:
Start

Read x, n

x=x*3.14159/180;

t=x;

sum=x;

i=1;i<=n; i++

t= (t*(-1)*x*x)/(2*i*(2*i+1));

sum= sum+t;

Print sum as sine(x)

stop

Result:

Thus, the given program successfully executed and practically verified.

6
Ex.No 1.D
Developing flow charts for Weight of a Motorbike
Date:

Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.

Algorithm:

Step1: Start the program.

Step2: Place the motor bike on weight case.

Step3: Read the scale in kg.

Step4: Initialise ADC=0.

Step5: Is it digitally clear? If yes display it on LCD. Otherwise, repeat step4

Step6: Stop the program.

7
Flowchart:
Start

Place the motor bike on weight case

Read the scale in kg

Initialise ADC=0

No Is it
digitally
clear?

yes

Display it on LCD

Stop
Result:

Thus, the given program successfully executed and practically verified.

8
Ex.No 1.E
Developing flow charts for Weight of a Steel Bar
Date:

Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.

Algorithm:

Step1: Start the program.

Step2: Get the input l and r.

Step3: Read den=7800

Step4: Calculate the value of weight with formula wt= (math.Pi*r*r*l*den)/10000

Step5: Print the value of wt.

Step6: Stop the program.

9
Flowchart:

Start

Input l &r

den =7800

wt =(math .pi*r*l*den)/10000

Print (wt)

stop

Result:

Thus, the given program successfully executed and practically verified.

10
Ex. No 1.F

Developing flow charts for Electrical Current in Three Phase AC Circuit.


Date:

Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.

Algorithm:

Step1: Start the program.

Step2: Read Vline ,Aline

Step3: Calculate VA using the formula,VA=√3*Vline* Aline

Step4: Print VA

Step5: Stop the program

11
Flowchart:

Start

Read Vline ,Aline

VA=√3*Vline*Aline

Print VA

Stop

Result:

Thus, the given program successfully executed and practically verified.

12
Ex. No 2.A
Exchange the values of two variables using Simple Statements
Date:

Aim
To write a python program to Exchange the values of two variables using simple
statements.
Algorithm :
Step1 : Start the program
Step 2 : Declare the values of x and y
Step 3 : Print before swaping x ,y
Step 4: compute x , y = y , x
Step 5 : Print after swaping x , y
Step 6 : stop the program .
Program
x=input(“Enter the value of x”)
y=input(“Enter the value of y”)
print(“Before exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
x,y=y,x
print(“After exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
Output
Enter the value of x 23
Enter the value of y 45
Before exchange of x,y
x=23
y=45
After exchange of x,y
x=45
y=23

Result:
Thus the above program was executed and output is verified successfully.

13
Ex. No 2.B
Circulate the Values of N Variable
Date:

Aim
To write a python program to Circulate the values of n variable using simple
statements.

Algorithm :
Step 1 : Start the program
Step 2 : Declare the value of n
Step 3 : Get the elements in the list.
Step 4 : print circulating the elements of list
Step 5 : for circulate the values of n and for i in range (n+1)
Step 6 : compute c= L[i:]+L[:i]
Step 7 : print circulation value of n
Step 8 : stop the program .

Program:
n = int(input('Enter n : '))
L=[ 91,92,93,94,95]
print("Circulating the elements of list ", L)
for i in range(n+0):
c=L[i:]+L[:i]
print(“Circulation”,i,”=”,c)

Output:
Enter n : 5
Circulating the elements of list[ 91,92,93,94,95]
Circulation 0 = [91, 92, 93, 94, 95]
Circulation 1 = [92, 93, 94, 95, 91]
Circulation 2 = [93, 94, 95, 91, 92]
Circulation 3 = [94, 95, 91, 92, 93]
Circulation 4 = [95, 91, 92, 93, 94]
Circulation 5 = [91, 92, 93, 94, 95]

Result:

Thus the above program was executed and output is verified successfully.

14
Ex. No 2.C
Distance between two points using Simple Statements
Date:

Aim:
To write a python program to find distance between two variables.
Alogrithm :
Step 1: Start the program by importing math library.
Step 2 : Declare the values of x1 , y1, x2 , y2 .
Step 3 : Calulate the distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
Step 4 : Print the distance between two points
Step 5 : Stop the program .

Program:

import math

x1=int(input(“enter a x1 value:”))

y1=int(input(“enter a y1 value:”))

x2=int(input(“enter a x2 value:”))

y2=int(input(“enter a y2 value:”))

distance=math.sqrt(((x2-x1)**2)+((y2-1)**2))

print(“distance between two points=”,distance)

Output:

enter a x1 value:3

enter a y1 value:2

enter a x2 value:7

enter a y2 value:8

distance between two points= 7.211102550927978

Result:
Thus the above program was executed and output is verified successfully.
.

15
Ex. No 3.A
Programs Using Conditionals and Iterative Statements
Date: Number Series

Aim:

To write a python program to evaluate 12+22+32+….+N2


Algorithm :
Step 1: Start the program
Step 2: Declare the value of n
Step 3: Intialize sum = 0, i=0
Step 4: Check the while condition i<=n and goes to next step
Step 5: Increment the value of I and calculate the sum value sum = sum +i*i
Step 6: Increment the I value i+=1
Step 7: Print the sum value. Execute the sum value while the condition become false.
Step 8: Stop the program.

Program:
n = int(input('Enter a number: '))
sum=0
i=1
while(i<=n):
sum=sum+i*i
i+=1
print('Sum = ',sum)

Output:

Enter a number: 10

Sum = 385

Result:

Thus the above program was executed and output is verified successfully.

16
Ex. No 3.B
Programs Using Conditionals and Iterative Statements
Date: Number Pattern

Aim:
To write a python program to print Number Pattern.
Algorithm ;
Step 1 : Start the program .
Step 2 : Define the value of n
Step 3 : Check the condition of for i in loop (1,n+1)
Step 4: Next, check for k in range (n,i-1)
Step 5 : print (“ “)
Step 6 : Check the condition for j in range (1,1+1)
Step 7 : print (“ “)
Step 8 : Check the last condition of for m in (i-1,0-1)
Step 9 : Print (“ “)
Step 10 : print ()
Step 11: stop the program.

Program:
N = int(input("enter n value:"))
for i in range(1,N+1):
for k in range(N,i,-1):
print(" ", end =' ')
for j in range(1,i+1):
print(j, end =' ')
for m in range(i-1,0,-1):
print(m, end =' ')
print()

Output:
enter n value:5
1
121
12321
1234321
123454321

Result:

Thus the above program was executed and output is verified successfully.

17
Ex. No 3.C
Programs Using Conditionals and Iterative Statements Pyramid Pattern
Date:

Aim:
To write a python program to print Pyramid Pattern.

Algorithm :
Step 1 : Start the program .
Step 2 : Declare the value for n
Step 3 ; Check the condition for i in 1 to n+1
Step 4 : Next , check the condition for j in 0 to i
Step 5 : Print (*)
Step 6 : Print ()
Step 7 : Stop the program.

Program:
# to print pyramid pattern1
n=int(input("enter the value:"))
for i in range(1, n+1):
for j in range(0, i):
print("* ",end=' ')
print()
print(' ')
# to print pyramid pattern2
for i in range(1,n+1):
print(' '*(n-i), end=' ')
for j in range(1, i+1):
print('* ',end=' ')
print()
print(' ')
# to print pyramid pattern3
for i in range(1,n+1):
for j in range(1, n-i+2):
print('* ',end=' ')
print()
print(' ')
# to print pyramid pattern3
for i in range(1,n+1):
print(' '*(i-1), end=' ')
for j in range(1, n-i+2):
print('* ',end='')
print()
print(' ')

18
Output:
enter the value:5
*
**
***
****
*****

*
**
***
****
*****

*****
****
***
**
*

*****
****
***
**
*

Result:

Thus the above program was executed and output is verified successfully.

19
Ex. No 4.A
Operations of List
Date:

Aim:

To implement operations in a library list.


Algoritm:
Step:1 Start the program by declaring a list of items in a Library.
Step2: Print the complete list.
Step:3 Printing first and fourth element using index value.
Step:4 Print list elements from 0th index to 4th index from the list using silicing method.
Step5: Appending an element to the list library.append('Audiobooks')
Step6: Print the sorting the elements of List and popping an element in a list.
Step7: print the removed specified elementlibrary.remove('Maps')
Step 8: Print Number of Ekements in Library list
Step9: End the program.
Program:
library =['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
print('Library: ',library)
print('first element: ',library[0])
print('fourth element: ',library[3])
print('Items in Library from 0 to 4 index: ',library[0: 5])
print('3rd or -7th element: ',library[-7])
library.append('Audiobooks')
print('Library list after append(): ',library)
print('index of \'Newspaper\': ',library.index('Newspaper'))
library.sort()
print('after sorting: ', library)
print('Popped elements is: ',library.pop())
print('after pop(): ', library)
print('after removing \'Maps\': ',library)
# inserting an element at specified index
# inserting 100 at 2nd index
library.insert(2, 'CDs')
print('after insert: ', library)
print(' Number of Elements in Library list : ',len(library)

Output:

Library:['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps', 'Prints','Documents', 'Ebooks']

20
first element: Books

fourth element: Manuscripts


Items in Library from 0 to 4 index:['Books', 'Periodicals', 'Newspaper','Manuscripts', 'Maps']

3rd or -7th element: Periodicals

Library list after append():['Books', 'Periodicals', 'Newspaper', 'Manuscripts','Maps', 'Prints', 'Documents',


'Ebooks', 'Audiobooks']

index of 'Newspaper':2

after sorting:['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps','Newspaper', 'Periodicals',


'Prints']

Popped elements is:Prints

after pop(): ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps','Newspaper', 'Periodicals']

after removing 'Maps':['Audiobooks', 'Books', 'Documents', 'Ebooks','Manuscripts', 'Newspaper', 'Periodicals']

after insert:['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks', 'Manuscripts','Newspaper', 'Periodicals']

Number of Elements in Library list :8

Result:

Thus the above program was executed and output is verified successfully.

21
Ex. No 4.B
Operations of Tuple
Date:

Aim:

To Implement operations in a Car Tuple.


Algorithm:
Step1: Start the program by declaring a tulple of components of a car.
Step2: Print the complete tuple
Step3:Display the first element as car[0] and fourth element as car[3].
Step4: Print tuple elements from 0th index to 4th index
Step5: Find the Number of Elements in car tuple by using len().
Step6: End the program.

Program:

# Python code for various Tuple operation


# declaring a tuple of Components of a car
car = ('Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt')
# printing the complete tuple
print('Components of a car: ',car)
# printing first element
print('first element: ',car[0])
# printing fourth element

print('fourth element: ',car[3])

# printing tuple elements from 0th index to 4th index


print('Components of a car from 0 to 4 index: ',car[0: 5])
# printing tuple -7th or 3rd element from the list
print('3rd or -7th element: ',car[-7])
# finding index of a specified element
print('index of \'Alternator\': ',car.index('Alternator'))
# Number of Elements in car tuple
print(' Number of Seat belts in Car Tuple :',car.count('SeatBelt'))

22
#Length of car tuple
print(' Length of Elements in Car Tuple : ',len(car))

Output:
Components of a car:('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break','Seat Belt')
first element: Engine
fourth element : Radiator
Components of a car from 0 to 4 index:('Engine', 'Battery', 'Alternator', 'Radiator','Steering')
3rd or -7th element: Engine
index of 'Alternator':2
Number of Seat belts in Car Tuple:1

Length of Elements in Car Tuple :7


Result:

Thus the above program was executed and output is verified successfully.

23
Ex. No 5.A
Operations of Set
Date:

Aim:

To implement operations in a set using Components of a Language as example.


Algorithm:
Step1:Start the Program.

Step 2:Create two set of Elements.

Step3:Compare two set of Elements using Union Operator

Step 4:Compare two set of elements Using intersection Operation.

Step 5:Compare two set of elements using Difference Operator.

Step 6:Compare two set of elements using Set symmetric difference operation.

Step7:Stop the program.

Program:

S1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};

S2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};# set union

print("Union of S1 and S2 is ",S1 | S2)# set intersection

print("Intersection of S1 and S2 is",S1 & S2)# set difference

print("Difference of S1 and S2 is",S1 - S2)# set symmetric difference

print("Symmetric difference of S1 and S2 is",S1 ^ S2)

Output:

Union of S1 and S2 is{'Words', 'Pitch', 'Sentences', 'Phonetics', 'Script', 'Grammar','Syllabus', 'Context'}


Intersection of S1 and S2 is{'Grammar', 'Syllabus'}
Difference of S1 and S2 is{'Script', 'Pitch', 'Sentences'}
Symmetric difference of S1 and S2 is {'Words', 'Context', 'Script', 'Pitch','Sentences', 'Phonetics'}

Result:

Thus the above program was executed and output is verified successfully.

24
Ex. No 5.B
Operations of Dictionaries
Date:
Aim:

To implement operations in a set using Components of a Language as example.

Algoithm:

Step 1:Start the program.


Step 2:Create set of dictionary elements using variable name.

Step 3: Print the entire dictionary element using print method.


Step 4:Access the single key element and print the result.

Step 5:Access the single values by calling values().

Step 6:Display the length of the dictionary elements.

Step 7:Check the Keys and Values Using „in‟ operator.


Step 8:Stop the program.

Program:
civ={'name':'civil structure',2:'floor',3:'stairs',4:'beams',5:'walls'}
print(civ)
print(civ['name'])
print(civ.get(4))
print(len(civ))
print('name' in civ)
print(1 in civ)
print(civ.values())
print(civ.keys())

Output:
{'name': 'civil structure', 2: 'floor', 3: 'stairs', 4: 'beams', 5: 'walls'}
civil structure
beams
5
True
False
dict_values(['civil structure', 'floor', 'stairs', 'beams', 'walls'])
dict_keys(['name', 2, 3, 4, 5])

Result:

Thus the above program was executed and output is verified successfully.

25
Ex. No 6.A
Factorial of a Number Using Recursive Function
Date:

Aim:
To write a python program to Factorial of a number using Recursive Function.
Algorithm:
Step1: Start the program.
Step2: Get the input n.
Step3: Define the function fact(x).
Step4: If x==1, then return 1.Otherwise return (x*fact(x-1)).
Step5: Print the factorial of a number.
Step6: Stop the program.

Program:
def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))
n=int(input(“Enter a number:”))
print(“The factorial of”, n,”is”,fact(n))

Output:

Enter a number:5

The factorial of 5 is 120.

Result:

Thus the above program was executed and output is verified successfully.

26
Ex. No 6.B
Finding Largest Number in a List using Function
Date:

Aim:
To write a python program to find the largest number in a list using function.

Algorithm:
Step1: Start the program.
Step2: Get the input num.
Step3: Using for loop which has the range(1,num+1).Read the element in the list.
Step4: Define the function myMax (list1) and find the largest number in a list.
Step5: Print the largest number in a list.
Step6: Stop the program.
Program:
def myMax(list1):
print(“Largest element is:”, max(list1))
list1=[]
num=int(input(“Enter a number of elements in a list:”))
for i in range(1,num+1):
ele=int(input(“Enter elements:”))
list1.append(ele)
print(my Max(list1))
Output:
Enter a number of elements in a list:5
Enter elements:23
Enter elements:45
Enter elements:87
Enter elements:67
Enter elements:39
Largest element : 87

Result:
Thus the above program was executed and output is verified successfully.

27
Ex. No 6.C
Finding Area of a Shape using Function
Date:

Aim:
To write a python program to find the area of the different shapes using function.

Algorithm:
Step1: Start the program.
Step2: Define the function square.
Step3: Get the input value of side and print the area of square. (i.e., side*side)
Step4: Define the function rectangle.
Step5: Get the input value of l and b and print the area of rectangle. (i.e., l*b)
Step6: Define the function triangle.
Step7: Get the input value b and h and print the area of triangle. (i.e., 0.5*b*h)
Step8: Define the function circle.
Step9: Get the input value r and print area of circle. ((i.e., 3.14*r**2)
Step10: Print 1. square, 2. rectangle, 3. triangle and 4. circle.
Step11: Get the n value as input.
Step12: Compute if n==1, then call the function square. If no go to next step.
Step13: If n==2,then call the function rectangle. If no go to next step.
Step14: If n==3,then call the function triangle. If no go to next step.
Step15: If n==4,then call the function circle. Otherwise go to next step.
Step16: Print invalid choice.
Step17: Stop the program.

Program:
def square():
side=int(input(“Enter the side of a square:”))
print(“Area of a square:”, side*side)
def rectangle():
l=int(input(“Enter the length of a rectangle:”))
b=int(input(“Enter the breath of a rectangle:”))
print(“Area of a rectangle:”, l*b)
def triangle():
b=int(input(“Enter the base of a triangle:”))
h=int(input(“Enter the height of a triangle:”))
print(“Area of a triangle:”, b*h*0.5)

28
def circle():
r=float(input(“Enter the radius of a circle:”))
print(“Area of a circle:”, 3.14*r**2)
print(“1. Square 2. Rectangle 3. Triangle 4. Circle “)
n=int(input(“Enter your choice:”))
if n==1:square()
elif n==2:rectangle()
elif n==3:triangle()
elif n==4:circle()
else: print(“Invalid Choice”)

Output:

1. Square 2. Rectangle 3. Triangle 4. Circle

Enter your choice:4

Enter the radius of a circle:14

Area of a circle:615.44

1. Square 2. Rectangle 3. Triangle 4. Circle

Enter your choice:2

Enter the length of a rectangle:12

Enter the breath of a rectangle: 15

Area of a rectangle: 180.00

Result:

Thus the above program was executed and output is verified successfully.

29
Ex. No 7.A
Reversing a String
Date:

Aim:
To write a python program to reverse a string.

Algorithm:
Step1: Read the input str.
Step2: Using the colon operator, the string get reversed.
Step3: Print the reversed string.

Program:
str=input(“Enter the string:”)
rev=str[::-1]
print(“The reversed string is:”,rev)

Output:
Enter the string: python
The reversed string is: nohtyp

Result:

Thus the above program was executed and output is verified successfully.

30
Ex. No 7.B
Checking Palindrome in a String
Date:

Aim:
To write a python program to check whether the given string is Palindrome.

Algorithm:

Step1: Start the program.

Step2: Reverse the str using the colon operator

Step3: If str==rev, print the given string is palindrome otherwise, go to step4.

Step4: print the given string is not palindrome.

Step5: Stop the program.

Program:

str=input(“Enter the string:”)

rev=str[::-1]

if str==rev:

print(“Given string is palindrome”)

else:

print(“Given string is not palindrome”)

Output:

Enter the string: AMMA

Given string is palindrome

Enter the string: PROGRAM

Given string is not palindrome

Result:

Thus the above program was executed and output is verified successfully.

31
Ex. No 7.C
Counting Characters in a String
Date:

Aim:
To write a python program to count a character in a string.

Algorithm:
Step1: Get the input str and ch.
Step2: Using the count method find the number of characters in str and assign it as val.
Step3: Print val
Step4: stop the program.

Program:
str=input(“Enter the string”)
ch=input(“Enter the character:”)
val=str.count(ch)
print(val)

Output:
Enter the string: PYTHON PROGRAMMING
Enter the character: G
2

Result:

Thus the above program was executed and output is verified successfully.

32
Ex. No 7.C
Replace Characters in a String
Date:

Aim:
To write a python program to replace a character in a string.

Algorithm:
Step1: Start the program.

Step2: Get the input str,old and new.

Step3: By using replace method,replace old string by new string

Step4: Print (str.replace(old,new))

Step5: Stop the program

Program:
str=input(“Enter the string:”)

old=input(“Enter the old string:”)

new=input(“Enter the new string:”)

print(str.replace(old,new))

Output:
Enter the string: PYTHON PROGRAMMING

Enter the old string: PYTHON

Enter the new string: C PROGRAMMING

C PROGRAMMING PROGRAMMING

Result:

Thus the above program was executed and output is verified successfully.

33
Ex. No 8.A
Compare the Elements of the Two Pandas Series using Pandas Library
Date:

Aim:
To write a python program to compare the elements of the two Pandas series using pandas
library.

Algorithm:
Step1: Start the program.
Step2: Import the library function Pandas.
Step3: Give the inputs as ds1, ds2 in the form of lists.
Step4:ds1 is interpreted as Series1.
Step5:ds2 is interpreted as Series2.
Step6: Compare Series1 and Series2 and follow the steps 6.1,6.2,6.3.
6.1.ds1==ds2
6.2.ds1>ds2
6.3.ds1<ds2

Program:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:") print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)

Output:
Series1:
02
14
26
38
4 10
dtype: int64

34
Series2:
01
13
25
37
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Less than:
0 False
1 False
2 False
3 False
4 False
dtype: bool

Result:

Thus, the given program successfully executed and practically verified.

35
Ex. No 8.B
To Test whether None of the Elements of a Given Array is Zero Using Numpy
Library
Date:

Aim:
To write a python program to test whether none of the elements of a given array is
zero using numpy library.

Algorithm:
Step1:Start the program.
Step2:Import the numpy library as np.
Step3:Give the input x as array.
Step4:Print x as Original Array.
Step5:Check whether any of the elements is zero or not.
Step6:print the statement.
Step7:Close the program.

Program:
import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))

Output:

Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False

Result:
Thus, the given program successfully executed and practically verified.

36
Ex. No 8.C
To Plot a Graph Using Matplotlib Library
Date:

Aim:
To write a python program to plot a graph using matplotlib library.

Algorithm:
Step1:Start the program.
Step2:Import matplotlib and numpy as plt and np respectively.
Step3:Give input xpoints and ypoints in the form of array.
Step4:Now plot the points using plt.plot function.
Step5:Display the graph using plt.show() fuction
Step6:Close the program.

Program:

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

Output:

Result:
Thus, the given program successfully executed and practically verified.

37
Ex. No 8.D
To Return the Specified Unit in Seconds Using Scipy Library
Date:

Aim:
To write a python program to return the specified unit in seconds (e.g. hour returns 3600.0)
using scipy library.

Algorithm:
Step1: Start the program.

Step2: Import scipy as constants.

Step3: Print Minutes, Hours, Days, Weeks,Years, Julian_Year

Program:
from scipy import constants
print(constants.minute)

print(constants.hour)

print(constants.day)
print(constants.week)

print(constants.year)

print(constants.Julian_year)

Output:
60.0
3600.0

86400.0
604800.0

31536000.0

31557600.0

Result:
Thus, the given program successfully executed and practically verified.

38
Ex. No 9.A
COPY FROM ONE FILE TO ANOTHER FILE
Date:

Aim:
To write a python program to copy from one file to another file.

Algorithm:
Step-1- Start the program
Step-2- Import the copy file from the shutil
Step-3- Enter the source file
Step-4- Enter the destination file
Step-5- The file copy from the source file to the destination file using copy file module.
Step-6- If the file is successfully copied, then show „file copied successfully‟
Step-7- Open the destination file and read.
Step-8- Close the file.
Step-9- Stop the program.

Program:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
c = open(destinationfile, "r")
print(c.read())
c.close()
print()
print()
Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully!
Sunflower
Jasmine
Roses

Result:
Thus, the given program successfully executed and practically verified.

39
Ex. No 9.B
WORD COUNT FROM FILE
Date:

Aim:
To write a python program to count number of word in a file.

Algorithm:
Step-1: Start the program.

Step-2: Open the file by using open module and read the file as the text format denoted by „rt‟.

Step-3: Read the file.

Step-4: Split the number of word in the file.

Step-5: Count the splited word and display.

Step-6: End the program.

Program:

file = open("F:\Data.txt", "rt")


data = file.read()
words = data.split()
print('Number of words in text file :', len(words))

Output:
Number of words in text file : 36

Result:
Thus, the given program successfully executed and practically verified.

40
Ex. No 9.C
Finding Longest Word in a File
Date:

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

Algorithm:
Step-1- Start the program.

Step-2- call the function longest_word() and give the filename.

Step-3-End the program

Sub function()

Step-1-define the function longest_word()

Step-2- open the file and read and split the words.

Step-3- find the longest word in the splited word.

Step-4- Display the longest word.

Step-5- End the program.

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('F:\Data.txt'))

Output:

['collection']

Result:
Thus, the given program successfully executed and practically verified.

41
Ex. No 10.A
Divide by Zero Error using Exception Handling
Date:

Aim:
To write a python program to handle divide y zero error using exception handling.

Algorithm:
Step-1- Start the Program
Step-2- Get num1, num2.
Step-3- Evaluate the result by num1/num2.
Step-4- print result.
Step-5- Otherwise display the e.
Step-6-End 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)
Output:
enter first number: 33
enter second number:23
1.434782608695652

Result:
Thus, the given program successfully executed and practically verified.

42
Ex. No 10.B
Voters Age Validity Using Exception Handling
Date:

Aim:
To write a python program to check voters age validity.

Algorithm:
Step-1- Start the program by defining main function.
Step-2- Get the age as input.
Step-3- Check the condition age>18, display eligible to vote, otherwise, display not eligible.
Step-4- if the try block is not executed, exception block get executed.
Step-5- Stop the program.
Program:

def main():
try:
age=int(input("enter your age"))
if age>18:
print("eligible to vote")
else:
print("not eligible to vote")
except ValueError as err:
print(err)
print("an error occured")
print("rest of the code...")
main()

Output:
enter your age18
not eligible to vote

enter your age45


eligible to vote

Result:
Thus, the given program successfully executed and practically verified.

43
Ex. No 10.C
Student Mark Range Validation
Date:

Aim:
To write a python program to perform student mark range validation.

Algorithm:
Step-1- Start the Program by defining main function.
Step-2- Get marks Step-3- using try Check if mark>=3 and mark<101 display pass and mark is
valid, otherwise fail.
Step-4- Otherwise display the exception block.
Step-5- Stop the Program.

Program:

def main():
try:
mark=int(input("Enter your mark:"))
if mark>=35 and mark<101:
print("pass and your mark is valid")
else:
print("fail and your mark is valid")
except ValueError:
print("mark must be a valid number")
except IOError:
print("Enter correct valid mark")
except:
print("An ERror occured")
main()
Output:
Enter your mark:59
pass and your mark is valid

Enter your mark: 20


fail and your mark is valid

Enter your mark:aa


mark must be a valid number

Result:
Thus, the given program successfully executed and practically verified.

44
Ex. No 11
Exploring Pygame
Date:

PYGAME INSTALLATION
To Install Pygame ModuleSteps
1. Install python 3.6.2 into C:\
2. Go to this link to install pygame www.pygame.org/download.shtml

3. Click
pygame-1.9.3.tar.gz ~ 2M and download zar file
4. Extract the zar file into C:\Python36-32\Scripts folder
5. Open command prompt
Type the following command
C:\>py -m pip install pygame --
userCollecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)

100% |████████████████████████████████| 4.0MB


171kB/s

Installing collected packages:


pygameSuccessfully installed
pygame-1.9.3
7. Now, pygame installed successfully

45
8. To see if it works, run one of the included examples in pygame-1.9.3

 Open command prompt


 Type the following

C:\>cd Python36-32\Scripts\pygame-1.9.3
C:\Python36-32\Scripts\pygame-1.9.3>cd
examples
C:\Python36-32\Scripts\pygame-
1.9.3\examples>aliens.pyC:\Python36-
32\Scripts\pygame-1.9.3\examples>

46
Ex. No 12
Simulate Bouncing Ball using Pygame
Date:
Aim:
To write a python program to bouncing ball in pygame.

Algorithm:
Step1: Start the program.
Step2: Set screen size and background color.
Step3: Set speed of moving ball.
Step4: Create a graphical window using set_ mode()
Step5: Set caption.
Step6: Load the ball image and create a rectangle area covering the image
Step7: Use blit() method to copy the pixel color of the ball to the screen
Step8: Set back ground color of screen and use flip() method to make all
images visible.
Step9: Move the ball in specified speed.
Step10: If ball hits the edges of the screen reverse the direction.
Step11: Create an infinite loop and Repeat steps 9 and 10 until user qu its the
progra m
Step12: Stop the program

Program:

import sys, pygame


pygame.init()
size = width, height = 700, 250
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
pygame.time.delay(2)
for event in pygame.event.get():
if event.type == pygame.QUIT:

sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:

47
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
ball.jpg

Output:

Result:
Thus, the given program successfully executed and practically verified.

48

You might also like