GE3171_Problem-Solving-and-Python-Programming-Lab
GE3171_Problem-Solving-and-Python-Programming-Lab
ELECTRICITY BILL
AIM:
To write a python program to calculate electricity bill
ALGORITHM
Step1: Start
Step2: Read units
Step3: check if(units<=100) then
payAmount=units*1.5
fixedcharge=25.00
elif(units<=200) then
payAmount=(100*1.5)+(units*100)*2.5
fixedcharge=50.00
elif(units<=350) then
payAmount=(100*1.5)=(200-100)*2.5+(300-200)*4=(units-300)*5
fixedcharge=100.00
else
payAmount=0
fixedcharge=1500.00
step4 : calculate total=payAmount+fixedcharge
Step 5: print the electricity bill
Step 6: stop
PROGRAM
units=int(input("please enter the number of units you consumed in a month"))
if(units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
fixedcharge=75.00
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
fixedcharge=100.00
else:
payAmount=0
fixedcharge=1500.00
Total=payAmount+fixedcharge
print("\nElecticity bill",Total)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
please enter the number of units you consumed in a month300
Electicity bill 875.0
1.B. RETAIL SHOP BILLING
AIM:
To write a python program to calculate Retail shop bill
ALGORITHM:
Step 1: Start the program
Step 2 : Define a function to calculate the bill amount.
Step 3: Read items_list, reqd _list,price_list,reqd_quantity.
Stem 4: Call the function to calculate bill amount.
Step 5 : Print the bill amount.
Step 6: Stop the program.
PROGRAM:
def calculate_bill_amount(items_list, price_list, reqd_items,reqd_quantity):
bill_amount=0
i=0
total=0
leng=len(reqd_items)
check = all(item in items_list for item in reqd_items)
if check is True:
while(i<leng):
inty=items_list.index(reqd_items[i])
total=total+ price_list[inty]*reqd_quantity[i]
bill_amount=total
i=i+1
else:
bill_amount=total
return bill_amount
items_list=["rice","oil","sugar","soap","paste"]
price_list=[50,200,40,30,35]
reqd_items=["rice","oil"]
reqd_quantity=[5,2]
bill_amount=calculate_bill_amount(items_list, price_list, reqd_items, reqd_quantity)
print(“Total bill amount:”, bill_amount)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Total bill amount: 650
1.C.SINE SERIES
AIM:
To write a python program to calculate Sine series
sin x = x - x3/3! + x5/5! - x7/7! + x9/9! ........
ALGORITHM:
Step 1: start
Step 2: read the value of x and n
Step 3: calculate the sum of sine series
Sign=-1
Fact=i=1
Sum=0
Step 4: check while i<=n then
P=1
Fact=1
For j in range (1,I +1)then
P=p*x
fact=fact*j
sign=-1*sign
Step 5: calculate sum=sum+sign*p/fact
I=i+2
Step 6: print(‘sin(,’x,’)=’,sum)
Step 7:stop
PROGRAM:
x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
sum = 0
while i<=n:
p=1
fact = 1
for j in range(1,i+1):
p = p*x
fact = fact*j
sign = -1*sign
sum = sum + sign* p/fact
i = i+2
print("sin(",x,") =",sum)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Enter the value of x: 5
Enter the value of n: 4
sin( 5 ) = -15.833333333333332
1.D. WEIGHT OF BIKE
AIM:
To write a python program along with flowchart to calculate Weight of bike
ALGORITHM:
Step1: start
Step2: read the values of x,wf,wr,wb
Step3: calculate the weight of bike
X=wr*wb/wf+wr
Step4: print weight of bike
Step5: stop
PROGRAM:
Wf=10#front weight
Wr=40# rear weight
WB=50#wheelbase
X =Wr*WB/ Wf+Wr
print("Weight of bike",X)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
PROGRAM:
D=10
L=100
W=(D**2)*L)/162
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
AIM:
To write a python program to calculate Sine series
ALGORITHM:
Step 1: start
Step 2: read the value of R , X_L ,V_L ,f
Step 3: calculate the line current
V_Ph =V_L/sqrt(3)
Z_Ph =sqrt((R**2)+(X_L**2))
I_Ph =V_Ph/Z_Ph
I_L = I_Ph
Step 4: print the line current in A is , round(I_L ,2)
Step 5: calculate the power factor
Pf = cos (phi) = R_Ph/Z_Ph
R_Ph=R
Phi= a cos(R_Ph/Z_Ph)
Step 6: print the power factor is : Pf ‘degree lag.
Step 7: calculate the power supplied
P=sqrt(3)*V_L*I_L*cos(phi)
Step 8: print the power supplied in W is;P
Step 9: stop
PROGRAM:
from math import cos,acos,sqrt
R = 20.;# in ohm
X_L = 15.;# in ohm
V_L = 400.;# in V
f = 50.;# in Hz
#calculations
V_Ph = V_L/sqrt(3);# in V
Z_Ph = sqrt( (R**2) + (X_L**2) );# in ohm
I_Ph = V_Ph/Z_Ph;# in A
I_L = I_Ph;# in A
print ("The line current in A is",round(I_L,2))
# pf = cos(phi) = R_Ph/Z_Ph;
R_Ph = R;# in ohm
phi= acos(R_Ph/Z_Ph);
# Power factor
pf= cos(phi);# in radians
print ("The power factor is : ",pf,"degrees lag.")
P = sqrt(3)*V_L*I_L*cos(phi);# in W
print ("The power supplied in W is",P)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
ALGORITHM:
Step1: start
Step2: read upper limit ‘var’
Step3: read ‘var’ elements using loop and store them in list
Step4: pop out each element from list and append to list
Step5: print list
Step6: stop
PROGRAM:
Var=int(input(‘enter number of values’))
List1=[]
For val in range (0, var, 1):
ele=int(input(“Enter the element”))
list1 . append(ele)
print (“circulating the elements of list”,list1)
for val in range (0, var,1)
ele = list1.pop(0)
list1.append(ele)
print(list1)
RESULT:
To write a Python program to circulate values of ‘n’ variables in the list.
OUTPUT:
enter number of values 4
enter the element12
enter the element43
enter the element11
enter the element56
circulating the elements of list [12, 43, 11, 56]
[43, 11, 56, 12]
[11, 56, 12, 43]
[56, 12, 43, 11]
[12, 43, 11, 56]
2.B. EXCHANGE THE VALUES OF TWO VARIABLES
AIM:
To write a Python program to exchange the values of two variables.
ALGORITHM:
Step 1: Start
Step 2: Initialize the function of swap
Step 3: Declare the variables a and b read input
Step 4: Call the function swap a,b
Step 5: The function swap perform the following operation
temp=a
a=b
b=temp
step 6:Print swap number a and b
step 7:Stop
PROGRAM:
def swap(a,b):
temp=a
a=b
b=temp
print(“the value of x after swapping:”,a)
print(“the value of y after swapping:”,b)
return
x=int(input(“Enter value of x:”))
y=int(input(“Enter value of y:"))
swap(x,y)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Enter value of x:6
Enter value of y:8
the value of x after swapping: 8
the value of y after swapping: 6
2.C. DISTANCE BETWEEN TWO POINTS
AIM:
To write the python program to find distance between two points.
ALGORITHM:
STEP 1: start the program
STEP2: Define function distance
STEP3: Read the value a,b,c & d
STEP4: Call the function distance
STEP5: The Distance function performs following
d=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
STEP6: Print distance between two points.
STEP7: Stop the program
PROGRAM:
import math
def distance (x1,y1,x2,y2):
d=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
return d
a= int(input('Enter the value of x1'))
b= int(input('Enter the value of x2'))
c= int(input('Enter the value of x1'))
d= int(input('Enter the value of x2'))
print( 'The distance between the two points is', distance(a,b,c,d))
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Enter the value of x13
Enter the value of x24
Enter the value of x15
Enter the value of x22
The distance between the two points is 2.8284271247461903
3.A. NUMBER SERIES
AIM:
ALGORITHM:
Step 2: Take the input from the user by using python input () function.
Step 4: Increment for loop iteration value by 1, as well as print iteration value.
PROGRAM
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Please Enter any Number: 10
The List of Natural Numbers from 1 to 10
1 2 3 4 5 6 7 8 9 10
3.B. NUMBER PATTERN
AIM:
ALGORITHM:
PROGRAM
num = 5
for n in range(1, num):
for i in range(1, n+1):
print(i, end=" ")
print("")
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
1
12
123
1234
3.C.PYRAMID PATTERN
AIM:
ALGORITHM:
PROGRAM
num = 5
for n in range(0, num):
for i in range(0, n+1):
print(*, end=" ")
print()
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
*
**
***
****
4.A. OPERATIONS OF LIST
AIM:
To write a python program to implement the operations of a list.
ALOGIRTM
Step: Start the program
Step 2: Create a list named list.
Step 3: Display the items in the list
Step 4: Append a new element to the existing list
Step 5: Delete an element from the existing list.
Step 6: Create a new list and concatenate it with the existing list.
Step 7: Repeat an item to a specified number of times.
Step 8: Stop the program.
PROGRAM:
print('operations of list')
list=['python programming','java complete reference','C']
print('Books available in library:')
print(list)
print('append the item in list')
newbook=input("enter the name of book to be inserted")
newlist=list.append(newbook)
print(list)
newlist=['C++ programming','C Programming']
print('Concatenation of 2 lists')
print('Concatenated list: ',(list+newlist))
print('Repetition of an item in list')
print(3*'python programming')
print("Removing an item from list")
list.remove('python programming')
print("Available books")
print(list)
RESULT:
Thus the python program was executed and verified successfully.
OUTPUT:
operations of list
Books available in library:
['python programming', 'java complete reference', 'C']
append the item in list
enter the name of book to be inserted C++
['python programming', 'java complete reference', 'C', ' C++']
Concatenation of 2 lists
Concatenated list: ['python programming', 'java complete reference', 'C', ' C++', 'C++ programming',
'C Programming']
Repetition of an item in list
python programmingpython programmingpython programming
Removing an item from list
Available books
['java complete reference', 'C', ' C++']
4.B. OPERATIONS OF TUPLE
AIM:
To write a python program to implement the operations of a tuple1.
ALOGIRTM
Step1: Start the program.
Step 2: Create a tuple1 named tuple1.
Step 3: Display the items in the tuple1.
Step 4: Create a new tuple1 and concatenate it with the existing tuple1.
Step 5: Repeat an item to a specified number of times.
Step6: Search the materials for construction of civil structure.
Step7:Stop the program.
PROGRAM:
print('operations of tuple1')
tuple1=('bricks','cement','steel')
print('Displaying the items in tuple1')
print('Materials required for construction of building:')
print(tuple1)
newtuple1=('sand','wood')
print('Concatenation of 2 tuples')
print('Concatenated tuple1: ',(tuple1+newtuple1))
print('Repetition of an item in tuple1')
print(3*'steel')
print('Searching the materials for construction of building')
if 'C' in tuple1:
print('present')
else:
print('not present')
RESULT:
Thus the python program was executed and verified successfully.
OUTPUT:
operations of tuple1
Displaying the items in tuple1
Materials required for construction of building:
('bricks', 'cement', 'steel')
Concatenation of 2 tuples
Concatenated tuple1: ('bricks', 'cement', 'steel', 'sand', 'wood')
Repetition of an item in tuple1
steelsteelsteel
Searching the materials for construction of building
not present
5.A. OPERATIONS OF SETS
AIM:
ALGORITHM:
Step 2: Creating a Set with the use of a List and print the result.
Step 3: Addition of Languages to the Set using Update operation and print the result.
Step 4: Removing languages from Set using Remove operation and print the result.
Step5: Find the Language present or not in Set using membership operation and print the result.
Step6: Apply Union operation on Set using “|” operator and print the result.
Step7: Apply Intersection operation on set using “&” operator and print the result.
PROGRAM
Programming languages
{'C', 'python', 'java', 'C++'}
not present
AIM:
ALGORITHM:
Step7: Apply Intersection operation on set using “&” operator and print the result.
PROGRAM
Updated Components:
{1: 'Engine', 2: 'Gearbox', 3: 'lights', 4: 'Battery'}
Accessing a Component using key:
Engine
AIM:
AIM:
def reversed_string(text):
if len(text) == 1:
return text
print(reversed_string("Python Programming!"))
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
!gnimmargorP nohtyP
7.B. PALINDROME
AIM:
def isPalindrome(s):
return s == s[::-1]
ans = isPalindrome(s)
if ans:
else:
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
AIM:
Program:
def count_chars(txt):
result = 0
return result
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
AIM:
Program:
print(string.replace("a", "A",1))
print(string.replace("a", "A"))
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
ALOGIRTM
Step1: Start the program
Step 2: import pandas as pd.
Step 3: creating a series as data.
Step 4: creating a series as data1
Step 5: print the series data and data1.
Step 6: Stop the program.
PROGRAM:
import pandas as pd
data = pd.Series([5, 2, 3,7], index=['a', 'b', 'c', 'd'])
data1 = pd.Series([1, 6, 4, 9], index=['a', 'b', 'd', 'e'])
print(data, "\n\n", data1)
RESULT:
Thus the python program was executed and verified successfully.
OUTPUT:
a 5
b 2
c 3
d 7
dtype: int64
a 1
b 6
d 4
e 9
dtype: int64
8(B). NUMPY LIBRARY MODULE
AIM:
ALOGIRTM
PROGRAM:
import numpy as np
data = np.array([1,3,4,7])
print(data)
RESULT:
OUTPUT:
[1 3 4 7]
8(C).MATPLOTLIB LIBRARY MODULE
AIM:
ALOGIRTM
PROGRAM:
OUTPUT:
8(D).SCIPY LIBRARY MODULE
AIM:
ALOGIRTM
PROGRAM:
import numpy as np
A = np.array([[1,2,3],[4,2,6],[7,3,9]])
from scipy import linalg
linalg.det(A)
RESULT:
OUTPUT:
6.0
9.A. COPY CONTENTS OF ONE FILE TO ANOTHER FILE
AIM:
To Copy contents of one file to another file
ALGORITHM:
STEP 1: Start
STEP 2: open both files
STEP 3: Add file name as argument
STEP 4: read content from first file
STEP 5: append content to secon
d file
STEP 6: Stop
PROGRAM:
with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
for line in firstfile:
secondfile.write(line)
RESULT:
FILE CREATION:
OUTPUT:
9.B.WORD COUNT
AIM:
To find the word and lines in command line arguments.
ALGORITHM:
STEP 1: Start
STEP 2: Add arguments to find the words and lines
STEP 3: Add file name as argument
STEP 4: Parse the arguments to get the values
STEP 5: Format and print the words
STEP 6: Stop
PROGRAM:
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
RESULT:
OUTPUT:
Enter file name: first.py
Number of words:
3
9.C. LONGEST WORD
AIM:
To write a python program to find longest word from file
ALGORITHM:
STEP 1: Start
STEP 2: Open text file say ‘s1.py’ in read mode using open function
STEP 3: Pass file name and access mode to open function
STEP 4: Read the whole content of text file using read function and store it in another variable say
‘str’
STEP 5: Use split function on str object and store words in variable say ‘words’
STEP 6: Find maximum word from words using len method
STEP 7: Iterate through word by word using for loop
STEP 8: Use if loop within for loop to check the maximum length of word
STEP 9: Store maximum length of word in variable say ‘longest_word’
STEP 10: Display longst_word using print function
STEP 11: Stop
PROGRAM:
fin = open("first.py","r")
str = fin.read()
words = str.split()
max_len = len(max(words, key=len))
for word in words:
if len(word)==max_len:
longest_word =word
print(longest_word)
RESULT:
Thus the python program was executed and verified successfully.
FILE CREATION:
OUTPUT:
welcome
10.A. DIVIDE BY ZERO ERROR
AIM
To write a python program to implement exception handling using devide by zero error.
Algorithm
step 1: Start
Step 2: Enter the inputs a and b
Step 3: Calculate (a+b)/(a-b) in try block
Step 4: if a equal to b try block throws an exception.
Step 5: The exception is caught and handled.
Step 6: stop
Program
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
RESULT:
OUTPUT:
Enter a=4
Enter b=4
a/b result in 0
10.B. VOTER’S AGE VALIDITY
AIM
To write a python program to implement exception handling using voter’s age validity.
Algorithm
step 1: Start
Step 2: Enter the age
Step 3: Check whether the age is less than 18.
Step 4: If less than 18 throw an exception
Step 5: The exception is caught and handled.
Step 6: stop
Program:
try:
c=a
#Raising Error
if c<18:
raise ValueError
#Handling of error
except ValueError:
else:
print (c)
RESULT:
OUTPUT:
20
10.C. STUDENT MARK RANGE VALIDATION
AIM
To write a python program to implement exception handling using Students mark range.
Algorithm
step 1: Start
Step 2: Enter the mark of student
Step 3: Check whether the mark is between 0 and 100
Step 4: if the range is not between 0 and 100 then throw an exception.
Step 5: The exception is caught and handled.
Step 6: stop
Program:
try:
c=a
#Raising Error
raise ValueError
#Handling of error
except ValueError:
else:
print (c)
RESULT:
OUTPUT:
90
11. EXPLORING PYGAME TOOL.
Pygame
o Pygame is a cross-platform set of Python modules which is used to create video games.
o It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
o Pygame was officially written by Pete Shinners to replace PySDL.
o Pygame is suitable to create client-side applications that can be potentially wrapped in a
standalone executable.
Pygame Installation
Install pygame in Windows
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1 or
above version because it is much friendlier to beginners, and additionally runs faster. There are
mainly two ways to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what python
uses to install packages). The command is the following:
2. Installing through an IDE: The second way is to install it through an IDE and here we are using
Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can install it by running
the above command in the terminal or use the following steps:
import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
12.A. SIMULATE BOUNCING BALL USING PYGAME
AIM:
To write a python program to simulate bouncing ball using pygame.
PROGRAM/SOURCE CODE :
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT
RESULT:
Thus the program to simulate bouncing ball using pygameis executed and the output is
obtained.
12.B. SIMULATE CAR RACE USING PYGAME
AIM:
To write a python program to simulate car race using pygame.
PROGRAM/SOURCE CODE :
import random
import pygame
class CarRacing:
def __init__(self):
pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.clock = pygame.time.Clock()
self.gameDisplay = None
self.initialize()
def initialize(self):
self.crashed = False
self.carImg = pygame.image.load('.\\img\\car.png')
self.car_width = 49
# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100
# Background
self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0
def racing_window(self):
pygame.display.set_caption('Car Dodge')
self.run_car()
def run_car(self):
if event.type == pygame.QUIT:
self.crashed = True
# print(event)
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
self.car_x_coordinate -= 50
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
self.gameDisplay.fill(self.black)
self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed
self.enemy_car_starty = 0 - self.enemy_car_height
self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
self.count += 1
self.enemy_car_speed += 1
self.bg_speed += 1
self.crashed = True
self.crashed = True
pygame.display.update()
self.clock.tick(60)
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
def back_ground_raod(self):
self.bg_y1 += self.bg_speed
self.bg_y2 += self.bg_speed
self.bg_y1 = -600
self.bg_y2 = -600
def display_credit(self):
if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT
RESULT: