0% found this document useful (0 votes)
80 views54 pages

Ge3151 Lab Manual

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)
80 views54 pages

Ge3151 Lab Manual

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/ 54

Total

Average

4
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,
1.
c) Sin Series,
d) Weight of a Motorbike,
e) Weight of a Steel Bar,
f) Compute Electrical Current in Three Phase AC Circuit.
Programs Using Simple Statements

2. a) Exchange the values of two variables,


b) Circulate the values of n variables,
c) Distance between two points.
Programs Using Conditionals and Iterative Statements
3. a) Number Series
b) Number Patterns
c) Pyramid Pattern

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


4. Materials required for construction of a building)
b) Operations of Lists and Tuples (Items present in a library/Components
of acar/ Materials required for construction of a building)
a) Operations of Sets (Language, components of an automobile, Elements of
5. a civil structure, etc.)
b) Operations of Dictionaries (Language, components of an automobile,
Elements of a civil structure, etc.)
Programs Using Functions
6. a) Factorial of a Number
b) Largest Number in a list
c) Area of Shape
Programs using Strings.

7. a) Reversing a String,
b) Checking Palindrome in a String,
c) Counting Characters in a String
d) Replacing Characters in a String

5
Programs Using modules and Python Standard Libraries
a) Pandas
8. b) Numpy
c) Matplotlib
d) Scipy
Programs using File Handling.

9. a) Copy from one file to another,


b) Word count
c) Longest word
Programs Using Exception handling.
10. a) Divide by zero error
b) Voter’s age validity
c) Student mark range validation
11.
Exploring Pygame tool.

12. Developing a game activity using Pygame like bouncing ball.

6
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 Calculate amt =0. Then go to step7.

Step4: Check n<=200 is yes, 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.

7
Flowchart:

Start

Read units

<=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 = (100*0)+
(unit-100)*1.5 (200-100)*2+ (unit-200)*3

Print Amount

Stop

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

8
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: Compute the Tax=0.18 and read 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.

9
Flowchart:

Start

Tax=0.18

Rate_ of_ item

Display Quantities

Rated 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.

10
Ex.No 1.C
Developing flow charts for Sine Series
Date:

Aim:
To write a algorithm and draw flowchart for sine series.

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: Check the condition 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.

11
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.

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

Aim:
To write a algorithm and draw flowchart for Weight of a Motorbike.

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.

13
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.
14
Ex.No 1.E
Developing flow charts for Weight of a Steel Bar
Date:

Aim:
To write a algorithm and draw flowchart for Weight of a Steel Bar.

Algorithm:

Step1: Start the program.

Step2: Get the input l and r.

Step3: Compute 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.

15
Flowchart:

Star

Input l

den =7800

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

Print

sto

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

16
Ex. No 1.F

Developing flow charts for Electrical Current in Three Phase AC


Date: Circuit.

Aim:
To write a algorithm and draw flowchart for Electric Current in Three Phase AC Circuit.

Algorithm:
Step1: Start the program.

Step2: Compute Total VA

Step3: Calculate Aline using the formula, Aline=Total VA/ (√3*Vline)


Step4: Print Aline

Step5: Stop the program

17
Flowchart:

Start

Read Total VA

Aline=Total VA/ (√3*Vline)

Print Aline

Stop

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

18
Ex. No 2.A

Date: Exchange the values of two variables using Simple Statements

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 successfully and output was verified.

19
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+1):
c=L[i:]+L[:i]
print(“circulation”,i”=”,c)

Output:
Enter n : 5
Circulating the elements of list[ 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 given program successfully executed and practically verified.

20
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-y1)**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 given program successfully executed and practically verified.

21
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 go to next step 5 else goto step 7.
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.
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 given program successfully executed and practically verified.

22
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 given program successfully executed and practically verified.
23
Ex. No 3.C
Programs Using Conditionals and Iterative Statements Pyramid
Date: Pattern

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

24
Output:
enter the value:5
*
**
***
****
*****
*
**
***
****
*****
*****
****
***
**
*
*****
****
***
**
*

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

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

Aim:
To implement operations in a library list.

Algorithm:
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 slicing 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 Elements 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])
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 : ',library.count('Ebooks'))

26
Output:

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

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 :1

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

27
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 Elements in Car Tuple : ',car.count('Seat Belt'))
#Length of car tuple
print(' Length of Elements in Car Tuple : ',len(car))
28
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 Elements in Car Tuple :1
Length of Elements in Car Tuple :7

Result:
Thus, the given program successfully executed and practically verified.
29
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'}; print("Union of S1 and S2 is ",S1 | S2) # set

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

intersection print("Difference of S1 and S2 is",S1 - S2) #

set difference

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

30
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 given program successfully executed and practically verified.

31
Ex. No 5.B
Operations of Dictionaries
Date:

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

Algorithm:
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 given program successfully executed and practically verified.


32
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 given program successfully executed and practically verified.

33
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
87

Result:
Thus, the given program successfully executed and practically verified.
34
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():

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

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

36
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 given program successfully executed and practically verified.

37
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 given program successfully executed and practically verified.

38
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.

Step4: 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 given program successfully executed and practically verified.

39
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 given program successfully executed and practically verified.
40
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.

Step4: 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

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

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

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)

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

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
43
Ex. No 8.B
To Test whether None of the Elements of a Given Array is
Date: 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:
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.
44
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.
45
Ex. No 8.D
To Return the Specified Unit in Seconds Using Scipy
Date: Library

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.

46
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- Get the source and destination file name as input.
Step-3- Read the source file using read
Step-4- Write on 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:
sfn = input("Enter source file name: ")
dfn = input("Enter destination file name: ") sf
= open(sfn, "r")
df = open(dfn, "w")
str = sf.read()
df.write(str)
print("File copied successfully!")
sf.close()
df.close()
sf2 = open(dfn, "r")
str2 = sf2.read()
print(str2)
sf2.close()

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.
47
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.

48
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()
maxword = max(words, key=len)
return maxword
print( longest_word ('ex9a.py'))

Output:
['collection']

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

49
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

except ValueError as e:
print("invalid input")
except ZeroDivisionError as e:
print(e)
else:
print(result)
Output:
enter first number: 33
enter second number:23
1.434782608695652

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

50
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("an error occured : ",err)

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.

51
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.
52
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
53
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>

54
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 background 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 quits the program
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]
55
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
ball.jpg

56
Output:

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

57

You might also like