Python Lab Assignment Manual
Python Lab Assignment Manual
Page 1
Date: 1.A. Electricity Billing
Aim
To write a python program for the Electricity Billing.
Algorithm
Step 1: Start the program
Step 2: Read the input variable
“unit” Step 3: Process the following
When the unit is less than or equal to 100 units, calculate usage=unit*5
When the unit is between 100 to 200 units, calculate usage=(100*5)+((unit-100)*7)
When the unit is between 200 to 300 units, calculate usage=(100*5)+(100*7)+((unit- 200)*10)
When the unit is above 300 units, calculate usage=(100*5)+(100*7)+(100*!0)+((unit- 300)*15)
For further, no additional charge will be calculated.
Step 4: Display the amount “usage” to the user.
Step 5: Stop the program
Flowchart
Page 2
Program
unit = int(input("Please enter Number of Unit you Consumed :
")) if(unit <= 100):
usage = unit * 5
elif(unit <= 200):
usage=(100*5)+((unit-100)*7)
elif(unit <= 300):
usage=(100*5)+(100*7)+((unit-200)*10)
else:
usage=(100*5)+(100*7)+(100*10)+((unit-300)*15)
print("Electricity Bill = %.2f" %usage)
print("Note: No additional charge will be calculated")
Output
Please enter Number of Unit you consumed: 650
Electricity Bill = 7450.00
Note: No additional charge will be calculated
Result
Thus the Electricity Billing program has been executed and verified successfully.
Page 3
Date: 1.B.Retail Shop Billing
Aim
To write a python program for the Retail Shop Billing.
Algorithm
Step 1: Start the program
Step 2: Initialize the values of the items
Step 3: Read the input like the name of item and quantity.
Step 4: Process the following amount=(item_name*quantity)
+amount
Step 5: Repeat the step4 until the condition get
fails. Step 6: Display the value of “amount”.
Step 7: Stop the program.
Flowchart
Page 4
Program
print("Welcome to Varnika Retail
Shopping") print("List of items in our
market")
soap=60; powder=120; tooth_brush=40; paste=80;
perfume=250 amount=0
print("1.Soap\n2.Powder\n3.Tooth Brush\n4.Tooth Paste\n5.Perfume")
print("To Stop the shopping type number 0")
while(1):
item=int(input("Enter the item
number:")) if(item==0):
break
else:
if(item<=5):
quantity=int(input("Enter the quantity:"))
if(item==1):
amount=(soap*quantity)+amount
elif(item==2):
amount=(powder*quantity)+amount
elif(item==3):
amount=(tooth_brush*quantity)+amount
l3.append(amount)
elif(item==4):
amount=(paste*quantity)+amount
elif(item==5):
amount=(perfume*quantity)+amount
else:
print("Item Not available")
print("Total amount need to pay
is:",amount) print("Happy for your visit")
Page 5
Output
Welcome to Varnika Retail Shopping
List of items in our market
1. Soap
2.Powder
3.Tooth Brush
4.Tooth Paste
5.Perfume
To Stop the shopping type number 0
Enter the item number:1
Enter the quantity:5
Enter the item
number:2 Enter the
quantity:4 Enter the
item number:0
Total amount need to pay is:
780 Happy for your visit
Result
Thus the Retail Shopping Billing program has been executed and verified successfully.
Page 6
Date: 1.C. Sin Series
Aim
To write a python program for sin series.
Algorithm
Step 1: Start the program.
Step 2: Read the input like the value of x in radians and n where n is a number up to which we
want to print the sum of series.
Step 3: For first term,
x=x*3.14159/180
t=x;
sum=x
Step 4: For next term,
t=(t*(-1)*x*x)/(2*i*(2*i+1))
sum=sum+t;
# The formula for the 'sin x' is represented as
# sin x= x-x3/3!+x5/5!-x7/7!+x9/9! (where x is in radians)
Step 5: Repeat the step4, looping 'n’' times to get the sum of first 'n' terms of the series.
Step 6: Display the value of sum.
Step 7: Stop the program.
Page 7
Flowchart
Program:
x=float(input("Enter the value for x : "))
a=x
n=int(input("Enter the value for n : "))
x=x*3.14159/180
t=x;
sum=x
for i in range(1,n+1):
t=(t*(-1)*x*x)/(2*i*(2*i+1))
sum=sum+t;
print("The value of Sin(",a,")=",round(sum,2))
Page 8
Output
Enter the value for x : 30
Enter the value for n : 5
The value of Sin( 30.0 )= 0.5
Result
Thus the sine series program has been executed and verified successfully.
Page 9
Date: 1.D. Weight of a
Motorbike Aim
To write a python program to find the weight of a motorbike.
Algorithm
Step 1: Start the program
Step 2: Initialize values to the parts of the motorbike in weights(Chassis, Engine, Transmissions,
Wheels, Tyres, Body panels, Mud guards, Seat, Lights)
Step 3: Process the following weight = weight+sum_motorbike[i]
Step 4: Repeat the step 3, looping 'n’' times to get the sum of weight of the vehicle
Step 5: Display the Parts and Weights of the motor bike
Step 6: Display “Weight of
theMotorbike” Step 7: Stop the program.
Flowchart
Page 10
Program
sum_motorbike = {"Chassis" : 28, "Engine" : 22, "Transmissions" : 18, "Wheels" : 30, "tyres" :
15, "Body_Panels" : 120, "Mudguards" : 6, "Seat" : 10, "lights": 10}
weight = 0
for i in sum_motorbike:
weight = weight+sum_motorbike[i]
print("Parts and weights of the Motorbike")
for i in sum_motorbike.items():
print(i)
print("\nWeight of the Motorbike is:",weight)
Output
Parts and weights of the
Motorbike ('Chassis', 28)
('Engine', 22)
('Transmissions', 18)
('Wheels', 30)
('tyres', 15)
('Body_Panels', 120)
('Mudguards', 6)
('Seat', 10)
('lights', 10)
Weight of a Motorbike is: 259
Result
Thus the weight of the motorbike program has been executed and verified successfully.
Page 11
Date: 1.E. Weight of a steel
bar Aim
To write a python program to find the weight of a steel bar.
Algorithm
Weight of steel bar = (d2 /162)*length (Where d-diameter value in mm and length value in m)
Step 1: Start the program.
Step 2: Read the values of the variable d and length.
Step 4: Process the following weight=(d2 /162kg/m)*length
Step 5: Display the value of weight.
Step 6: Stop the program.
Flowchart
Page 12
Program
d=int(input("Enter the diameter of the steel bar in milli meter: " ))
length=int(input("Enter the length of the steel bar in meter: " ))
weight=((d**2)/162)*length
print("Weight of steel bar in kg per meter :", round(weight,2))
Output
Enter the diameter of the steel bar in milli meter:
6 Enter the length of the steel bar in meter: 3
Weight of steel bar in kg per meter : 0.67
Result
Thus the weight of the steel bar program has been executed and verified successfully.
Page 13
Date: 1.F. Compute Electrical Current in Three Phase AC
Circuit Aim
To write a python program to compute the Electrical Current in Three Phase AC Circuit.
Algorithm
Step 1: Start the program
Step 2: Import math header file for finding the square root of
3 Step 3: Read the values of pf, I and V.
Step 4: Process the following:
Perform a three phase power calculation using the following formula: P=√3 * pf * I * V
Where pf - power factor, I - current, V - voltage and P – power
Step 5: Display “The result is
P”. Step 6: Stop the program.
Flowchart
Page 14
Program
import math
pf=float(input("Enter the Power factor pf (lagging): " ))
I=float(input("Enter the Current I: " ))
V=float(input("Enter the Voltage V: " ))
P=math.sqrt(3)*pf*I*V
print("Electrical Current in Three Phase AC Circuit :", round(P,3))
Output
Enter the Power factor pf (lagging): 0.8
Enter the Current I: 1.7
Enter the Voltage V: 400
Electrical Current in Three Phase AC Circuit : 942.236
Result
Thus the Electrical Current in Three Phase AC Circuit program has been executed and verified
successfully.
Page 15
2. Python programming using
simple statements and
expressions
Page 16
Date: 2.A. Exchange the values of two
variables Aim
To write a python program to exchange the values of two variables.
Algorithm
Step 1: Start the program
Step 2: Read the values of two variables
Step 3: Print the values of the two variables before
swapping. Step 4: Process the following
Swapping of two variables using tuple assignment
operator. a,b=b,a
Step 5: Display the values of the two variables after swapping.
Step 6: Stop the program.
Program
#with temporary variable
print("Swapping two values")
a=int(input("Enter the value of A: "))
b=int(input("Enter the value of B: "))
print("Before Swapping\nA value is:",a,"B value
is:",b) c=a #with temporary variable
a=b
b=c
print("After Swapping\nA value is:",a,"B value is:",b)
Page 17
#Tuple assignment
print("Swapping two values")
a=int(input("Enter the value of A: "))
b=int(input("Enter the value of B: "))
print("Before Swapping\nA value is:",a,"B value
is:",b) a,b=b,a #Tuple assignment
print("After Swapping\nA value is:",a,"B value is:",b)
Output
Swapping two values
Enter the value of A: 65
Enter the value of B: 66
Before Swapping
A value is: 65 B value is: 66
After Swapping
A value is: 66 B value is: 65
Result
Thus the exchange the values of two variables program has been executed and verified
successfully.
Page 18
Date: 2.B. Circulate the values of n
variables Aim
To write a python program to circulate the values of n variables
Algorithm
Step 1: Start the program
Step 2: Read the values of two variables
Step 3: Display the values of the two variables before swapping.
Step 4: Process the following
Swapping of two variables using tuple assignment
operator. a,b=b,a
Step 5: Display the values of the two variables after swapping.
Step 6: Stop the program.
Program
print("Circulate the values of n
variables") list1=[10,20,30,40,50]
print("The given list is: ",list1)
n=int(input("Enter how many circulations are required:
")) circular_list=list1[n:]+list1[:n]
print("After",n,"circulation is: ",circular_list)
Output
Circulate the values of n variables
The given list is: [10, 20, 30, 40, 50]
Enter how many circulations are required: 3
After %f circulation is: [40, 50, 10, 20, 30]
Page 19
Program
from collections import deque
lst=[1,2,3,4,5]
d=deque(lst)
print d
d.rotate(2)
print d
Output
deque([1, 2, 3, 4, 5])
deque([4, 5, 1, 2, 3])
Result
Thus circulate the values of n variables program has been executed and verified successfully.
Page 20
Date: 2.C. Distance between two points
Aim
To write a python program to find the distance between two points
Algorithm
Step 1: Start the program
Step 2: Read the values of two points (x1,y1,x2,y2)
Step 3: Process the following
Result=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
Step 4: Display the result of distance between two points.
Step 5: Stop the program.
Program
import math
print("Enter the values to find the distance between two
points") x1=int(input("Enter X1 value: "))
y1=int(input("Enter Y1 value: "))
x2=int(input("Enter X2 value: "))
y2=int(input("Enter Y2 value: "))
Result=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance between two
points:",int(Result))
Page 21
Output
Enter the values to find the distance between two
points Enter X1 value: 2
Enter Y1 value: 4
Enter X2 value: 4
Enter Y2 value: 8
Distance between two points: 4
Result
Thus the distance between two points program has been executed and verified successfully.
Page 22
3. Scientific problems using Conditionals and
Iterative loops
Page 23
Date: 3.A. Number Series
Aim
To write a python program for the Number Series
a. Fibonacci sequence: 0 1 1 2 3 5 8 13 21
34 Algorithm
Step 1: Start the program
Step 2: Read the number of terms n
Step 3: Initialize f1 = -1, f2 = 1
Step 4: Process the following from i=0 to n
times f3=f1+f2
Display f3
Do the tuple assignment f1,f2=f2,f3
Step 5: Stop the program.
Program
print("Program for Number Series : Fibanacci
Sequence") n=int(input("How many terms? "))
f1=-1
f2=1
for i in range(n):
f3=f1+f2
print(f3,end=" ")
f1,f2=f2,f3
Output
Program for Number Series : Fibanacci
Sequence How many terms? 10
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Page 24
b. Number Series: 12+22+…+n2
Algorithm
Step 1: Start the program
Step 2: Read the number of terms n
Step 3: Initialize sum=0
Step 4: Process the following from i=1 to n+1 times
Sum = sum + i**2
Output
Program for Number Series :
How many terms? 5
The sum of series = 55
Result
Thus the number series program has been executed and verified successfully.
Page 25
Date: 3.B. Number Patterns
Aim
To write a python program for the Number Patterns
a. Number Pattern_Type
1 Algorithm
Step 1: Start the program
Step 2: Read the number of rows
Step 3: Process the following from i=1 to rows+1 times
Step 3a: Process the following from j=0 to i
times
Display i
Step 4: Stop the program.
Program
print("Program for Number Pattern")
rows=int(input("Enter the number of rows: "))
for i in range(1,rows+1):
for j in range(0,i):
print(i,end=" ")
print(" ")
Output
Program for Number Pattern
Enter the number of rows: 5
1
22
333
4444
55555
Page 26
b. Number Pattern_Type
2 Algorithm
Step 1: Start the program
Step 2: Read the number of rows
Step 3: Process the following from i=1 to rows+1 times
Step 3a: Process the following from j=1 to i+1 times
Display j
Step 4: Stop the
program.
Program
b. Number Pattern
print("Program for Number Pattern")
rows=int(input("Enter the number of rows: "))
for i in range(1,rows+1):
for j in
range(1,i+1):
print(j,end=" ")
print(" ")
Output
Program for Number Pattern
Enter the number of rows: 5
1
12
123
1234
12345
Result
Thus the number patterns programs have been executed and verified successfully.
Page 27
Date: 3.C. Pyramid Patterns
Aim
To write a python program for the Pyramid Patterns
Algorithm
Step 1: Start the program
Step 2: Read the number of rows
Step 3: Process the following from i=1 to rows+1 times
Step 3a: Process the following from space=1 to(rows- i)+1 times
Display empty space
Step 3b: Process the following from j=0 to 2*i-1 times
Display ‘*’
Step 4: Stop the program.
Program
Pyramid pattern
rows = int(input("Enter number of rows: "))
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
for j in range(0,2*i-
1): print("* ",
end="")
print()
Output
Program for Pyramid Pattern
Enter the number of rows: 4
*
***
*****
*******
Result
Thus the pyramid pattern program has been executed and verified successfully.
Page 28
4. Implementing
real-time/technical applications
using Lists, Tuples
Page 29
AIM:
To implement the Real-time / Technical application of program using List & Tuples concept applied in
python code.
library Algorithm
Program
print("Welcome to Varnika Advanced
Library") print(" ")
Library=["Books","e-
Books","Journals","Audiobooks","Manuscripts","Maps","Prints","Periodicals","Newspapers"]
for i in Library:
print(i)
print(" ")
print(Library)
Library.remove("Prints")
print(Library)
Library.pop(4)
print(Library)
Library.clear()
print(Library)
Library.append("CD’s")
print(Library)
Library.insert(0,"DVD's")
Page 30
print(Library)
print(Library.index("DVD's"))
del Library[0:1]
print(Library)
Output
Welcome to Varnika Advanced Library
Books
e-Books
Journals
Audiobooks
Manuscripts
Maps
Prints
Periodicals
Newspapers
['Books', 'e-Books', 'Journals', 'Audiobooks', 'Manuscripts', 'Maps', 'Prints', 'Periodicals',
'Newspapers']
['Books', 'e-Books', 'Journals', 'Audiobooks', 'Manuscripts', 'Maps', 'Periodicals', 'Newspapers']
['Books', 'e-Books', 'Journals', 'Audiobooks', 'Maps', 'Periodicals', 'Newspapers']
[]
['CD’s']
["DVD's", 'CD’s']
0
['CD’s']
4.B. Components of a
car Program
print("Components of a
car") print(" ")
Main_parts=["Chassis","Engine","Auxiliaries"]
Transmission_System=["Clutch","Gearbox", "Differential","Axle"]
Body=["Steering system","Braking system"]
print("Main Parts of the Car:",Main_parts)
print("Transmission systems of the Car:",Transmission_System)
print("Body of the Car:",Body)
total_parts=[]
total_parts.extend(Main_parts)
total_parts.extend(Transmission_System)
total_parts.extend(Body)
print(" ")
print("Total components of the
car:",len(total_parts)) print(" ")
total_parts.sort()
j=0
for i in total_parts:
j=j+1
print(j,i)
Page 31
Output
Components of a car
Main Parts of the Car: ['Chassis', 'Engine', 'Auxiliaries']
Transmission systems of the Car: ['Clutch', 'Gearbox', 'Differential', 'Axle']
Body of the Car: ['Steering system', 'Braking system']
Total components of the car: 9
1 Auxiliaries
2 Axle
3 Braking system
4 Chassis
5 Clutch
6 Differential
7 Engine
8 Gearbox
9 Steering system
Output
Page 32
Materials required for construction of a
building Approximate Price:
1.Cement:16%
2.Sand:12%
3.Aggregates:8%
4.Steel bars:24%
5.Bricks:5%
6.Paints:4%
7.Tiles:8%
8.Plumbing items:5%
9.Electrical items:5%
10.Wooden products:10%
11.Bathroom accessories:3%
Cement/Bag : 410
Sand/Cubic feet : 50
Aggregates/Cubic feet : 25
Steel bars/Kilogram : 57
Bricks/Piece : 7
Paints/Litres : 375
Tiles/Squre feet : 55
Plumbing items/meter or piece : 500
Electrical items/meter or piece : 500
Wooden products/square feet : 1000
Bathroom accessories/piece : 1000
Cement/Bag : 500
Sand/Cubic feet : 50
Aggregates/Cubic feet : 25
Steel bars/Kilogram : 57
Bricks/Piece : 7
Paints/Litres : 375
Tiles/Squre feet : 55
Plumbing items/meter or piece : 500
Electrical items/meter or piece : 500
Wooden products/square feet : 1000
Bathroom accessories/piece : 1000
Operations of
tuple/list 7
1000
11
4069
[7, 25, 50, 55, 57, 375, 500, 500, 500, 1000, 1000]
True
True
Result
Thus the Real-time / Technical application of program using List & Tuples concept were executed and
verified successfully.
Page 33
5.Implementing real-time/technical
applications using Sets,
Dictionaries.
Page 34
AIM:
To implement the real –time / technical applications using st & Dictionaries of library file concepts
construct through python code.
5.A. Language
Program
LANGUAGE1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};
LANGUAGE2 = {'Grammar', 'Syllabus', 'Context', 'Words',
'Phonetics'}; # set union
print("Union of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE1 | LANGUAGE2)
# set intersection
print("Intersection of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE1 &
LANGUAGE2)
# set difference
print("Difference of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE1 - LANGUAGE2)
print("Difference of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE2 - LANGUAGE1)
# set symmetric difference
print("Symmetric difference of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE1 ^
LANGUAGE2)
Output
Union of LANGUAGE1 and LANGUAGE2 is {'Pitch', 'Syllabus', 'Phonetics', 'Script',
'Words', 'Grammar', 'Sentences', 'Context'}
Intersection of LANGUAGE1 and LANGUAGE2 is {'Syllabus', 'Grammar'}
Difference of LANGUAGE1 and LANGUAGE2 is {'Pitch', 'Sentences', 'Script'}
Difference of LANGUAGE1 and LANGUAGE2 is {'Context', 'Words', 'Phonetics'}
Symmetric difference of LANGUAGE1 and LANGUAGE2 is {'Pitch', 'Script', 'Words',
'Phonetics', 'Sentences', 'Context'}
5.B. Components of an
automobile Program
print("Components of an automobile")
print("\n")
print("Dictionary keys")
print(" ")
components={"Engine parts":["piston","cylinder head","oil pan","engine valves","combustion
chamber","gasket"],"Drive transmission and steering parts":["Adjusting nut","pitman arm
shaft","roller bearing","steering gear shaft"],"Suspension and brake parts":["Break pedal","Brake
lines","Rotors/drums","Break pads","Wheel cylinders"],"Electrical parts":
["Battery","Starter","Alternator","Cables"],"Body and chassis":["Roof panel","front panel","screen
pillar","Lights","Tyres"]}
for i in components.keys():
print(i)
print("\n")
Page 35
print("Dictionary values")
print(" ")
for i in components.values():
print(i)
print("\n")
print("Dictionary items")
print(" ")
for i in components.items():
print(i)
print("\n")
accessories={"Bumper":["front","back"]}
components.update(accessories)
components['Bumper']=["front and back"]
print("Dictionary items")
print(" ")
for i in components.items():
print(i)
print("\n")
print(len(components))
del components["Bumper"]
components.pop("Electrical parts")
components.popitem()
print("\n")
print("Dictionary items")
print(" ")
for i in components.items():
print(i)
components.clear();
print(components)
Output
Components of an automobile
Dictionary keys
Engine parts
Drive transmission and steering
parts Suspension and brake parts
Electrical parts
Body and chassis
Dictionary values
['piston', 'cylinder head', 'oil pan', 'engine valves', 'combustion chamber', 'gasket']
['Adjusting nut', 'pitman arm shaft', 'roller bearing', 'steering gear shaft']
['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads', 'Wheel
cylinders'] ['Battery', 'Starter', 'Alternator', 'Cables']
Page 36
['Roof panel', 'front panel', 'screen pillar', 'Lights', 'Tyres']
Page 37
Dictionary items
('Engine parts', ['piston', 'cylinder head', 'oil pan', 'engine valves', 'combustion chamber', 'gasket'])
('Drive transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing',
'steering gear shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads', 'Wheel
cylinders'])
('Electrical parts', ['Battery', 'Starter', 'Alternator', 'Cables'])
('Body and chassis', ['Roof panel', 'front panel', 'screen pillar', 'Lights', 'Tyres'])
Dictionary items
('Engine parts', ['piston', 'cylinder head', 'oil pan', 'engine valves', 'combustion chamber', 'gasket'])
('Drive transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing',
'steering gear shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads', 'Wheel
cylinders'])
('Electrical parts', ['Battery', 'Starter', 'Alternator', 'Cables'])
('Body and chassis', ['Roof panel', 'front panel', 'screen pillar', 'Lights', 'Tyres'])
('Bumper', ['front and back'])
Dictionary items
('Engine parts', ['piston', 'cylinder head', 'oil pan', 'engine valves', 'combustion chamber', 'gasket'])
('Drive transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing',
'steering gear shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads', 'Wheel
cylinders'])
Program
print("Elements of a civil
structure") print(" ")
print("1.foundation \n2.floors \n3.walls \n4.beams and slabs \n5.columns \n6.roof
\n7.stairs\n8.parapet\n9.lintels\n10.Damp proof")
elements1={"foundation","floors","floors","walls","beams and
slabs","columns","roof","stairs","parapet","lintels"} print("\
n")
print(elements1)
print("\n")
elements1.add("damp proof") #add
print(elements1)
elements2={"plants","compound"}
print("\n")
print(elements2)
print("\n")
Page 38
elements1.update(elements2) #extending
print(elements1)
elements1.remove("stairs") #data removed, if item not present raise error
print(elements1)
elements1.discard("hard floor") #data removed,if item not present not raise error
print(elements1)
elements1.pop()
print(elements1)
print(sorted(elements1))
print("\n")
print("set operations")
s1={"foundation","floors"}
s2={"floors","walls","beams"}
print(s1.symmetric_difference(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.intersection(s2))
print(s1.union(s2))
Output
Elements of a civil structure
1.foundation
2.floors
3.walls
4.beams and
slabs 5.columns
6.roof
7.stairs
8. parapet
9.lintels
10.Damp proof
{'stairs', 'floors', 'roof', 'walls', 'columns', 'lintels', 'foundation', 'beams and slabs', 'parapet'}
{'stairs', 'floors', 'roof', 'walls', 'columns', 'lintels', 'foundation', 'damp proof', 'beams and slabs',
'parapet'}
{'compound', 'plants'}
{'stairs', 'floors', 'roof', 'plants', 'walls', 'columns', 'compound', 'lintels', 'foundation', 'damp proof',
'beams and slabs', 'parapet'}
{'floors', 'roof', 'plants', 'walls', 'columns', 'compound', 'lintels', 'foundation', 'damp proof', 'beams
Page 39
and slabs', 'parapet'}
{'floors', 'roof', 'plants', 'walls', 'columns', 'compound', 'lintels', 'foundation', 'damp proof', 'beams
and slabs', 'parapet'}
{'roof', 'plants', 'walls', 'columns', 'compound', 'lintels', 'foundation', 'damp proof', 'beams and
slabs', 'parapet'}
['beams and slabs', 'columns', 'compound', 'damp proof', 'foundation', 'lintels', 'parapet', 'plants',
'roof', 'walls']
set operations
{'foundation', 'beams', 'walls'}
{'foundation'}
{'beams', 'walls'}
{'floors'}
{'floors', 'beams', 'foundation', 'walls'}
RESULT:
Thus the real –time / technical applications using st & Dictionaries of library file concepts construct through
python code was executed successfully.
Page 40
6. Implementing programs using Functions.
Page 41
AIM:
To implement the real –time / technical applications using functions construct through python code.
6.A. Factorial
Program
def factorial(num): #function
definition fact=1
for i in range(1,num+1):
fact=fact*i
return fact
number=int(input("Please enter any number to find the factorial:"))
result=factorial(number) #function calling
print("Using functions - The factorial of %d = %d" %(number,result))
Output
Please enter any number to find the
factorial:6 Using functions - The factorial of
6 = 720
list Program
def myMax(list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi=x
return maxi
def myMax(list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi=x
return maxi
Output
Largest element in the list is: 500
Page 42
6.C. Area of shape
Program
def calculate_area(name):
name=name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth:
"))
# calculate area of
triangle tri_area = 0.5 * b
*h
print(f"The area of triangle is {tri_area}.")
# calculate area of
circle circ_area = pi * r
*r
print(f"The area of circle is {circ_area}.")
# calculate area of
parallelogram para_area = b * h
Page 43
print(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
Page 44
print("Calculate Shape Area:\nRectangle\nSquare\nTriangle\nCircle\nParallelogram")
shape_name=input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output
Calculate Shape Area:
Rectangle
Square
Triangle
Circle
Parallelogram
Enter the name of shape whose area you want to find:
Triangle Enter triangle's height length: 10
Enter triangle's breadth length: 5
The area of triangle is 25.0.
RESULT:
Thus the real –time / technical applications using functions construct through python code were executed
successfully.
Page 45
7. Implementing programs using Strings.
(reverse, palindrome, character count, replacing characters)
Page 46
AIM:
To implement the real –time / technical applications using string concepts construct through python code.
Program
def rev(string):
string="".join(reversed(string))
return string
Output
Enter any string:Varnika
The Original String is:Varnika
The reversed string (using reversed function) is:akinraV
7.B. Palindrome
Program
string=input("Enter the string:")
string=string.casefold()
print(string)
rev_string=reversed(string)
if(list(string)==list(rev_string)):
print(f"Given string {string} is
Palindrome.") else:
print(f"Given string {string} is not Palindrome.")
Output
Enter the string:
Amma amma
Given string amma is Palindrome.
Page 47
7.C. Character count
Program
string=input("Enter the string:")
print("Total characters in the given string is",len(string))
char=input("Enter a character to count:")
val=string.count(char)
print(val,"\n")
Output
Enter the string:Megavarnika
Total characters in the given string is
11 Enter a character to count:a
3
Program
string=input("Enter the string:")
str1=input("Enter old string:")
str2=input("Enter replacable string:")
print(string.replace(str1,str2))
Output
Enter the string:Problem Solving and Python
Programming Enter old string:Python
Enter replacable string:Java
Problem Solving and Java Programming
RESULT:
Thus the real –time / technical applications using string concepts construct through python code.
Were implemented successfully.
Page 48
8. Implementing programs using
written modules and Python Standard
Libraries
(numpy, pandas, Matplotlib, scipy)
Page 49
AIM:
To implement the real –time / technical applications using file handling concepts construct through python
code.
8.A. Numpy
Program
#1D array
import numpy as np
arr=np.array([10,20,30,40,50])
print("1 D array:\n",arr)
print(" ")
#2D array (matrix)
import numpy as
np
arr = np.array([[1,2,3], [4,5,6]])
print("\n2 D array:\n",arr)
print("\n2nd element on 1st row is: ",
arr[0,1]) print(" ")
#3D array
(matrices) import
numpy as np
arr = np.array([[[1,2,3], [4,5,6]], [[1,2,3], [4,5,6]]])
print("\n3 D array:\n",arr)
print("\n3rd element on 2nd row of the 1st matrix is",arr[0,1,2])
Output
1 D array:
[10 20 30 40 50]
2 D array:
[[1 2 3]
[4 5 6]]
3 D array:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Page 50
3rd element on 2nd row of the 1st matrix is 6
Page 51
8.B. Pandas
Program
import pandas
mydata=['a','b','c','d','e']
myvar=pandas.Series(mydata)
print(myvar)
print("\n")
mydataset={'cars':["BMW","Volvo","Ford"], 'passings':[3,7,2]}
print(mydataset)
myvar=pandas.DataFrame(mydataset)
print(myvar)
Output
0 a
1 b
2 c
3 d
4 e
dtype: object
8.C. Scipy
1.Program
from scipy import constants
print(constants.minute)
print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)
print(constants.Julian_year)
print(constants.kilo) #printing the kilometer unit (in meters)
print(constants.gram) #printing the gram unit (in kilograms)
print(constants.mph) #printing the miles-per-hour unit (in meters per seconds)
print(constants.inch)
Page 52
1. Output
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
1000.0
0.001
0.44703999999999994
0.0254
2. Program
import numpy as np
from scipy import io as
sio array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat("example.mat", struct_as_record=True)
data['ar']
2.Output
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
8.D. Matplotlib
1.Program
import matplotlib.pyplot as plt
import numpy as np
plt.plot([-1,-4.5,16,23])
plt.show()
plt.plot([10,200,10,200,10,200,10,200])
plt.show()
xpoints=np.array([0,6])
ypoints=np.array([0,250])
plt.plot(xpoints,ypoints)
plt.show()
Page 53
1. Output
Page 54
2. Program
from scipy import misc
from matplotlib import pyplot as plt
import numpy as np
#get face image of panda from misc package
panda = misc.face()
#plot or show image of face
plt.imshow( panda )
plt.show()
2. Output
RESULT:
Thus the real –time / technical applications using file handling concepts construct through python code.was
implemented sucessfully
Page 55
9. Implementing
real-time/technical applications
using File handling.
(copy from one file to another, word count, longest word)
Page 56
AIM:
To implement the real –time / technical applications using file handling concepts construct through python
code.
Program
Output
Source File Name: mega.txt
Hello India
9.B. Word
count Program
file=open("mega.txt","r")
data=file.read()
words=data.split()
print("Number of words in text file:",len(words))
Output
Source File Name: mega.txt
Hello India
Page 57
9.C. Longest word
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] file_name=input("Enter the file
name:") print(longest_word(file_name))
Output
Source File Name: mega.txt
Welcome to India
RESULT:
Thus the real –time / technical applications using file handling concepts construct through python code was
implemented and executed successfully.
Page 58
10. Implementing real-time/technical
applications using Exception handling
Page 59
AIM:
To implement the real –time / technical applications using exception handling concepts construct through
python code.
Program
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of
b:")) try:
c=a/b
print("Divide a / b:",c)
except ZeroDivisionError:
print("Found Divide by Zero Error!")
Output
Enter the value of
a:50 Enter the value
of b:0
Found Divide by Zero Error!
validity Program
try:
age=int(input("Enter your age:"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except ValueError as err:
print(err)
finally:
print("Thank you")
Output
Page 60
Enter your age:17
Not eligible to vote
Thank you
Page 61
10.C. Student mark range validation
Program
try:
python=int(input("Enter marks of the Python subject:
")) print("Python Subject Grade",end=" ")
if(python>=90):
print("Grade: O")
elif(python>=80 and python<90):
print("Grade: A+")
elif(python>=70 and python<80):
print("Grade: A")
elif(python>=60 and python<70):
print("Grade: B+")
elif(python>=50 and python<60):
print("Grade: B")
else:
print("Grade: U")
except:
print("Entered data is wrong, Try
Again") finally:
print("Thank you")
Output
Enter marks of the Python subject: 95
Python Subject Grade Grade: O
Thank you
Page 62