GE3171_PSPP_LAB_Manual
GE3171_PSPP_LAB_Manual
A
ELECTRICITY BILLING
Date:
Aim:
To draw a Flowchart for calculating Electricity Bill.
Algorithm:
1. Read the number units consumed as units
2. For 0 to 100 units the per unit is ₹ 0/-
3. For 0 to 200 units, for the first 100 unit the per unit cost is zero and the next
100 units, the consumer shall pay ₹ 1.5 per unit.
4. For 0 to 500 units, the consumer shall pay ₹ 0 for the first 100 units, for the
next 100 units the consumer shall pay ₹ 2 per unit, for the next 300 units the
unit cost is ₹3.00/-
5. For above 500 units, the consumer shall pay ₹ 0 for the first 100 units, for
the next 100 units the consumer shall pay ₹ 3.50 per unit, for the next 300
units the unit cost is ₹4.60/- and for the remaining units the unit cost is
₹6.60/-
6. Calculate amount as per step 2 to step 6
7. Display the total amount as amount
Flowchart:
Result:
Flowchart for Electricity Bill Calculation has been drawn and verified.
Ex. No.: 1.B
ARITHMATIC OPEARTION
Date:
Aim:
To draw a Flowchart for finding addition of two numbers
Algorithm:
1.start the algorithm
2.Read the inputs number1,number2
3.Calculate sum as addition of number1 and number2
4.Display the result sum
5.End the algorithm
Flow chart
Result:
Flowchart for finding addition of two numbers has been drawn and verified.
Ex. No.: 1.C
RETAIL SHOP BILLING
Date:
Aim:
To draw a Flowchart for Retail Shop Billing.
Algorithm:
1.Start the algorithm
2.Assign tax as 0.18
3.Display the available items
4.Read rate of item , quantity purchased
5.Calculate cost as sum of rate of item multiplying with quantity
6.Calculatebill amount as sum of cost with (cost * tax)
7.Display bill amount
8.Stop the algorithm
Flowchart
Start
Tax=0.28
Display
Items,Rate_of_ite
Read Quantity
Stop
Result:
Flowchart for Retail shop Billing has been drawn and verified.
Ex. No.: 1.D
WEIGHT OF A STEEL BAR
Date:
Aim:
To draw a Flowchart for calculating the weight of a Steel Bar.
Algorithm:
1.start the algorithm
2.Read the input as diameter D of the steel bar
3.Claculate weight w as (D*D) divided by 162
4.Print the result w
5.stop the algorithm
Flowchart:
Result:
Flowchart for calculating weight of a steel bar has been drawn and verified.
Ex. No.: 1.E
SINE SERIES
Date:
Aim:
To draw a Flowchart for evaluating sine series.
Flowchart:
Start
Read x, n
x = x * 3.14/ 180
t=x
sum = x
t =(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
Stop
Result:
Flowchart for Sine series has been drawn and verified.
Ex. No.: 1.F
COMPUTE ELECTRICAL CURRENT IN THREE
PHASE AC CIRCUIT
Date:
Aim:
To draw a Flowchart for calculating the electrical current in three phase AC
circuit.
Flowchart:
Result:
Flowchart for calculating the electrical current in three phase AC circuit has
been drawn and verified.
Ex. No.: 2.A
EXCHANGING THE VALUES OF TWO VARIABLES
Date:
Aim:
To write a python program to exchange the values of two variables.
Algorithm:
1.Read two numbers x,y
2.Displayx,y before swapping
3.Assign x value to z
4.Assign y to x
5.Assign z to y
6.Display x, y after swapping
7.stop the algorithm
Program:
# swapping of 2 numbers
x=int(input("Enter x"))
y=int(input("Enter y"))
print("Before swapping")
print("x=",x,”y=”,y)
z=x
x=y
y=z
print("after swapping")
print("x=",x)
print("y=",y)
Output:
Enter value of x: 67
Enter value of y: 56
Before swapping
x = 67
Y= 56
After swapping
x = 56
Y= 67
Result:
Thus the Python program for exchanging the values among two variables
has been done and the output is verified successfully.
Ex. No.: 2.B
CIRCULATING THE VALUES OF N VARIABLES
Date:
Aim:
To write a python program to circulate the values of ‘n’ variables.
Algorithm:
Step 1: Define a List named a.
Step 2: Get the input n value to rotate the values.
Step 3: Define the function circulate with 2 arguments List and number of
times to circulate
Step 3.1 Perform the following step till b=a[n:]+a[:n],using slice
operator
Step 4: Print the rotated List
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]
print(“Given List is “,A)
N=int(input("Enter n:"))
circulate(A,N)
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]
Result:
Thus the Python program for circulating the values of ‘n’ variables has been
done and the output is verified successfully.
Ex. No.: 2.C
DISTANCE BETWEEN TWO POINTS
Date:
Aim:
To write a python program to find the distance between two points.
Algorithm:
Step 1: Read the value of point 1 coordinates x1,y1
Step 2: Read the value of point 2 coordinates x2,y2
Step 3: Calculate the difference between the corresponding X-coordinates
x2-x1 and Y coordinates i. y2-y1 of two points
Step 4 :Calculate the distance between two point as D using the formula
D=((x2-x1)^2 +(y2-y1)^2)^1/2
Step 5: Print the result D
Step 5: Stop
Program:
import math
x1 = int(input("Enter x1: "))
y1 = int(input("Enter y1: "))
x2 = int(input("Enter x2: "))
y2 = int(input("Enter y2: "))
D = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = ",D)
Output:
Enter x1: 3
Enter y1: 2
Enter x2: 7
Enter y2: 8
Distance = 7.211102550927978
Result:
Thus the Python program for computing the distance between 2 points has
been done and the output is verified successfully.
Ex. No.: 3.A
FIBONACCI NUMBER SERIES
Date:
Aim:
To write a python program to display the Fibonacci Number Series as
1,1,2,3,5,8….
Algorithm:
1. Assign first number in the Fibonacci series as f1=1
2. Assign second number in the Fibonacci series as f2=1
3.Read the limit of the Fibonacci series
4.Display first two numbers in the series
5.Repeat for loop I ranging from 3 to n+1
5.1 calculate f3 as f1+f2
5.2 Display third number in the series f3
5.3 assign f1as f2
5.5 assign f2 as f3
6.Stop
Program:
#fibonacci number series
f1=1
f2=1
n=int(input("Enter the limit in the series:\t"))
print(f1)
print(f2)
for i in range(3,n+1):
f3=f1+f2
print(f3)
f1=f2
f2=f3
Output:
Enter the limit in the series6
1
1
2
3
5
8
>
Result:
Thus the Python program to program to display the Fibonacci Number Series as
1,1,2,3,5,8…. Has been done and output is verified
Ex. No.: 3.B
NUMBER PATTERN
Date:
Aim:
To write a python program to display the number pattern.
1) 1
1 2
1 2 3
1 2 3 4
2) 1
2 2
3 3 3
4 4 4 4
Algorithm 1:
1.Initialize depth as 6
2.Repeat for number ranging upto depth
2.1 Repeat i ranging up to number
2.1.1 Display the value of number
2.2 Display “ “
3.stop
Algorithm 2:
1.Initialize depth as 6
2.Repeat for number ranging upto depth
2.1 Repeat i ranging from 1 to number+1
2.1.1 Display the value of i
2.2 Display “ “
3.stop
Program 1:
depth=5
for number in range(depth):
for i in range(1,number+1):
print(i,end=" ")
print(" ")
Program 2:
depth=5
for number in range(depth):
for i in range(number):
print(number,end=" ")
print(" ")
Output 1:
1
12
123
1234
Output 2:
1
22
333
4444
Result:
Thus the Python program to display given Number Pattern has been done and the
output is verified successfully.
Ex. No.: 3.C
STAR PATTERN
Date:
Aim:
To write a python program to display the star pattern.
Algorithm:
1.Initialize n as 5
2.Repeat for m ranging from 0 to n
2.1 Repeat i ranging from 0 to m+1
2.1.1 Display the symbol *
2.2 Display “ “
3.stop
Program:
n=5
for m in range(0,n):
for i in range(0,m+1):
print("*",end=" ")
print(" ")
Output:
*
**
***
****
*****
Result:
Thus the Python program to display given star Pattern has been done and the
output is verified successfully.
Ex. No.: 4 A
OPERATIONS OF LIST
Date:
Aim:
To write a python program to create library data list and implement list operations
in it
Algorithm:
1. Declaring a list of items in a Library
2. printing the complete list
3. printing first element from the library
4. printing fourth element from the library
5. printing list elements from 0th index to 4th index
6. printing list -7th or 3rd element from the list
7. appending an element to the list & print the list after append
8. sorting the elements of List
9.popping an element from a list
10. removing specified element from a list
11. inserting element at 2nd index of the list
12. counting Number of “ebooks” Elements in Library list
Program:
# declaring a list of items in a Library
library =
['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks
']
# printing the complete list
print('Library: ',library)
# printing first element
print('first element: ',library[0])
# printing fourth element
print('fourth element: ',library[3])
# printing list elements from 0th index to 4th index
print('Items in Library from 0 to 4 index: ',library[0: 5])
# printing list -7th or 3rd element from the list
print('3rd or -7th element: ',library[-7])
# appending an element to the list
library.append('Audiobooks')
print('Library list after append(): ',library)
# finding index of a specified element
print('index of \'Newspaper\': ',library.index('Newspaper'))
# sorting the elements of iLIst
library.sort()
print('after sorting: ', library);
# popping an element
print('Popped elements is: ',library.pop())
print('after pop(): ', library);
# removing specified element
library.remove('Maps')
print('after removing \'Maps\': ',library)
# inserting an element at specified index
# inserting 100 at 2nd index
library.insert(2, 'CDs')
print('after insert: ', library)
# Number of Ekements in Library list
print(' Number of Elements in Library list : ',library.count('Ebooks'))
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 Python program to create library data list and implement list operations in
a list has been done and the output is verified successfully.
Ex. No.: 4 B
OPERATIONS OF TUPLE
Date:
Aim:
To write a python program to implement operations in a tuple for car details.
Algorithm:
1. Declaring a tuple of Components of a car
2. printing the complete tuple
3. printing first element
4. printing fourth element
5. printing tuple elements from 0th index to 4th index
6. printing tuple -7th or 3rd element from the list
7. Finding index of a specified element
8. Find Number of Elements in car tuple
9. Display car tuple
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))
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 Python program to implement operations in a list has been done and the
output is verified successfully.
Ex. No.: 5 A
OPERATIONS OF SETS
Date:
Aim:
To write a python program to implement operations in a sets.
Algorithm:
1. Create a set L1
2. Create a set L2
3. Display union of L1 , L2
4. Display intersection of L1 and L2
5. Display difference between L1,L2
Program:
L1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};
L2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};
# set union
print("Union of L1 and L2 is ",L1 | L2)
# set intersection
print("Intersection of L1 and L2 is ",L1 & L2)
# set difference
print("Difference of L1 and L2 is ",L1 - L2)
# set symmetric difference
print("Symmetric difference of L1 and L2 is ",L1 ^ L2)
Output:
Union of L1 and L2 is {'Words', 'Pitch', 'Sentences', 'Phonetics', 'Script', 'Grammar',
'Syllabus', 'Context'}
Intersection of L1 and L2 is {'Grammar', 'Syllabus'}
Difference of L1 and L2 is {'Script', 'Pitch', 'Sentences'}
Symmetric difference of L1 and L2 is {'Words', 'Context', 'Script', 'Pitch',
'Sentences', 'Phonetics'}
Result:
Thus the Python program to implement operations in a set has been done and the
output is verified successfully.
Ex. No.: 5B
OPERATIONS OF DICTIONARIES
Date:
Aim:
To write a python program to implement operations in a dictionary
Algorithm:
1.Create a dictionary called civil
2.Display the content of the dictionary
3. To display keys in dictionary for repeating i in civil
4. To display values as civil[i] in dictionary for repeating i in civil
5.Stop
Program:
civil={1:'cement',2:'steel',3:'sand'}
print(civil)
print("keys in civil")
for i in civil:
print(i)
print("values in civil")
for i in civil:
print(civil[i])
Output:
{1: 'cement', 2: 'steel', 3: 'sand'}
keys in civil
1
2
3
values in civil
cement
steel
sand
Result:
Thus the Python program to implement operations in a dictionary has been done
and the output is verified successfully.
Ex. No.: 6 A
FACTORIAL OF A NUMBER USING FUNCTION
Date:
Aim:
To write a python program to find the factorial of a number using functions.
Algorithm:
STEP1:Start
STEP2:Read a number num
STEP3: Call the function fact by passing the value of num
STEP 3.1: Check if n is equal to 1 , if true return n, if not goto step 3.2
STEP3.2: return n * fact(n-1)
STEP7:Print he result fact
STEP8:Stop
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))
Output:
Enter a number: 5
The factorial of 5 is 120
Result:
Thus the Python program to implement a factorial of a number using function has
been done and the output is verified successfully.
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 functions.
Algorithm:
Step 1: Create an empty list as list1
Step 2: Read number of elements in a list as num
Step 3: Repeat for i ranging from 1 to num
Step 3.1: Read the element x and append the value of x into list1
Step 4: Call the function Mymax() by passing list1.
Step 4.1 Find maximum in a given list using the built-in function max()
Step 3: Print the maximum number in a list
Step 4: End
Program:
def myMax(list1):
print("Largest element is:", max(list1))
list1 = []
num = int(input("Enter number of elements in list: "))
fori in range(1, num + 1):
x = int(input("Enter elements: "))
list1.append(x)
print("Largest element is:", myMax(list1))
Output:
Enter number of elements in list: 6
Enter elements: 58
Enter elements: 69
Enter elements: 25
Enter elements: 37
Enter elements: 28
Enter elements: 49
Largest element is: 69
Result:
Thus the Python program to implement largest number in a list using function has
been done and the output is verified successfully.
Ex. No.: 6 C
FINDING AREA OF SHAPES USING FUNCTION
Date:
Aim:
To write a python program to find the area of a square , rectangle, triangle
and circle using functions.
Algorithm:
Program:
To Find area of square
#find area of the square
def area_sq(side):
area=side*side
return area
print("To Find area of square")
side=int(input("Enter side of the square:\t"))
print("The area of the square with side ",side, "is", area_sq(side))
def findArea_c(r):
PI = 3.142
return PI * (r*r)
print("To Find area of Circle")
num=float(input("Enter radius:"))
print("Area is %.6f" % findArea_c(num))
# Calculating the area of a triangle using the formula: 0.5 * base * height
def triangle_area(base, height):
return 0.5 * base * height
# Inputting the values of base and height
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
# Printing the result
print("The area of the triangle is", triangle_area(base, height))
Output:
To Find area of square
Enter side of the square: 4
The area of the square with side 4 is 16
Result:
Thus the Python program to implement finding area of a shapes using function has
been done and the output is verified successfully.
Ex. No.: 7 A
REVERSING A STRING
Date:
Aim:
To write a python program to reverse a string.
Algorithm:
STEP1:Start
STEP2:Read the string from the user
STEP3:Calculate the length of the string
STEP4:Initialize rev=””
STEP5:Initialize i=length-1
STEP6:Repeat until i>=0:
rev=rev+character at position “i” of the string
i=i-1
STEP7:Print rev
STEP8:Stop
Program: Method 1
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))
Method 2
def reverse(string):
string = string[::-1] # Using Slicing
return string
s = "Python"
print("The original string is : ", end="")
print(s)
print("The reversed string(using extended slice syntax) is : ", end="")
print(reverse(s))
Output:
Enter any string: Python
The original string is : Python
The reversed string(using reversed) is : nohtyP
Result: Thus the Python program to implement reversing a string has been done
and the output is verified successfully.
Ex. No.: 7 B
CHECKING PALINDROME IN A STRING
Date:
Aim:
To write a python program to check palindrome in a string.
Algorithm:
STEP1: start
STEP2: reading the string fromthe users
STEP3: calculate the lengthof the string
STEP4: initialize rev =””[empty string]
STEP5: initialize i= length -1
STEP6: repeat until i>=0:
6.1: rev = rev + character at position ‘i’ of the string
6.2: i=i-1
STEP7: if string = rev :
7.1: print ”yes”
STEP8: else:
8.1: print:”no”
STEP9: stop
Program:
string = input("Enter string: ")
string = string.casefold()
rev_string = reversed(string)
if list(string) == list(rev_string):
print("It is palindrome")
else:
print("It is not palindrome")
Output:
Enter string: Python
It is not palindrome
Enter string: malayalam
It is palindrome
Result:
Thus the Python program to implement checking palindrome in a string has been
done and the output is verified successfully.
Ex. No.: 7 C
COUNTING CHARACTERS IN A STRING
Date:
Aim:
To write a python program to count number of given character in a string.
Algorithm:
1.Read the input string
2.Read the character to count
3.Use count() & find count of the specified character
4. print the character count
Program:
string = input("Enter any string: ")
char = input("Enter a character to count: ")
val = string.count(char)
print(val,"\n")
Output:
Enter any string: python programming
Enter a character to count: m
2
Result:
Thus the python program to count number of character in a string has been done
and the output is verified successfully.
Ex. No.: 7 D
REPLACE CHARACTERS IN A STRING
Date:
Aim:
To write a python program to replace characters in a string.
Algorithm:
1.Read any input string
2. Read the old string to replace
3. Read a new string to replace the old string
4. Display the replaced string
Program:
string = input("Enter any string: ")
str1 = input("Enter old string: ")
str2 = input("Enter new string: ")
print(string.replace(str1, str2))
Output:
Enter any string: problem solving python programming
Enter old string: python
Enter new string: C
problem solving C programming
Result:
Thus the python program to implement replace characters in a string has been done
and the output is verified successfully.
Ex. No.: 8 A
PANDAS
Date:
Aim:
To write a python program to compare the elements of the two Pandas Series using
Pandas library.
Algorithm:
1.import the module pandas and create alias name as pd
2. Create pandas series ds1 using pandas object pd and . operator by passing
[2,4,6,8,10]
3. Create pandas series ds1 using pandas object pd and . operator by passing
[1,3,5,7,10]
4.Display the series ds1,ds2
5. Check whether the two series are equal and display the result
6. Check whether the first series is greater than series 2 and display the result
7. Check whether the second series is greater than series 2 and display the result
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
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
Result:
Thus the python program to implement Pandas has been done and the output is
verified successfully
Ex. No.: 8 B
NUMPY
Date:
Aim:
To write a program to test whether none of the elements of a given array is zero
using NumPy library.
Algorithm:
1.import the module numpy and create alias name as np
2.create array x from [1,2,3,4] using np.array()
3.Display original array x
4. Test if none of the elements of the said array is zero using np.all()
5.Display the result true if none of the elements of the said array is zero otherwise
false
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))
dtype: bool
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 python program to implement numpy has been done and the output is
verified successfully
Ex. No.: 8 C
MATPLOTLIB
Date:
Aim:
To write a python program to plot a graph using matplotlib library.
Algorithm:
1.Import the module import matplotlib.pyplot as plt
2. import numpy as np
3.Create x array from [0,6]
4.Create y array from [0,250]
5.Draw line from x point to y point using plt.plot()
6. Show plot line in display frame
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 python program to implement matplotlib has been done and the output is
verified successfully.
Ex. No.: 8 D
SCIPY
Date:
Aim:
To write a python program to return the specified unit in seconds (e.g. hour returns
3600.0) using scipy library.
Algorithm:
1.Import constants module from scipy
2.Display the constant value of minute
3. Display the constant value of hour
4. Display the constant value of day
5. Display the constant value of week
6. Display the constant value of year
7. Display the constant value of 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 python program to return the specified unit in seconds (e.g. hour returns
3600.0) using scipy library has been done and the output is verified successfully
Ex. No.: 9 A
COPY FROM ONE FILE TO ANOTHER
Date:
Aim:
To write a python program to copy from one file to another.
Algorithm:
1. from shutil import copyfile
2. Read source file name
3. Read destination file name
4. Call the function copyfile() by passing soursefilename and
destinationfilename
5. Open the destination file in read mode
6. Read the content from the destination file using read()
7. Display the content which has been read from the file
8. Close the file
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()
Input:
file1.txt
Sunflower Jasmine Roses
Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully!
Sunflower
Jasmine
Roses
Result:
Thus the python program to implement copy from one file to anotherhas been done
and the output is verified successfully
Ex. No.: 9 B
WORD COUNT FROM A FILE
Date:
Aim:
To write a python program to count number of words in a file.
Algorithm:
1.Open the file data.txt in read mode using open() method
2.read the content from that input file opened in read mode and store it in the name
data
3.Split the words from the variable data using split() & store it in the variable
words
4. Display the number of words in a file by finding length of the list called words
Program:
file = open("F:\Data.txt", "r")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
Input:
Data.txt
This is my input file for word count program
Output:
Result:
Thus the python program to implement word count from a file has been done and
the output is verified successfully
Ex. No.: 9 C
FINDING LONGEST WORD IN A FILE
Date:
Aim:
To write a python program to find longest word in a file.
Algorithm:
1.Define the function called longest_word(filename)
1.1 Open the file in read mode by creating file object infile
1.2 read the content from that input file opened in read mode and Split the words
from it using
split() & store it in the variable words
1.3 Find length of the word whose length is maximum
1.4 return the longest word by using list comprehension to iterate each word &
check whose
length is maximum
2. Call the function longest_word(filename) to display longest word from the file
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'))
Input:
Data.txt
This is my input file for word count program
Output:
['program']
Result:
Thus the python program to implement finding longest word in a file has been
done and the output is verified successfully
Ex. No.: 10 A
DIVIDE BY ZERO ERROR USING EXCEPTION
HANDLING
Date:
Aim:
To write a python program to handle divide by zero error using exception handling.
Algorithm:
1. Read the input n
2.Read the input d
3.In try: block
3.1 find q as division of n & d
3.2 Print the result q
3.3 if d is zero then exception raised and handled by displaying message as
Division by Zero
4.Stop
Program:
n=int(input("Enter the value of n:"))
d=int(input("Enter the value of d:"))
try:
q=n/d
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")
Output:
Enter the value of n:10
Enter the value of d:0
Division by Zero!
Result:
Thus the python program to implement divide by zero error using exception
handling has been done and the output is verified successfully.
Ex. No.: 10 B
VOTERS AGE VALIDITY
Date:
Aim:
To write a python program to check voter’s age validity.
Algorithm:
1. define the function main()
1.1 In try :
1.2 Read the input voter’s age
1.3 Check if age is greater than 18 , yes then display the result as “ eligible
to vote
1.4 if age is not greater than 18 , then display the result as “ not eligible
to vote
1.5 if 1.3 and 1.4 both condition fails then raise an exception and handle it in
except block
1.5.1 Display Arithmetic Error
1.5.2 Display “ Error occurred and rest of the code
def main():
try:
age=int(input("enter your age"))
if age>18:
print("eligible to vote")
else:
print("not eligible to vote")
#display exception's default error message
except ArithmeticError as err:
print(err)
except:
print("an error occured")
print("rest of the code")
main()
Output:
enter your age 45
eligible to vote
Result:
Thus the python program to implement voter’s age validity has been done and the
output is verified successfully.
Ex. No.: 10 C
STUDENT MARK RANGE VALIDATION
Date:
Aim:
To write a python program to perform student mark range validation.
Algorithm:
1. Define the function main()
1.1 In try : block
1.1.1 Read the student mark
1.1.2 check the mark is in between 35 to 101 , if yes display the result as pass and
valid mark
1.1.3 if mark is not in that above range display the result as fail and your mark is
Valid
1.1.4 if both 1.1.2 and 1.1.3 are fail then raise an exception corresponds to
ValueError ,IOError.
1.1.5 Raise any other kind of general Exception and display the message Error
Occured
2. call the function main()
Program:
#mark validation
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")
#generic except clause, which handles any exception.
except:
print("An Error occurred")
main()
Output:
enter your mark:56
pass and your mark is valid
Result:
Thus the python program to implement student mark range validation has been
done and the output is verified successfully.
Ex. No.: 11
EXPLORING PYGAME
Date:
PYGAME INSTALLATION
To Install Pygame Module
Steps
1. Install python 3.6.2 into C:\
2. Go to this link to install pygamewww.pygame.org/download.shtml
Result:
Thus the python steps to install pygame has been done successfully.
Ex. No.: 12
SIMULATE BOUNCING BALL USING PYGAME
Date:
Aim:
To write a Python program to bouncing ball in Pygame.
Program:
import sys, pygame
pygame.init()
size = width, height = 600,400
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:
for event in pygame.event.get():
ifevent.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
ifballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
ifballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Output:
Result:
Thus the python program to simulate bouncing ball using pygame has been done
and the output is verified successfully.
Ex. No.: 13 A
CLASS AND OBJECT IN PYTHON
Additional Program Beyond the syllabus
Date:
Aim:
To write a python program to Implement class and object
Algorithm:
1. Define a class Myclass
1.1 Assign a member variable x as 5
2.Create object p1 by calling Myclass()
3.Display the value of member variable using . operator with p1
4. Define a class Person
4.1 Define _init_ () by passing name, age
4.1.1 Assign name and age to self object
5.Create object p1 of type Person
6.Display the person name and age
7.Stop
Program:
class MyClass:
x=5
p1 = MyClass()
print("The value of x",p1.x)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
Output:
The value of x 5
Name of the person John
Age of the person 36
>
Result:
Thus the above python program to Implement class and object has been done and
output has been verified
Implementation of linear search algorithm using function in
Ex. No.: 13 B
python
Date:
Additional Program Beyond the syllabus
Aim:
To write a python program to Implement linear search using function
Algorithm:
Step 1: Enter the element to be searched as a
Step 2: Define mylist as list of elements 10,20,2,1,25
Step 3: Call the function linear by passing a and mylist as arguments
Step 4: Define the function lenear()
Step 4.1 : Initialize i=0,matched=0
Step 4.2 : Repeat for k in mylist
Step 4.3 : Check whether input to be searched is equal to k, if true display
the input x found at index I and change the value of the variable
matched as 1else goto Step 4.6
Step 4.4 : break
Step 4.5 : Increment I by 1
Step 4.6 : display that element is not found
Step 5: Stop
Program:
#linear search
def linear(x,mylist):
i=0
matched=0
for k in mylist:
if(x == k):
print(x , " is found @",i)
matched=1
break
i=i+1
if(matched==0):
print(x, "is not found in the given list")
a=int(input("enter the element to search"))
mylist=[10,20,2,1,25]
linear(a,mylist)
#linear(5,[10,20,5,30,99])
#linear(100,[10,20,5,30,99])
Output:
enter the element to search5
5 is not found in the given list
Result:
Thus the above python program to Implement Linear Search using function has
been done and output has been verified