R2021 Python Lab Modified
R2021 Python Lab Modified
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:
Read Units
Print Amount
Stop
RETAIL SHOP BILLING
Problem Statement:
Start
Tax=0.18
Rate_of_item
Display Items
Read Quantities
Cost=Rate_of_item * quantity+
Rate_of_item * quantity+ ……………..
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;
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
Stop
WEIGHT OF A STEEL BAR
Problem Statement:
Start
Read Diameter D
W = D2 / 162
Print W
Stop
COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Problem Statement:
Start
VA = * Vline * Aline
Print VA
Stop
PROGRAMS USING SIMPLE STATEMENTS EXCHANGE THE
VALUES OF TWO VARIABLES
Program:
print("Y= ",y)
x=input("Enter value of X ") #Main Function
y=input("Enter value of Y ")
Enter value of X: 67
Enter value of Y: 56
x = 67
Y= 56
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
Program:
import math
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:
Output:
Enter a number: 10
Sum = 385
NUMBER PATTERN
Program:
N=5
for i in range(1,N+1):
for j in range(1,i+1):
for l in range(i−1,0,−1):
print()
Output:
121
12321
1234321
123454321
PYRAMID PATTERN
Program:
m = (2 * n) - 2
print(end=" ")
print(" ")
Output:
**
** *
** * *
** * * *
* * ** * *
** * * * * *
** * * * * * *
* ** * * * * * *
OPERATIONS OF LISTS
Program:
library =
['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
print('Library: ',library)
library.append('Audiobooks')
library.sort()
# popping an element
library.remove('Maps')
library.insert(2, 'CDs')
index of 'Newspaper': 2
Program:
Program:
# set union
# set intersection
# set difference
Output:
Program:
def fact(n):
if n = = 1:
return n
else:
return n*fact(n−1)
Output:
Enter a number: 5
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:
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
Output:
Program:
string = string.casefold()
rev_string = reversed(string)
if list(string) = = list(rev_string):
print("It is palindrome")
else:
Output:
It is not palindrome
COUNTING CHARACTERS IN A STRING
Program:
val = string.count(char)
print(val,"\n")
Output:
2
REPLACE CHARACTERS IN A STRING
Program:
def reverse(string):
string = "".join(reversed(string))
return string
Output:
Program:
import pandas as pd
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print("Less than:")
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 numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Output:
SCIPY
Program:
Output:
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
COPY FROM ONE FILE TO ANOTHER
Program:
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:
Output:
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:
Output:
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:
Program:
Output:
PYGAME INSTALLATION
Steps
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)
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
FPS = 120
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
pos_x += velocity[0]
pos_y += 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()