Python Lab Manual
Python Lab Manual
Laboratory Manual
UG Regulation 2021
Prepared by : K.Rajalakshmi
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
Patternspyramid pattern)
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)
12. Developing a game activity using Pygame like bouncing ball, car race etc.
COURSE OUTCOMES
On completion of the course, students will be able to:
CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
TEXT BOOKS
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition, O’Reilly
Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and MadhavanMukund, “Computational Thinking: A Primer for Programmers andData
Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python: With Applicationsto
Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press, 2021
4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to Programming”,2nd
Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
Ex. No: 1.A) ELECTRICITYBILLING
Aim
To draw flowchart for Electricity Billing
Flowchart
Start
Read Units
Print Amount
Stop
Result
Thus the flowchart for Electricity Billing was drawn successfully
Ex. No: 1.B) RETAIL SHOPBILLING
Aim
To draw flowchart for Retail shopbilling
Flowchart
Start
tax=0.18
Rate_of_item
Display Items
Read Quantities
Cost=Rate_of_item *
quantity+Rate_of_item
*quantity+……………..
Bill_Amount=cost+cost*tax
Print Bill_Amount
Stop
Result
Thus the flowchart for Retail shopbilling was drawn successfully
Ex. No: 1.C) SINESERIES
Aim
To evaluate and draw flowchart for Sine Series
Flowchart
Start
Read x, n
x=x*3.14159/180
t=x
sum=x
t=(t*(-
1)*x*x)/(2*i*(2*i+1));sum=su
m+t;
Stop
Result
Thus the flowchart for Sine Series was drawn successfully
Ex. No: 1.D) WEIGHT OF A MOTOR BIKE
Aim
To draw flowchart for weight of Motorbike
Flowchart
Start
start
Read weight
Stop
Result
Thus the flowchart for weight of Motorbike was drawn successfully
Ex. No: 1.E) WEIGHT OF A STEELBAR
Aim
To draw flowchart for Weight of a Steel Bar
Flowchart
Start
Read Diameter D
W=D2/162
Print W
Stop
Result
Thusthe flowchart for Weight of a Steel Bar was drawn successfully
Ex. No: 1.F) COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Aim
To draw flowchart for Compute electrical current in three phase AC circuit.
Flowchart
Start
Print VA
Stop
Result
Thus the flowchart for Compute electrical current in three phase AC circuit was drawn successfully
Ex. No: 2.A) EXCHANGE THE VALUES OF TWO VARIABLES USING TEMPORARY VARIABLE
Aim
To write a program to exchange the values of two variables using third variable
Algorithm
1. Start
2. Read x and y
3. Print x and y value before swap
3. Swap values using temporary variable
temp=x
x=y
y=temp
4. Print x and y value after swap
5. Stop
Program
x = int(input("Enter x value:"))
y = int(input("Enter y value:"))
print("Value of x and y before swap:",x,y)
temp = x
x=y
y = temp
print("Value of x and y after swap:",x,y)
Output
Enter x value:10
Enter y value:23
Value of x and y before swap: 10 23
Value of x and y after swap: 23 10
Result
Thus the Python program to exchange the values of two variables by using a third variable
was executed successfully.
Ex. No: 2.B) EXCHANGE THE VALUES OF TWO VARIABLES WITHOUT USING TEMPORARY
VARIABLE
Aim
To write a program to exchange the values of two variables without using third variable.
Algorithm
1. Start
2. Read x and y
3. Print x and y value before swap
3. Swap values without temporary variable
x=x+y
y=x-y
x=x-y
4. Print x and y value after swap
5. Stop
Program
x = int(input("Enter x value:"))
y = int(input("Enter y value:"))
print("Value of x and y before swap:",x,y)
x=x+y
y=x-y
x=x-y
print("Value of x and y after swap:",x,y)
Output
Enter x value:24
Enter y value:45
Value of x and y before swap: 24 45
Value of x and y after swap: 45 24
Result
Thus the Python program to exchange the values of two variables without using a third variable
was executed successfully.
Ex. No: 2.C) CIRCULATE THE VALUES OF N VARIABLES
Aim
To write a program to circulate the values of N variables.
Algorithm
1. Start
2. Read upper limit n
3. Read n element using loop
4. Store elements in list
5. POP out each element from list and append to list
6. Print list
7. Stop
Program
n = int(input("Enter number of values:"))
list1=[]
fori in range(0,n,1):
x=int(input("Enter integer:"))
list1.append(x)
print("Circulating the elements of list:",list1)
fori in range(0,n,1):
x=list1.pop(0)
list1.append(x)
print(list1)
Output
Enter number of values:3
Enter integer:2
Enter integer:3
Enter integer:5
Circulating the elements of list: [2, 3, 5]
[3, 5, 2]
[5, 2, 3]
[2, 3, 5]
Result
Thus the Python program to circulate the values of N variables was executed successfully.
Ex. No: 2.D) DISTANCE BETWEEN TWO VARIABLES
Aim
To write a program to find distance between two variables.
Algorithm
1. Start
2. Read four coordinates x1, y1, x2, y2
Result
Thus the Python program to find distance between two variables was executed successfully.
Ex. No: 3.A) NUMBERSERIES
Aim
To write a program to evaluate number series12+22+32+….+N2
Algorithm
1. Start
2. Read maximum limit n
3. Initialize sum=0 and i=1
4. Calculate sum of series
while i<=n:
sum=sum+i*i
increment i
5. Print sum
6. Stop
Program
n = int(input('Enter a number: '))
sum=0
i=1
whilei<=n:
sum=sum+i*i
i+=1
print('Sum = ',sum)
Output
Enter a number: 3
Sum = 14
Result
Thus the Python program to evaluate number series was executed successfully.
Ex. No: 3.B) NUMBER PATTERN
Aim
To write a program to print number pattern.
Algorithm
1. Start
2. Read upper limit N
3. Print pattern using nested for loop
fori in range(1,N+1)
for k in range (N,i-1)
print empty space
for j in range(1,i+1)
print j
for l in range(i-1,0,-1)
print l
4. Stop
Program
N = int(input("Enter the number:"))
fori in range(1,N+1):
for k in range(N,i,-1):
print " ",
for j in range(1,i+1):
print j,
for l in range(i-1,0,-1):
print l,
print
Output
Enter the number:3
1
121
12321
Result
Thus the Python program toprint number pattern was executed successfully.
Ex. No: 3.C) HALF PYRAMIDPATTERN
Aim
To write a python program to print half pyramid pattern
Algorithm
1. Start
2. Read upper limit rows
3. Print pyramid pattern using nested for loop
fori in range(rows):
for j in range(i+1)
print * in half pyramid
print newline
4. Stop
Program
rows = int(input("Enter number of rows: "))
fori in range(rows):
for j in range(i+1):
print "* ",
print("\n")
Output
Enter number of rows: 4
*
* *
* * *
* * * *
Result
Thus the Python program to print half pyramid pattern was executed successfully.
Ex. No: 3.D) FULL PYRAMID PATTERN
Aim
To write a program to print pyramid pattern.
Algorithm
1. Start
2. Read upper limit rows
3. Print pyramid using for and while loop
fori in range(1,rows+1):
print space in range 1,(rows-i)+1
while k!=(2*i-1):
print *
increment k
set k=0
4. Process continues upto range
5. Stop
Program
rows = int(input("Enter number of rows: "))
k=0
fori in range(1, rows+1):
for space in range(1, (rows-i)+1):
print " ",
while k!=(2*i-1):
print "*",
k += 1
k=0
print
Output
Enter the number of rows: 3
*
* *
* * *
Result
Thus the Python program to print full pyramid pattern was executed successfully.
Ex. No: 4.A) ITEMS PRESENT IN A LIBRARY
Aim
Towrite a program to implementoperationsina librarylist
Algorithm
1. Start
2. Read library list
3. Print library details
4. Print first and fourth position element
5. Print items from index 0 to 4
6. Append new item in library list
7. Print index of particular element
8. Sort and print the element in alphabetical order
9. Pop the element
10. Remove the element
11. Insert an element in position
12. Count the number of elements in library
13. Stop
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('-7th element: ',library[-7])
library.append('Audiobooks')
print('Library list after append( ): ',library)
print('Index of \'Newspaper\': ',library.index('Newspaper'))
library.sort( )
print('After sorting: ', library);
print('Popped elements is: ',library.pop( ))
print('After pop( ): ', library);
library.remove('Maps')
print('After removing \'Maps\': ',library)
library.insert(2, 'CDs')
print('After insert: ', library)
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']
-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 toprint items present in a library using list operation
was executed successfully.
Ex. No: 4.B) COMPONENTS OF A CAR
Aim
Towrite a program to implement operations of Tuple using Components of a Car.
Algorithm
1. Start
2. Read car tuple
3. Print components of car
4. Print first and fourth position element
5. Print items from index 0 to 4
6. Print index of particular element
7. Count the number of ‘Seat Belt element’ in car tuple
8. Count number of elements in car tuple
9. Stop
Program
car = ('Engine','Battery','Alternator','Radiator','Steering','Break','SeatBelt')
print('Components of a car: ',car)
print('First element: ',car[0])
print('Fourth element: ',car[3])
print('Components of a car from 0 to 4 index: ',car[0: 5])
print('3rd or -7th element: ',car[-7])
print('Index of \'Alternator\': ',car.index('Alternator'))
print('Number of Elements in Car Tuple : ',car.count('Seat Belt'))
print('Length of Elements in Car Tuple : ',len(car))
Output
Components of a car: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break', 'SeatBelt')
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: 0
Length of Elements in Car Tuple: 7
Result
Thus the Python program toprint components of a car using tuple operation was executed successfully.
Ex. No: 4.C) MATERIALS REQUIRED FOR CONSTRUCTION OF A BUILDING
Aim
Towrite a program for operations of list to print materials required for construction of a building
Algorithm
1. Start
2. Read material list
3. Print material details
4. Print first and fourth position element
5. Print number of elements in material list
6. Print items from index 0 to 2
7. Append new item in material list
8. Print list of material after append
9. Print ending alphabet of material
10. Print starting alphabet of material
11. Print index of particular element
12. Sort and print the element in alphabetical order
13. Pop the element and print remaining element of material
14. Remove an element and print remaining element of material
15. Insert an element in position
16. Print the element after inserting
17. Stop
Program
material =['Wood','Concrete','Brick','Glass','Ceramics','Steel']
print('Building Materials',material)
print('First element: ',material[0])
print('Fourth element: ',material[3])
print('Number of Elements in Material list : ',len(material))
print('Items in Material from 0 to 2 index: ',material[0: 3])
print('-3th element: ',material[-3])
material.append('Water')
print('Material list after append(): ',material)
print('Ending Alphabet of Material',max(material))
print('Starting Alphabet of Material',min(material))
print('Index of Brick: ',material.index('Brick'))
material.sort( )
print('After sorting: ', material);
print('Popped elements is: ',material.pop())
print('After pop(): ', material);
material.remove('Glass')
print('After removing Glass: ',material)
material.insert(3, 'Stone')
print('After insert: ', material)
Output
Building Materials ['Wood', 'Concrete', 'Brick', 'Glass', 'Ceramics', 'Steel']
First element: Wood
Fourth element: Glass
Number of Elements in Material list : 6
Items in Material from 0 to 2 index: ['Wood', 'Concrete', 'Brick']
-3th element: Glass
Material list after append(): ['Wood', 'Concrete', 'Brick', 'Glass', 'Ceramics', 'Steel', 'Water']
Ending Alphabet of Material Wood
Starting Alphabet of Material Brick
Index of Brick: 2
After sorting: ['Brick', 'Ceramics', 'Concrete', 'Glass', 'Steel', 'Water', 'Wood']
Popped elements is: Wood
After pop(): ['Brick', 'Ceramics', 'Concrete', 'Glass', 'Steel', 'Water']
After removing Glass: ['Brick', 'Ceramics', 'Concrete', 'Steel', 'Water']
After insert: ['Brick', 'Ceramics', 'Concrete', 'Stone', 'Steel', 'Water']
Result
Thus the Python program to print materials required for construction of a building using list operation
was executed successfully.
Ex. No: 5.A) COMPONENTS OF A LANGUAGE
Aim
To implement operations of set to print components of a language
Algorithm
1. Start
2. Read two sets L1 and L2
3. Print union of L1 and L2
4. Print Intersection of L1 and L2
5. Print Difference L1 and L2
6. Print Symmetric difference of L1 and L2
7. Stop
Program
L1 = {'Pitch', 'Syllabus', 'Script', '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)
Output
Union of L1 and L2 is {'Phonetics', 'Sentences', 'Context', 'Script', 'Syllabus', 'Grammar', 'Words', 'Pitch'}
Intersection of L1 and L2 is {'Syllabus', 'Grammar'}
Difference of L1 and L2 is {'Script', 'Pitch', 'Sentences'}
Symmetric difference of L1 and L2 is {'Script', 'Phonetics', 'Sentences', 'Context', 'Pitch', 'Words'}
Result
Thus the Python program to print components of a language using set operation
was executed successfully.
Ex. No: 5.B) ELEMENTS OF A CIVIL STRUCTURE
Aim
To implement operations of dictionary to print elements of a civil structure.
Algorithm
1. Start
2. Read elements in civil variable
3. Print elements
4. Insert element in last position and print
5. Update element in particular position and print the elements
6. Print the value of key using square bracket and get method
7. Remove element from the structure and print the remaining elements
8. Remove element arbitrarily using popitem( ) function
9. Stop
Program
civil = {1:'Foundation',2:'Roof',3:'Beams',4:'Columns',5:'Walls'};
print(civil)
civil[6]='Stairs'
print("Print elements after adding:",civil)
civil[3]='Lintels'
print("Elements after updating key 3:",civil)
print("Print value of Key 2:",civil[2])
print("Print value of Key 5:",civil.get(5))
print("Element removed from key 1:",civil.pop(1))
print("Elements after removal:",civil)
print("Element removed arbitrarily:",civil.popitem())
print("Elements after pop:",civil)
Output
{1: 'Foundation', 2: 'Roof', 3: 'Beams', 4: 'Columns', 5: 'Walls'}
Print elements after adding: {1: 'Foundation', 2: 'Roof', 3: 'Beams', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Elements after updating key 3: {1: 'Foundation', 2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Print value of Key 2: Roof
Print value of Key 5: Walls
Element removed from key 1: Foundation
Elements after removal: {2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls', 6: 'Stairs'}
Element removed arbitrarily: (6, 'Stairs')
Elements after pop: {2: 'Roof', 3: 'Lintels', 4: 'Columns', 5: 'Walls'}
Result
Thus the Python program toprint elements of civil structure using dictionary operation
was executed successfully.
Ex. No: 6.A) FACTORIAL USING RECURSION
Aim
To write a program to find the factorial of a number using recursion
Algorithm
1. Start
2. Read num
3. Call fact (n)
4. Print factorial f
5. Stop
Fact (n)
1. if n==1 then
return n
2. else
return (n*fact (n-1))
Program
deffact (n):
if n==1:
return n
else:
return (n*fact (n-1))
num = int (input("Enter a number: "))
f=fact(num)
print("The factorial of",num,"is",f)
Output
Enter a number: 3
The factorial of 3 is 6
Result
Thus the Python program tofind factorial of a number using recursion was executed successfully.
Ex. No: 6.B) FINDING LARGEST NUMBER IN A LIST USING FUNCTION
Aim
To write a program to find the largest number in a list using functions.
Algorithm
1. Start
2. Initialize empty list as lis1t=[ ]
3. Read upper limit of list n
4. Read values of list using for loop
fori in range(1,n+1)
Read num
Append num in list1
5. Call function myMax(list1)
6. Stop
myMax(list1)
1. Print largest element in a list using max( ) function
Program
def myMax(list1):
print("Largest element is:", max(list1))
list1 = []
n = int(input("Enter number of elements in list: "))
fori in range(1, n + 1):
num = int(input("Enter elements: "))
list1.append(num)
myMax(list1)
Output
Enter number of elements in list: 4
Enter elements: 23
Enter elements: 15
Enter elements: 67
Enter elements: 45
Largest element is: 67
Result
Thus the Python program to find the largest number in a list using functions was executed successfully.
Ex. No: 6.C) FINDING AREA OF A SHAPE USING FUNCTION
Aim
To writeaprogram to find the areaof a shapeusing functions
Algorithm
1. Start
2. Print Calculate Area of Shape
3. Read shape_name
4. Call function calculate_area(shape_name)
5. Stop
calculate_area(name):
1. Convert letters into lowercase
2. Check name== “rectangle” :
2.1. Read l
2.2. Read b
2.3. Calculate rect_area=l*b
2.4. Print area of rectangle
3. elif name==”square”:
3.1. Read s
3.2. Calculate sqt_area = s * s
3.3. Print area of square
4. elif name == "triangle":
4.1. Read h
4.2. Read b
4.3. Calculate tri_area = 0.5 * b * h
4.4. Print area of triangle
5. elif name == "circle":
5.1. Read r
5.2. Calculate circ_area = pi * r * r
5.3. Print area of circle
6. else:
6.1. Print Sorry! This shape is not available
Program
defcalculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print ("The area of rectangle=", rect_area)
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print ("The area of square=",sqt_area)
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print ("The area of triangle=",tri_area)
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print ("The area of circle=",circ_area)
else:
print("Sorry! This shape is not available")
print("Calculate Area of Shape")
shape_name = raw_input("Enter the name of shape: ")
calculate_area(shape_name)
Output
Calculate Area of Shape
Enter the name of shape: rectangle
Enter rectangle's length: 2
Enter rectangle's breadth: 3
('The area of rectangle=', 6)
Result
Thus the Python program to find the area of a shape using functions was executed successfully.
Ex. No: 7.A) REVERSINGA STRING
Aim
Towritea programtofind reverse astring.
Algorithm
1. Start
2. Read string in s
3. Print reversed string through function reverse(s)
4. Stop
reverse(string):
1. Reverse a string using join(reversed(string))
2. return reversed string
Program
def reverse(string):
string = "".join(reversed(string))
return string
s = raw_input("Enter any string: ")
print ("The original string is:",s)
print ("The reversed string(using reversed):",reverse(s))
Output
Enter any string: river
('The original string is:', 'river')
('The reversed string(using reversed):', 'revir')
Result
Thus the Python program to find reverse astring was executed successfully.
Ex. No: 7.B) PALINDROME IN A STRING
Aim
Towriteaprogram tocheck a given string is palindrome or not.
Algorithm
1. Start
2. Read string
3. Reverse a string using reversed( ) function
4. Check rev_string==original_string
Print "It is palindrome"
5. else
It is not palindrome
6. Stop
Program
string = raw_input("Enter string: ")
rev_string = reversed(string)
if list(string)== list(rev_string):
print("It is palindrome")
else:
print("It is not palindrome")
Output
Enter string: mam
It is palindrome
Result
Thus the Python program to check a string palindrome was executed successfully.
Ex. No: 7.C) COUNT CHARACTERS IN A STRING
Aim
Towriteaprogram tocountnumber ofcharacters in astring.
Algorithm
1. Start
2. Read string
3. Read character to count
4. Count number of characters using count( ) function
5. Print count
6. Stop
Program
string = raw_input("Enter any string: ")
char = raw_input("Enter a character to count: ")
val = string.count(char)
print("count",val)
Output
Enter any string: river
Enter a character to count: r
('count', 2)
Result
Thus the Python program to count number of characters in a string was executed successfully.
Ex. No: 7.D) REPLACING CHARACTERS
Aim
To write a program to replace characters in a string.
Algorithm
1. Start
2. Read string
3. Read old string to replace in str1
4. Read new string in str2
5. replace(str1,str2)
6. Print replaced string
7. Stop
Program
string = raw_input("Enter any string: ")
str1 = raw_input("Enter old string: ")
str2 = raw_input("Enter new string: ")
print(string.replace(str1, str2))
Output
Enter any string: python
Enter old string: p
Enter new string: P
Python
Result
Thus the Python program to replace characters in a string was executed successfully
Ex. No: 8 INSTALLING AND EXECUTING PYTHON PROGRAM IN ANACONDA NAVIGATOR
Aim
To write a python program to compare the elements of the two pandas series using pandas library.
Algorithm
1. Start
2. Import pandas library
3. Read and print two series in ds1 and ds2
4. Compare and print equality of two series
5. Compare ds1>ds2 and print the result
6. Compare ds1<ds2 and print the result
7. Stop
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:
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 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 python program using pandas library was executed successfully
Ex. No: 8. B) PYTHON PROGRAM USING NUMPY LIBRARY
Aim
Towriteato test whether none of the elements of a given array is zero using NumPy library
Algorithm
1. Start
2. Import numpy library
3. Read array in y, x, arr1 and arr2
4. Test and print none of elements in array is zero using all( ) function
5. Round the values and print the result
6. Add, divide two arrays and print the result
7. Stop
Program
importnumpy as np
y=np.array([1.3,2.5,3.8,4.1])
print("Original Array")
print(y)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x=np.array([1,1,2,0])
print("\nOriginal Array")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
roundoff = np.around(y)
print ("\nRounded values \n",roundoff)
arr1 = [2, 27, 2, 21, 23]
arr2 = [2, 3, 4, 5, 6]
print ("\narr1 : ", arr1)
print ("arr2 : ", arr2)
add=np.add(arr1,arr2)
print ("Add array : \n", add)
out = np.divide(arr1, arr2)
print ("Divide array : \n", out)
Output
Original Array
[1.3 2.5 3.8 4.1]
Test if none of the elements of the said array is zero:
False
Original Array
[1 1 2 0]
Test if none of the elements of the said array is zero:
False
Rounded values
[1. 2. 4. 4.]
Result
Thus the python program using numpy library was executed successfully
Ex. No: 8. C) PLOT A GRAPH USING MATPLOTLIB LIBRARY
Aim
Towritea python program to plot a graph using matplotlib library
Algorithm
1. Start
2. Import matplotlib.pyplot library
3. Import numpy library
4. Read two array in x points and y points
5. Plot line graph and show it
6. Read two arrays in x and y
7. Plot bar graph and show it
8. Stop
Program
importmatplotlib.pyplot as plt
importnumpy as np
xpoints=np.array([0,6])
ypoints=np.array([0,250])
plt.plot(xpoints,ypoints)
plt.show()
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.bar(x,y)
plt.show()
Output
Result
Thus the python program using matplotlib library was executed successfully.
Ex. No: 8. D) RETURN MATHEMATICAL CONSTANTS USING SCIPY LIBRARY
Aim
Towritea python program to return mathematical constants usingscipy library.
Algorithm
1. Start
2. Import constants from scipy library
3. Pint constant value of pi
4. Print minute in seconds
5. Print hour in seconds
6. Print day in seconds
7. Print week in seconds
8. Print year in seconds
9. Stop
Program
fromscipy import constants
print(constants.pi)
print(constants.minute)
print (constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)
Output
3.141592653589793
60.0
3600.0
86400.0
604800.0
31536000.0
Result
Thus the python program using scipy library was executed successfully
Ex. No: 9. A) COPY FROM ONE FILE TO ANOTHER
Aim
Towritea python program to copy from one file to another
Algorithm
1. Start
2. Create two text files through notepad such as sample1.txt and sample2.txt
3. Write some content in sample1.txt while creating it
4. Print “Enter the name of source file”
5. Read first file sample1.txt in sFile using raw_input
6. Open sample1.txt in read mode
7. Read all text from file to texts variable
8. Close sample1.txt
9. Read second file sample2.txt in tFile using raw_input
10. Open sample2.txt in write mode
11. Write all data from texts to sample2.txt using for loop
12. Close sample2.txt
13. Print “File copied successfully”
14. Stop
Program
print("Enter the Name of Source File: ")
sFile = raw_input()
fileHandle = open(sFile,"r")
texts = fileHandle.readlines()
fileHandle.close()
print("Enter the Name of Target File: ")
tFile = raw_input()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")
Output
Enter the Name of Source File:
sample1.txt
Enter the Name of Target File:
sample2.txt
File Copied Successfully!
After Copied
Result
Thus the Python program tocopy from one file to another was executed successfully
Ex. No: 9. B) WORD COUNT FROM A FILE
Aim
To write a python program to count number of word in a file.
Algorithm
1. Start
2. Create and write content intext file through notepad such as data.txt
3. Print “Enter the name of file”
4. Read filedata.txt in sFile using raw_input
5. Open file in read mode and store content in file1
6. Read content in file1 using for loop
7. Split the word in file and count the length
8. Print count
9. Close the file
10. Stop
Program
print("Enter the Name of File: ")
sFile = raw_input()
file1 = open(sFile,"r")
forval in file1:
count=len(val.split())
print('Number of words in text file:',count)
file1.close ()
Output
Enter the Name of File:
data.txt
('Number of words in text file:', 7)
Result
Thus the Python program to count number of word in a file was executed successfully
Ex. No: 9. C) FINDING LONGEST WORD IN A FILE
Aim
To write a python program to find longest word in a file.
Algorithm
1. Start
2. Create and write content in text file through notepad such as data.txt
3. Print “Enter the name of file”
4. Read file data.txt in sFile using raw_input
5. Pass sFile as an argument through function call
6. Open file in read mode and store content in words
7. Find longest word in a file using len( ) function
7. Split the word in file and count the length
8. Print longest word
9. Close the file
10. Stop
Program
deflongest_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("Enter the Name of File: ")
sFile = raw_input()
print(longest_word(sFile))
Output
Enter the Name of File:
data.txt
['collection']
Result
Thus the Python program to find longest word in a file was executed successfully.
Ex. No: 10. A) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING
Aim
To write a python program to handle divide by zero error using exception handling.
Algorithm
1. Start
2. Read a,b and c
3. Inside the try block calculate q=a/(b-c)
4. Print Quotient when d-c!=0 otherwise throw exception
5. Catch the exception and display the appropriate message.
6. Stop
Program
a=int(input("Enter the value of n:"))
b=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=a/(b-c)
print("Quotient:",q)
exceptZeroDivisionError:
print("Divide by Zero is not possible!")
Output
Enter the value of n:6
Enter the value of d:3
Enter the value of c:1
('Quotient:', 3)
Result
Thus the Python program to handle divide by zero error using exception handling was executed
successfully.
Ex. No: 10. B) VOTERS AGE VALIDITY
Aim
To write a python program to check voter’s age validity.
Algorithm
1. Start
2. Import date time module
3. Read Year_of_birth
4.Get current_year=datetime.datetime.now( ).year
5. Calculate current age=current_year – Year_of_birth
6. Print Current_age
7. Inside the try block check If Current_age<=18: then
8. Raise ValueError(“You are not eligible to vote”)
9. Else print “You are eligible to vote”
10. Catch exception and handle it
11. Stop
Program
Import datetime
Year_of_birth = int(input("In which year you took birth:- "))
current_year = datetime.datetime.now( ).year
Current_age = current_year - Year_of_birth
print("Your current age is ",Current_age)
try:
if(Current_age<=18):
raiseValueError("You are not eligible to vote")
else:
print("You are eligible to vote")
exceptValueError as e:
print(e)
Output
In which year you took birth:- 2009
('Your current age is ', 13)
You are not eligible to vote
In which year you took birth:- 1998
('Your current age is ', 24)
You are eligible to vote
Result
Thus the Python program to check voter’s age validity using exception handling was executed
successfully
Ex. No: 10. C) STUDENT MARK RANGE VALIDATION
Aim
To write a python program to perform student mark range validation.
Algorithm
1. Start
2. Inside the try block
3. Read Mark
4.Check if Mark<0 or Mark>100: then
5. Raise ValueError("The mark is out of range, try again.")
6. Else print("The Mark is in the range")
7. Catch exception and handle it
8. Stop
Program
try:
Mark = int(input("Enter the Mark: "))
if Mark <0 or Mark >100:
raiseValueError("The mark is out of range, try again.")
else:
print("The Mark is in the range")
exceptValueError as e:
print(e)
OUTPUT
Enter the Mark: 67
The Mark is in the range
Result
Thus the Python program to perform student mark range validation using exception handling was
executed successfully.
Ex. No: 11 EXPLORE PYGAME TOOL
Introduction to Pygame
Python Pygame library is used to create video games. This library includes several modules for
playing sound, drawing graphics, handling mouse inputs, etc. It is also used to create client-side
applications that can be wrapped in standalone executable.
To InstallPygame Module
Steps
1. Check for Python Installation
In order to install Pygame, Python must be installed already in your system. To check whether Python
is installed or not in your system, open the command prompt and give the command as shown below.
2. Install Anaconda Navigator. Open anaconda prompt (anaconda 3) and type the following command
pip install pygame
3. Open spyder in anaconda navigator to do pygame program
Ex. No: 12. A) DEVELOP A BOUNCING BALL GAME USING PYGAME
Aim
To write a pygame program to develop bouncing ball.
Program
importpygame
pygame.init()
window_w = 800
window_h = 600
white = (255, 255, 255)
red = (255, 0, 0)
green=(0,255,0)
blue=(0,0,255)
FPS = 150
window = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Bouncing Ball")
clock = pygame.time.Clock()
defgame_loop():
block_size = 10
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
for event in pygame.event.get():
ifevent.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
ifpos_x + block_size>window_w or pos_x< 0:
velocity[0] = -velocity[0]
ifpos_y + block_size>window_h or pos_y< 0:
velocity[1] = -velocity[1]
window.fill(white)
pygame.draw.circle(window, red, [pos_x, pos_y], 30)
pygame.draw.circle(window, blue, [pos_x-50, pos_y-50], 30)
pygame.display.update()
clock.tick(FPS)
game_loop()
Output
Result
Thus the Pygamecode for bouncing ball was created and executed successfully
Ex. No: 12. B) DEVELOP A CAR RACE GAME USING PYGAME
Aim
To write a pygame program to develop car race game
Program
Import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
car_width = 10
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A Car Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load('racecar5.png')
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def car(x,y):
gameDisplay.blit(carImg,(x,y))
deftext_objects(text, font):
textSurface = font.render(text, True, black)
returntextSurface, textSurface.get_rect()
defmessage_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
defgame_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
ifevent.type == pygame.QUIT:
pygame.quit()
quit()
ifevent.type == pygame.KEYDOWN:
ifevent.key == pygame.K_LEFT:
x_change = -5
ifevent.key == pygame.K_RIGHT:
x_change = 5
ifevent.type == pygame.KEYUP:
ifevent.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
# things(thingx, thingy, thingw, thingh, color)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
car(x,y)
if x >display_width - car_width or x < 0:
crash()
ifthing_starty>display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0,display_width)
####
if y <thing_starty+thing_height:
print('y crossover')
if x >thing_startx and x <thing_startx + thing_width or x+car_width>thing_startx and x +
car_width<thing_startx+thing_width:
print('x crossover')
crash()
####
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Output
Result
Thus the Pygame code for car racing was created and executed successfully