0% found this document useful (0 votes)
17 views106 pages

Ge3171-Pspp Lab Manual Final

The document is a lab manual for the GE3171 Problem Solving and Python Programming Laboratory at Varuvan Vadivelan Institute of Technology for the academic year 2024-2025. It outlines various experiments and programming tasks aimed at solving real-life problems using Python, including electricity billing, retail shop billing, and calculations involving lists, tuples, sets, and dictionaries. The manual includes detailed algorithms, flowcharts, sample outputs, and Python programs for each experiment.
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)
17 views106 pages

Ge3171-Pspp Lab Manual Final

The document is a lab manual for the GE3171 Problem Solving and Python Programming Laboratory at Varuvan Vadivelan Institute of Technology for the academic year 2024-2025. It outlines various experiments and programming tasks aimed at solving real-life problems using Python, including electricity billing, retail shop billing, and calculations involving lists, tuples, sets, and dictionaries. The manual includes detailed algorithms, flowcharts, sample outputs, and Python programs for each experiment.
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/ 106

VARUVAN VADIVELAN INSTITUTE OF TECHNOLOGY

Dharmapuri – 636 703

Regulation- 2021

GE3171 PROBLEM SOLVING AND PYTHON


PROGRAMMING LABORATORY

LAB MANUAL

ACADEMIC YEAR 2024-2025 (ODD SEMESTER)

I Year / I Semester
(Common to all Branches)

1
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motorbike,
Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of list
& tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language, components
of an automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (Reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to another,
word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.

Total Hours: 60

2
INDEX
EX. NO. NAME OF THE EXPERIMENT PAGE NO.

a. Electricity Billing 1

b. Retail Shop Billing 5


1
c. Weight of a Steel Bar 8

d. Compute Electrical Current in 3 Phase AC Circuit 11

Programs Using Simple Statements

a. Exchange the Values of Two Variables 14


2
b. Circulate the Values of N Variables 17

c. Distance Between Two Variables 20

Programs Using Conditionals & Iterative Loops

a. Number Series 23
3
b. Number Pattern 26

c. Pyramid Pattern 29

Lists & Tuples

4 a. Operations of Lists 32

b. Operations of Tuples 35

Sets & Dictionaries

5 a. Operations of Sets 38

b. Operations of Dictionaries 41

Functions

a. Factorial of a Number Using Function 44


6
b. Finding Largest Number in a List Using
47
Function
c. Finding Area of a Circle Using Function 50

1
String Operations 53

a. Reversing a String 56
7
b. Checking Palindrome in a String 59

c. Counting Characters in a String 62

d. Replace Characters in a String 65

Python Programs in Jupyter Notebook


a. Compare the Elements of Two Pandas Series Using Pandas
68
Library
b. Program to Test Whether None of the Elements of a Given
8 71
Array is Zero Using Numpy Library
c. Program to Plot a Graph Using Matplotlib Library 74
d. Python Program to Return the Specified Unit in Seconds Using
77
Scipy Library
Files

a. Copy From One File to Another 80


9
b. Word Count from a File 83

c. Finding Longest Word in a File 86

Exception Handling

a. A Divide by Zero Error Using Exception Handling 89


10
b. Voters Age Validity 92

c. Student Mark Range Validation 95

11 Exploring Pygame 98

12 Simulate Bouncing Ball Using Pygame 100

2
EX.NO: 1. a
ELECTRICITY BILLING

AIM:
To write a python program for implementing electricity billing.

ALGORITHM:

STEP 1: Start the program

STEP 2 :Get the total units of current consumed by the customer using the variable unit.

STEP 3:If the unit consumed less or equal to 100 units, calculates the total amount of consumed

payAmount=0

STEP 4: If the unit consumed between 100 to 200 units, calculates the total amount of

consumedPayAmount=(units-100)*2.25

STEP 5:If unit consumed between 200 to 400 units ,calculates total amount of consumed

PayAmount=(100*2.25)+(200*4.5)+(units-400)*6.

STEP 6: If unit consumed between 400-600 units ,calculates total amount of consumed=

PayAmount payAmount=(100*2.25)+(200*4.5)+(100*6)+(units-500)*8

STEP 7: If the unit consumed above 600 units,calculates total amount of consumed=

=(100*2.25)+(200*4.5)+(100*6)+(200*8)+(units-600)*10

STEP 8: Stop the program

1
FLOW CHART:
START

Read units of current


consumed

IF
Units<=100

payAmount=0

elif
unit<=200
PayAmount=
(units-100)*2.25

elif
unit<=400
PayAmount=(100*2.25)+(200
*4.5)+(units-400)*6

elif
unit<=600
payAmount=(100*2.25)+(200*4.5)+(
100*6)+(units-500)*8

elif payAmount
unit>600 =(100*2.25)+(200*4.5)+(100*6)+(200*
8)+(units-600)*10

PayAmount=0

STOP

2
OUTPUT:
Please enter the number of units you consumed in a month: 120
Electricity bill=200.00

3
PROGRAM:
units=int(input("Please enter the number of units you consumed in a month : "))
if(units<=100):
payAmount=units*1.5
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
else:
payAmount=1500

Total=payAmount;
print("\nElectricity bill=%.2f" %Total)

RESULT:
Thus, the python program for implementing electricity billing is executed and the
output is obtained.

4
EX.NO: 1. b
RETAIL SHOP BILLING

AIM:
To write a python program for implementing retail shop billing.

ALGORITHM:

STEP 1: Start the program


STEP 2: Assign tax=0.18
STEP 3: Assign rate for pencil, pen, scale and A4paper
STEP 4: Get the quantity of items from the user
STEP 5: Calculate total cost by multiplying rate and quantity of the items
STEP 6: Add tax value with the total cost and display the bill amount
STEP 7: Stop the program.

FLOWCHART:
START

Assign tax=0.18

Assign rate={“Pencil”:10,”Pen”:20,

”Scale”:7,”A4Sheet”:150}

Read quantity of
all items from

Calculate
cost=Pencil*Rate[“Pencil”]+Pen*Rate[“Pen”]+
Scale*Rate[“Scale”]+A4Sheet*Rate[A4Sheet]

Calculate Bill=cost+cost*tax

Print Bill

STOP
5
OUTPUT:
Retail Bill Calculator
Enter the quantity of the ordered items:

Pencil:5
Pen:2
Scale:2
A4Sheet:1
Please pay Rs.299.720000

6
PROGRAM:

tax=0.18
Rate={"Pencil":10,"Pen":20,"Scale":7,"A4Sheet":150}
print("Retail Bill Calculator\n")
print("Enter the quantity of the ordered items:\n")
Pencil=int(input("Pencil:"))
Pen=int(input("Pen:"))
Scale=int(input("Scale:"))
A4Sheet=int(input("A4Sheet:"))
cost=Pencil*Rate["Pencil"]+Pen*Rate["Pen"]+Scale*Rate["Scale"]+A4Sheet*Rate["A4S
heet"]
Bill=cost+cost*tax
print("Please pay Rs.%f"%Bill)

RESULT:
Thus, the python program for implementing retail shop billing is executed and the
output is obtained.

7
EX.NO: 1.c
WEIGHT OF A STEEL BAR

AIM:
To write a python program to calculate weight of a steel bar.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the diameter (D) value from user
STEP 3: Calculate weight=(D*D)/162
STEP 4: Print the weight
STEP 5: Stop the program

FLOWCHART:

START

Read
Diameter

Calculate
Weight=(D*D)/162

Print

STOP

8
OUTPUT:
Calculating weight of a steel bar:
Enter the Diameter of Steel bar:250
Weight of the steel bar is 385.000000 Kg/m

9
PROGRAM:

print("Calculating weight of a steel bar:\n")


D=int(input("Enter the Diameter of Steel bar:"))
Weight=(D*D)/162
print("Weight of the steel bar is %f Kg/m" %Weight)

RESULT:
Thus, the python program for calculating the weight of the steel is executed and the
output is obtained.

10
EX.NO: 1. d
COMPUTE ELECTRICAL CURRENT IN 3 PHASE AC CIRCUIT

AIM:
To write a python program to calculate electrical current in 3 phase AC circuit.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of volts and amperes from user
STEP 3: Calculate power=√3 *volts*amperes
STEP 4: Print the value of power
STEP 5: Stop the program

FLOWCHART:

START

Read Volts,
Amperes

Calculate

power=√3 * Volts*Amperes

Print power

STOP

11
OUTPUT:
Calculating electrical current of 3 phase AC circuit:
Enter the volts value:56
Enter the amperes value:85
Power = 8244.561844 KVA

12
PROGRAM:
import math
print("Calculating electrical current of 3 phase AC circuit:\n")
volts=int(input("Enter the volts value:"))
amperes=int(input("Enter the amperes value:"))
power=math.sqrt(3)*volts*amperes
print("Power = %f KVA" %power)

RESULT:
Thus, the python program to compute electrical current in 3 phase AC circuit is executed
and the output is obtained.
13
EX.NO: 2. a PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE VALUES OF
TWO VARIABLES

AIM:
To write a python program to exchange the values of two variables.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of x and y
STEP 3: Exchange the values using the assignment statement x,y=y,x
STEP 4: Print the values
STEP 5: Stop the program

14
OUTPUT:

Enter value of X 85
Enter value of Y 63
Before exchange of x,y
('x =', 85)
('Y= ', 63)
After exchange of x,y
('x =', 63)
('Y= ', 85)

15
PROGRAM:
def exchange(x,y):

x,y=y,x
print("After exchange of x,y")
print("x =",x)

print("Y= ",y)
x=input("Enter value of X ")
y=input("Enter value of Y ")
print("Before exchange of x,y")

print("x =",x)
print("Y= ",y)

exchange(x,y)

RESULT:
Thus, the python program to exchange the values of two variables is executed and the
output is obtained.

16
EX.NO: 2. b
CIRCULATE THE VALUES OF N VARIABLES

AIM:
To write a python program to circulate the values of n variables.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of n
STEP 3: Circulate the values using slice operator
STEP 4: Print the values
STEP 5: Stop the program

17
OUTPUT:
Enter n: 5
('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])

18
PROGRAM:

def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("Circulation",i,"=",B)
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)

RESULT:
Thus, the python program to circulate the values of n variables is executed and the output
is obtained.

19
EX.NO: 2. c DISTANCE BETWEEN TWO VARIABLES

AIM:
To write a python program to calculate distance between 2 variables.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of x1, x2, y1 and y2

STEP 3: Calculate distance=√((𝑥2 − 𝑥1) ∗∗ 2) − ((𝑦2 − 𝑦1) ∗∗ 2)

STEP 4: Print the distance


STEP 5: Stop the program

20
OUTPUT:
Enter a x1: 50
Enter a y1: 50
Enter a x2: 320
Enter a y2: 320
Distance = 381.84

21
PROGRAM:

import math
x1 = int(input("Enter a x1: "))
y1 = int(input("Enter a y1: "))
x2 = int(input("Enter a x2: "))
y2 = int(input("Enter a y2: "))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = %.2f"%distance)

RESULT:
Thus, the python program to circulate the distance between two variables is executed and
the output is obtained.

22
EX.NO: 3. a PROGRAMS USING CONDITIONALS & ITERATIVE LOOPS
NUMBER SERIES

AIM:
To write a python program to calculate 12+22+32+…. +N2.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of n
STEP 3: +N2) using while condition
STEP 4: Print the value
STEP 5: Stop the program

23
OUTPUT:

Enter a number: 5
('Sum = ', 55)

24
PROGRAM:

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


sum=0
i=1
while i<=n:
sum=sum+i*i
i+=1
print('Sum = ',sum)

RESULT:
Thus, the python program to calculate 12+22+32+…. +N2 is executed and the output is
obtained.

25
EX.NO: 3. b
NUMBER PATTERN

AIM:
To write a python program to print number pattern.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the number of rows to print from user
STEP 3: Print the pattern using for loops
STEP 4: Stop the program

26
OUTPUT:
Number Pattern Printing
Enter no. of rows to print: 5
1
12
123
1234
12345

27
PROGRAM:

print("Number Pattern Printing")


rows=int(input("Enter no.of rows to print:"))
for i in range(1, rows + 1):
print(end=' ')
for j in range(1, i + 1):
print(j,end=' '),
print(' ')

RESULT:
Thus, the python program to program to print number pattern is executed and the output
is obtained.

28
EX.NO: 3. c
PYRAMID PATTERN

AIM:
To write a python program to print number pattern.

ALGORITHM:
STEP 1: Start the program
STEP 2: Read the number of rows to print from user
STEP 3: Print the pyramid pattern using for loops
STEP 4: Stop the program

29
OUTPUT:

Print equilateral triangle Pyramid using asterisk symbol


Enter no.of rows:5
*
* *
* * *
* * * *
* * * * *

30
PROGRAM:

print("Print equilateral triangle Pyramid using asterisk symbol ")


size =int(input("Enter no.of rows:"))
m = (2 * size) - 2
for i in range(0, size):
print(end=' ')
for j in range(0, m):
print(' ', end = " ")
m=m-1
for j in range(0, i + 1):
print(" * ", end =' ')
print(" ")

RESULT:
Thus, the python program to program to print pyramid pattern is executed and the output
is obtained.

31
EX.NO: 4. a
OPERATIONS OF LISTS

AIM:

To implement List Operations in Library List.

ALGORITHM:

STEP 1: Start.

STEP 2: Declare a list variable named library and assign values to the list.

STEP 3: Print all the elements in the list.

STEP 4: Print random position values in the list.

STEP 5: Print the index value in the list.

STEP 6: Append values to the list.

STEP 7: Sort the elements in the list using sort () function.

STEP 8: Pop elements from the list using pop () function.

STEP 9: Remove specific element from the list using remove () function.

STEP 10: Print the total number of elements in the list using count () function

STEP 11: Stop.

32
OUTPUT:
library = ['books', 'magazines', 'documents', 'e-books']

first element = books

Third element = documents

All Items in library= ['books', 'magazines', 'documents']

-4th element = books

library list after append: ['books', 'magazines', 'documents', 'e-books', 'musical books']

index of 'magazines': 1

after sorting: ['books', 'documents', 'e-books', 'magazines', 'musical books']

popped elements is: musical books

after pop: ['books', 'documents', 'e-books', 'magazines']

after removing '\e-books': ['books', 'documents', 'magazines']

number of elements in library list = 1

33
PROGRAM:

library=['books','magazines','documents','e-books']
print("library = ", library)
print("first element = ", library[0])
print("Third element = ", library[2])
print("All Items in library= ", library[0:3])
print("-4th element = ", library[-4])
library.append('musical books')
print("library list after append: ", library)
print("index of \'magazines': ", library.index('magazines'))
library.sort()
print("after sorting: ",library)
print('popped elements is: ',library.pop())
print("after pop: ",library)
library.remove('e-books')
print("after removing '\e-books': ",library)
library.insert(2,'CDs')
print('number of elements in library list =',library.count('documents'))

RESULT:
Thus, the python program to verify the operations in the list is executed and the output
is obtained.
34
EX.NO: 4. b
OPERATIONS OF TUPLES

AIM:

To implement Tuple Operations in a Car Tuple.

ALGORITHM:

STEP 1: Start.

STEP 2: Declare a tuple variable named car and assign values to the Tuple.

STEP 3: Print all the elements in the Tuple.

STEP 4: Print random position values in the Tuple.

STEP 5: Print the index value in the Tuple.

STEP 6: Print the index value in the Tuple using index () function.

STEP 7: Print the total number of elements in the Tuple using count () function.

STEP 8: Print the length of elements in the Tuple using len () function.

STEP 9: Stop.

35
OUTPUT:
Components of a car: ('engine', 'battery', 'alternator', 'radiator', 'steering', 'break', 'seat belt')

first element = engine

Third element = alternator

Components of a car from 0 to 4 index= ('engine', 'battery', 'alternator', 'radiator')

-7th element: engine

index of 'radiator': 3

Total number of elements in a car Tuple: 1

length of elements in a car Tuple: 9

36
PROGRAM:

car=('engine','battery','alternator','radiator','steering','break','seat belt')
print("Components of a car: ", car)
print("first element = ", car[0])
print("Third element = ", car[2])
print("Components of a car from 0 to 4 index= ", car[0:4])
print("-7th element : ", car[-7])
print("index of \'radiator': ", car.index('radiator'))
print('Total number of elements in a car Tuple: ',car.count('steering'))
print("length of elements in a car Tuple: ", len('seat belt'))

RESULT:
Thus, the python program to verify the operations in the Tuples is executed and the
Output is obtained.
37
EX.NO: 5. a
OPERATIONS OF SETS

AIM:

To implement Operations in a set using components of a Language as an example.

ALGORITHM:

STEP 1: Start.

STEP 2: Declare a set variables named L1, L2 and assign values to the variables of the set.

STEP 3: Print Union of L1 and L2.

STEP 4: Print Intersection of L1 and L2.

STEP 5: Print Difference of L1 and L2.

STEP 6: Print Symmetric Difference of L1 and L2.

STEP 7: Stop.

38
OUTPUT:

union of L1 and L2 is: {'Phonetics', 'context', 'pitch', 'syllabus', 'grammar', 'Words',


'sentences', 'scripts'}
Intersection of L1 and L2 is: {'syllabus', 'grammar'}
Difference of L1 and L2 is: {'sentences', 'pitch', 'scripts'}
Symmetric Difference of L1 and L2 is: {'Phonetics', 'context', 'pitch', 'sentences', 'Words',
'scripts'}

39
PROGRAM:

L1={'pitch','syllabus','scripts','grammar','sentences'}
L2={'grammar','syllabus','context','Words','Phonetics'}
print("union of L1 and L2 is: ", L1 | L2)
print("Intersection of L1 and L2 is: ",L1&L2 )
print("Difference of L1 and L2 is: ", L1-L2)
print("Symmetric Difference of L1 and L2 is: ", L1^L2)

RESULT:
Thus, the python program to verify the operations in the Sets is executed and the
output is obtained.
40
EX.NO: 5. b
OPERATIONS OF DICTIONARIES

AIM:

To implement Operations in a Dictionaries using elements of a civil structure as an


example.

ALGORITHM:

STEP 1: Start.

STEP 2: Declare a Dictionary variable named thisdict and assign values to the variable.

STEP 3: Print all the values in thisdict.

STEP 4: Print the index value of element in the dictionary.

STEP 5: Print the length of the dictionary values.

STEP 6: Print the data type of particular element.

STEP 7: Print the key value using array and using get() function.

STEP 8: Print the element values in the dictionary.

STEP 9: Stop.

41
OUTPUT:

{'brand': 'Ford', 'year': 1964, 'model': 'Mustang'}


Ford
{'brand': 'Ford', 'year': 2020, 'model': 'Mustang'}
3
<class 'dict'>
dict_keys(['brand', 'year', 'model'])
dict_values(['Ford', 1964, 'Mustang'])

42
PROGRAM:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }


print(thisdict)
print(thisdict["brand"])
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020 }
print(thisdict)
print(len(thisdict))
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
print(type(thisdict))
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
x = thisdict["model"]
x = thisdict.keys()
print(x)
x = thisdict.values()
print(x)

RESULT:
Thus, the python program to verify the operations in the Dictionaries is executed and
the output is obtained.

43
EX.NO: 6. a
FACTORIAL OF A NUMBER USING FUNCTION

AIM:

To write a python program to find the factorial of a number using functions.

ALGORITHM:

STEP 1: Start.

STEP 2: Declare a function fact with the parameter ‘n’ as fact(n).

STEP 3: check if(n==1) return n value or return n* fact(n-1)

STEP 4: Read the data into variable num.

STEP 5: Print fact(num).

STEP 6: Stop.

44
OUTPUT:
Enter a number 5
The factorial of 5 is 120

45
PROGRAM:

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

RESULT:
Thus, the python program to find the factorial of a number using function is executed
and the output is obtained.
46
EX.NO: 6. b
FINDING LARGEST NUMBER IN A LIST USING FUNCTION

AIM:

To write a python program to find the largest number in a list using functions.

ALGORITHM:

STEP 1: Start.

STEP 2: Define a function ‘mymax’ with the parameter ‘list1’ as mymax(list1).

STEP 3: Assign empty array values to the variable list1.

STEP 4: Read the set of values into variable ‘elements ‘using FOR loop.

STEP 5: Add values to the list1 using append() function.

STEP 6: Print the maximum value of the list using max() function.

STEP 7: Stop.

47
OUTPUT:
Enter number of Elements in list: 3
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Largest element is: 3

48
PROGRAM:

def myMax(list1):
print("Largest element is : ",max(list1))
list1=[]
num=int(input("Enter number of Elements in list: "))
for i in range(0,num):
element=int(input("Enter the elements: "))
list1.append(element)
print("Largest element in the list is", myMax(list1))

RESULT:
Thus, the python program to find the largest number in a list using functions is
executed and the output is obtained.
49
EX.NO: 6. c
FINDING AREA OF A CIRCLE USING FUNCTION

AIM:

To write a python program to find the area of a circle using functions.

ALGORITHM:

STEP 1: Start.

STEP 2: Define a function ‘findarea’ with the parameter ‘r’ as findarea (r).

STEP 3: Assign the value of 3.142 to PI.

STEP 4: Calculate the value PI*(r*r)

STEP 5: Read the input value into num.

STEP 6: Print the area of circle by calling the function findarea (num).

STEP 7: Stop.

50
OUTPUT:
enter the r value7
Area is 153.958

51
PROGRAM:

def findarea(r):
PI=3.142
return PI*(r*r)

num=float(input("enter the r value"))


print("Area is " ,findarea(num))

RESULT:
Thus, the python program for finding the area of a circle using functions is executed
and the output is obtained.
52
EX.NO: 7. a
REVERSING A STRING

AIM:

To write a python program to reverse a string.

ALGORITHM:

STEP 1: Start.

STEP 2: Define a function ‘reverse’ with the parameter ‘string’ as reverse (string).

STEP 3: Read the input string into s.

STEP 4: Call the functionreverse (s).

STEP 5: Reverse the string using the function reversed ().

STEP 6: Print the original string and reversed string.

STEP 7: Stop.

53
OUTPUT:
Enter any string: Tendulkar
The original String is: Tendulkar
The reversed string (using reversed) is: rakludneT

54
PROGRAM:

def reverse(string):
string="".join(reversed(string))
return string
s=input("Enter any string: ")
print("The original String is: ",end=" ")
print(s)
print("The reversed string(using reversed)is: ",end= " ")
print(reverse(s))

RESULT:
Thus, the python program to reverse a string using reverse function is executed and
the output is obtained.
55
EX.NO: 7. b
CHECKING PALINDROME IN A STRING

AIM:

To write a python program to check palindrome in a string.

ALGORITHM:
STEP 1: Start.
STEP 2: Read the input string into string.
STEP 3: Call the functionreverse (s).
STEP 4: Reverse the string using the function reversed () and assign the value to
rev_string.
STEP 5: Compare string and rev_string.
STEP 6: If both strings are equal print palindrome or print not palindrome.
STEP 7: Stop.

56
OUTPUT:
Enter a string: madam
It is Palindrome

Enter a string: noorjahan


It is not a Palindrome

57
PROGRAM:

string=input("Enter a string: ")


string = string.casefold()
rev_string=reversed(string)
if list(string)==list(rev_string):
print("It is Palindrome")
else:
print("It is not a Palindrome")

RESULT:
Thus, the python program to find the given string is palindrome or not is executed
and the output is obtained.
58
EX.NO: 7. c
COUNTING CHARACTERS IN A STRING

AIM:

To write a python program to count number of characters in a string.

ALGORITHM:

STEP 1: Start.

STEP 2: Read the input string into string.

STEP 3: Read the input character included in the string into char.

STEP 4: Calculate the number of character in a string using count() function and store into
val.

STEP 5: Print the val.

STEP 6: Stop.

59
OUTPUT:
Enter any string: computer
Enter a character to count: r
1

60
PROGRAM:

string= input("Enter any string: ")


char = input("Enter a character to count: ")
val = string.count(char)
print(val,"\n")

RESULT:
Thus, the python program to count the number of characters from the given string is
executed and the output is obtained.
61
EX.NO: 7. d
REPLACE CHARACTERS IN A STRING

AIM:

To write a python program to replace characters in a string.

ALGORITHM:

STEP 1: Start.

STEP 2: Read the input string into string.

STEP 3: Read the old and new input strings into str1 and str2.

STEP 4: Replace strings str1 and str2 using replace () function.

STEP 5: Print the replaced string value.

STEP 6: Stop.

62
OUTPUT:
Enter any string: heat and mass transfer
Enter old string: mass
Enter new string: volume
heat and volume transfer

63
PROGRAM:

string=input("Enter any string: ")


str1=input("Enter old string: ")
str2=input("Enter new string: ")
print(string.replace(str1,str2))

RESULT:
Thus, the python program to replace the characters from the given string is executed
and the output is obtained.
64
INSTALLING AND EXECUTING PYTHON PROGRAM IN ANACONDA
NAVIGATOR

(To run pandas, numpy, matplotlib, scipy)

STEP 1: Install anaconda individual edition for windows.


STEP 2: Open anaconda navigator.

STEP 3: Launch Jupyter note book.

65
STEP 4: Click new python3.

66
STEP 5: Write or paste the python code.

STEP 6: Click run.

67
EX.NO: 8. a COMPARE THE ELEMENTS OF TWO PANDAS SERIES USING PANDAS
LIBRARY

AIM:

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

ALGORITHM:

STEP 1: Start.

STEP 2: Import pandas module.

STEP 3: Assign Series values into ds1 and ds2.

STEP 4: Print Series values ds1 and ds2.

STEP 5: Print the equal value, less than value and greater than value in the series by
comparison.

STEP 6: Stop.

68
OUTPUT:
series1:
0 2
1 4
2 6
3 8
4 10
dtype: int64
series2:
0 1
1 3
2 5
3 7
4 10
dtype: int64
Compare the elements of the series s1 and s2
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

69
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 series s1 and s2")
print("Equals: ")
print(ds1==ds2)
print("Greater than: ")
print(ds1>ds2)
print("Less than: ")
print(ds1<ds2)

RESULT:
Thus, the python program to compare the elements of two pandas series using pandas
library is executed and the output is obtained.
70
EX.NO: 8. b PROGRAM TO TEST WHETHER NONE OF THE ELEMENTS OF A
GIVEN ARRAY IS ZERO USING NUMPY LIBRARY

AIM:

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

ALGORITHM:

STEP 1: Start.

STEP 2: Import numpy module.

STEP 3: Assign non zero values in the array using numpy object into x.

STEP 4: Print the array values.

STEP 5: Assign including zero value in the array using numpy object into x.

STEP 6: Print the array values.

STEP 7: Stop.

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

72
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 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 array is zero: ")
print(np.all(x))

RESULT:

Thus, the python program to test whether none of the elements of a given array is
zero using numpy library is executed and the output is obtained.

73
EX.NO: 8. c
PROGRAM TO PLOT A GRAPH USING MATPLOTLIB LIBRARY

AIM:

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

ALGORITHM:

STEP 1: Start.

STEP 2: Import numpy module.

STEP 3: Assign non zero values in the array using numpy object into x.

STEP 4: Print the array values.

STEP 5: Assign including zero value in the array using numpy object into x.

STEP 6: Print the array values.

STEP 7: Stop.

74
OUTPUT:

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

RESULT:

Thus, the python program to plot a graph using matplotlib library is executed and the output
is obtained.

76
EX.NO: 8. d PYTHON PROGRAM TO RETURN THE SPECIFIED UNIT IN SECONDS
USING SCIPY LIBRARY

AIM:

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

ALGORITHM:

STEP 1: Start.

STEP 2: Import constant from scipy module.

STEP 3:print minute, hour, day, week, year, Julian year using constants.

STEP 4: Stop.

77
OUTPUT:
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0

78
PROGRAM:

from scipy import constants


print(constants.minute)
print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)
print(constants.Julian_year)

RESULT:

Thus, the python program to return the specified unit in seconds using scipy library is
executed and the output is obtained.

79
EX.NO: 9. a
COPY FROM ONE FILE TO ANOTHER

AIM:

To write a python program to copy from one file to another using shutil.

ALGORITHM:

STEP 1: Start.

STEP 2: Import copyfile from shutil module.

STEP 3: Read input from source file and destination file.

STEP 4: Copy the contents from source to destination using copyfile () function.

STEP 5: Print the result.

STEP 6: Stop.

80
OUTPUT:
Enter source file name: nandha.txt

Enter destination file name: deva.txt

File copied successfully!

where are you

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

RESULT:

Thus, the python program to copy from one file to another using shutil is executed and the
output is obtained.

82
EX.NO: 9. b
WORD COUNT FROM A FILE

AIM:

To write a python program to count number of words in a file.

ALGORITHM:

STEP 1: Start.

STEP 2: Open a file.

STEP 3: Read input from the file to data.

STEP 4: Calculate the words using split() function into words.

STEP 5: Print the total number of words in the file.

STEP 6: Stop.

83
OUTPUT:
Number of words in text file is: 30

84
PROGRAM:

file=open("d:\data.txt")
data=file.read()
words=data.split()
print("Number of words in text file is: ",len(words))

RESULT:

Thus, the python program to count number of words in a file is executed and the output is
obtained.

85
EX.NO: 9. c
FINDING LONGEST WORD IN A FILE

AIM:

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

ALGORITHM:

STEP 1: Start.

STEP 2: Open a file.

STEP 3: Read input from the file to words using split() function.

STEP 4: Calculate the maximum length of words using len() function and max() function.

STEP 5: Print the longest word in the file.

STEP 6: Stop.

86
OUTPUT:
Longest_word: [‘hippopotamus’]

87
PROGRAM:

def longest_word(filename):
with open(filename,'r')asinfile:
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("d:\deva.txt"))

RESULT:

Thus, the python program to find longest word in a file is executed and the output is
obtained.

88
EX.NO: 10. a
A DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING

AIM:

To write a python program to handle divide by zero error using exception handling.

ALGORITHM:

STEP 1: Start.

STEP 2: Read input values into n, d, c.

STEP 3: Calculate q=n/(d-c) in try block.

STEP 4: Print the value of q

STEP 5: If there is zero division error handle it in exception block.

STEP 6: Stop.

89
OUTPUT:
Enter the value of n: 2
Enter the value of d: 4
Enter the value of c: 5
quotient: -2.0

Enter the value of n: 4


Enter the value of d: 2
Enter the value of c: 2
Division by Zero error spotified!

90
PROGRAM:

n=int(input("Enter the value of n: "))


d=int(input("Enter the value of d: "))
c=int(input("Enter the value of c: "))
try:
q=n/(d-c)
print("quotient:",q)
except ZeroDivisionError:
print("Division by Zero error spotified! ")

RESULT:

Thus, the python program to check voter’s age validity is executed and the output is
obtained.

91
EX.NO: 10. b
VOTERS AGE VALIDITY

AIM:

To write a python program to check voter’s age validity.

ALGORITHM:

STEP 1: Start.

STEP 2: Import datetime module.

STEP 3: Read input value into Year_of_Birth.

STEP 4: Calculate the age using current year.

STEP 5: Check with the condition that age is less than or equal to 18.

STEP 6: Print whether eligible to vote or not.

STEP 7: Stop.

92
OUTPUT:
In which year u took birth: 1996
Your current age is: 25
You are eligible to vote.

93
PROGRAM:

import datetime
year_of_birth=int(input("In which year u took birth..."))
current_year=datetime.datetime.now().year
current_age=current_year-year_of_birth
print("Your current age is: ",current_age)

if(current_age<=18):
print("you are not eligible to vote. ")
else:
print("you are eligible to vote. ")

RESULT:

Thus, the python program to check voter’s age validity is executed and the output is
obtained.

94
EX.NO: 10. c
STUDENT MARK RANGE VALIDATION

AIM:

To write a python program to perform Student mark range validation.

ALGORITHM:

STEP 1: Start.

STEP 2: Read the mark as input value.

STEP 3: Check the input value is less than 0 or greater than hundred.

STEP 4: Print the result whether the mark is in range or not.

STEP 5: Stop.

95
OUTPUT:
Enter the mark95
The mark is in the range...

Enter the mark


123
The value is out of range,try again...

96
PROGRAM:

mark=int(input("Enter the mark"))


if mark<0 or mark>100:
print("The value is out of range,try again...")
else:
print("The mark is in the range...")

RESULT:

Thus, the python program to perform Student mark range validation is executed and the
output is obtained.

97
EX.NO: 11
EXPLORING PYGAME

AIM:

To Install Pygame Module.

STEPS:
1. Install python 3.6.2 into C:\

2. Go to this link to install Pygame

https://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

6. Type the following command

C:\>py –m pip install pygame –user

98
Collecting Pygame

Downloading Pygame -1.9.3-cp36m-win32.whl (4.0 MB)

Installing collected packages: Pygame

Successfully installed Pygame-1.9.3

7. Now Pygame installed successfully

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\Scriptspygame-1.9.3

C:\>cd Python36-32\Scriptspygame-1.9.3>cd examples

C:\>cd Python36-32\Scriptspygame-1.9.3\cd examples>bouncingball.py

RESULT:
Thus, Pygame module is installed and verified.

99
EX.NO: 12
SIMULATE BOUNCING BALL USING PYGAME

AIM:

To write a python program for bouncing ball in pygame.

ALGORITHM:

STEP 1: Start

STEP 2: Number of frames per second.

STEP 3: Change this value to speed up or slow down your game.

STEP 4: Global values to be used through the program.

STEP 5: Set up the colors.

STEP 6: Draw the arena the game will be played in.

STEP 7: Draw outline of arena and center line.

STEP 8: Draw the paddle and stop the paddle moving too low.

STEP 9: Draw and move the ball and returns new position.

STEP 10: Checks for collision with the wall, and ‘bounces’ ball off it and returns new

Direction.

STEP 11: Initiate variable and set starting positions and any future changes made within

Rectangles.

STEP 12: Create rectangles for ball and paddles.

STEP 13: Draws the starting position of the arena and make cursor invisible.

STEP 14: Mouse movement commands are produced.

STEP 15: Stop.


100
OUTPUT:

101
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:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()

RESULT:

Thus, the python program for bouncing ball in Pygame is executed and the output is
obtained.

102

You might also like