LAB MANUAL
List of Programs
1. Developing flow charts
a. Electricity Billing,
b. Retail Shop Billing,
c. Sin Series,
d. Weight of a Motorbike,
e. Weight of a Steel Bar,
f. Compute Electrical Current in Three Phase AC Circuit,
2. Programs Using Simple Statements
a. Exchange the values of two variables,
b. Circulate the values of n variables,
c. Distance between two points.
3. Programs Using Conditionals and Iterative Statements
a. Number Series
b. Number Patterns
c. Pyramid Pattern
4. Operations of Lists and Tuples (Items present in a library/Components of a
car/ Materials required for construction of a building)
5. Operations of Sets & Dictionaries (Language, components of an automobile,
Elements of a civil structure, etc)
6. Programs Using Functions
a. Factorial of a Number
b. Largest Number in a list
c. Area of Shape
7. Programs using Strings.
a. Reversing a String,
b. Checking Palindrome in a String,
c. Counting Characters in a String
d. Replacing Characters in a String
8. Programs Using modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Programs using File Handling.
a. Copy from one file to another,
b. Word count,
c. Longest word
10. Programs Using Exception handling.
a. Divide by zero error,
b. Voter’s age validity,
c. Student mark range validation
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
DEVELOPING FLOWCHARTS ELECTRICITY
BILLING
Problem Statement:
• For 0 to 100 units the per unit is ₹ 0/-
• 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.
• For 0 to 500 units, the consumer shall pay ₹ 0 for the first 100 units, forthe
next 100 units the consumer shall pay ₹ 2 per unit, for the next 300 units
the unit cost is ₹3.00/-
• 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/-
Start
Read Units
< =100 <=200 Units <= 500 >500
=
?
Amount = Amount = (100* 0) +
100* 0 (200 – 100)*3.5 +
Amount = (100* 0) + Amount = (100* 0) + (500 – 200)* 4.6+
(Unit – 100)*1.5 (200– 100)*2 + (Unit – 500) * 6.6
(Unit – 200)*3
Print Amount
Stop
RETAIL SHOP BILLING
Problem Statement:
To prepare Retail shop billing flowchart.
Start
Tax=0.18
Rate_of_item
Display Items
Read Quantities
Cost=Rate_of_item * quantity+
Rate_of_item * quantity+ ……………..
BillAmount = cost + cost * tax
Print BillAmount
Stop
SINE SERIES
Problem Statement:
To evaluate the sine series. The formula used to express the Sin(x) as
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
WEIGHT OF A STEEL BAR
Problem Statement:
To find the weight of a steel bar.
Start
Read Diameter D
W = D2 / 162
Print W
Stop
COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Problem Statement:
To compute electrical current in three phase AC circuit.
Start
Read Vline , Aline
VA = * Vline * Aline
Print VA
Stop
PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE
VALUES OF TWO VARIABLES
Program:
def exchange(x,y): #Function Definition
x,y=y,x # swapping using tuple assignment
print("After exchange of x,y")
print("x =",x)
print("Y= ",y)
x=input("Enter value of X ") #Main Function
y=input("Enter value of Y ")
print("Before exchange of x,y")
print("x =",x)
print("Y= ",y)
exchange(x,y) # Function call
Output:
Enter value of X: 67
Enter value of Y: 56
Before exchange of x,y
x = 67
Y= 56
After exchange of x,y
x = 56
Y= 67
CIRCULATE THE VALUES OF N VARIABLES
Program:
def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("Circulation ",i,"=",B)
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)
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]
DISTANCE BETWEEN TWO VARIABLES
Program:
import math
x1 = int(input("Enter a x1: "))
y1 = int(input("Enter a y1: "))
x2 = int(input("Enter a x2: "))
y2 = int(input("Enter a y2: "))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = ",distance)
Output:
Enter a x1: 3
Enter a y1: 2
Enter a x2: 7
Enter a y2: 8
Distance = 7.211102550927978
PROGRAMS USING CONDITIONALS AND ITERATIVE LOOPS
NUMBER SERIES
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
NUMBER PATTERN
Program:
N=5
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 l in range(i−1,0,−1):
print(l, end =' ')
print()
Output:
121
12321
1234321
123454321
PYRAMID PATTERN
Program:
n = int(input("Enter the number of rows: "))
m = (2 * n) - 2
for i in range(0, n):
for j in range(0, m):
print(end=" ")
m = m - 1 # decrementing m after each loop
for j in range(0, i + 1):
# printing full Triangle pyramid using stars
print("* ", end=' ')
print(" ")
Output:
Enter the number of rows: 9
**
** *
** * *
** * * *
* * ** * *
** * * * * *
** * * * * * *
* ** * * * * * *
OPERATIONS OF LISTS
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
OPERATIONS OF 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
OPERATIONS OF SETS
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'}
FACTORIAL OF A NUMBER USING FUNCTION
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
FINDING LARGEST NUMBER IN A LIST USING FUNCTION
Program:
def myMax(list1):
print("Largest element is:", max(list1))
list1 = []
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list1.append(ele)
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
FINDING AREA OF A CIRCLE USING FUNCTION
Program:
def findArea(r):
PI = 3.142
return PI * (r*r);
num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num));
Output:
Enter r value:8
Area is 201.088000
REVERSING A STRING
Program:
def reverse(string):
string = "".join(reversed(string))
return string
s = input("Enter any string: ")
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))
Output:
Enter any string: Python
The original string is : Python
The reversed string(using reversed) is : nohtyP
CHECKING PALINDROME IN A STRING
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
COUNTING CHARACTERS IN A STRING
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: n
2
REPLACE CHARACTERS IN A STRING
Program:
def reverse(string):
string = "".join(reversed(string))
return string
s = input("Enter any string: ")
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))
Output:
Enter any string: Python
The original string is : Python
The reversed string(using reversed) is : nohtyP
INSTALLING AND EXECUTING PYTHONPROGRAM IN
ANACONDA NAVIGATOR
(To run pandas, numpy,matplotlib, scipy)
Step 1: Install anaconda individual edition for windows
Step 2: Open Anaconda navigator
Step 3: launch jupyter note book
Step 4:
Click new Python3
Step 5: Write or paste the python code
Step 6 : click run
PANDAS
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
NUMPY
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
MATPLOTLIB
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:
SCIPY
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
COPY FROM ONE FILE TO ANOTHER
Program:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
c = open(destinationfile, "r")
print(c.read())
c.close()
print()
print()
Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully!
Sunflower
Jasmine
Roses
WORD COUNT FROM A FILE
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk.
They can be easily retrieved when required. Python supports two types of files. They
are Text files & Binary files.
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
FINDING LONGEST WORD IN A FILE
Data.txt
A file is a collection of data stored on a secondary storage device like hard disk.
They can be easily retrieved when required. Python supports two types of files. They
are Text files & Binary files.
Program:
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('F:\Data.txt'))
Output:
['collection']
DIVIDE BY ZERO ERROR USING EXCEPTIONHANDLING
Program:
n=int(input("Enter the value of n:"))
d=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")
Output:
Enter the value of n:10
Enter the value of d:5
Enter the value of c:5
Division by Zero!
VOTERS AGE VALIDITY
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)
if(Current_age<=18):
print("You are not eligible to vote")
else:
print("You are eligible to vote")
Output:
In which year you took birth:- 1981
Your current age is 40
You are eligible to vote
In which year you took birth:- 2011
Your current age is 10
You are not eligible to vote
STUDENT MARK RANGE VALIDATION
Program:
Mark = int(input("Enter the Mark: "))
if Mark < 0 or Mark > 100:
print("The value is out of range, try again.")
else:
print("The Mark is in the range")
Output:
Enter the Mark: 150
The value is out of range, try again.
Enter the Mark: 98
The Mark is in the range
EXPLORING PYGAME
PYGAME INSTALLATION
To Install Pygame Module
Steps
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
6. Type the following command
C:\>py -m pip install pygame --user
Collecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)
100% |████████████████████████████████| 4.0MB
171kB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.3
7. Now, pygame installed successfully
8. To see if it works, run one of the included examples in pygame-1.9.3
• Open command prompt
• Type the following
C:\>cd Python36-32\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.py
C:\Python36-32\Scripts\pygame-1.9.3\examples>
SIMULATE BOUNCING BALL USING PYGAME
Program:
import pygame
pygame.init()
window_w = 800
window_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 120
window = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Game: ")
clock = pygame.time.Clock()
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + block_size > window_w or pos_x < 0:
velocity[0] = -velocity[0]
if pos_y + block_size > window_h or pos_y < 0:
velocity[1] = -velocity[1]
# DRAW
window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size,
block_size])
pygame.display.update()
clock.tick(FPS)
game_loop()