50% found this document useful (4 votes)
5K views

Python Lab Manual - 25.02.2022

The document contains code and explanations for solving several simple real-life problems using Python programs. These include: 1. An electricity billing program that calculates a bill based on electricity units consumed. 2. A retail shop billing program that calculates a total bill from items purchased. 3. A program to calculate the sum of terms in a sine series for a given value of x and number of terms. 4. Programs to calculate the weight of a motorbike and steel bar based on their parts/dimensions. The programs demonstrate developing flowcharts and Python code to solve technical problems by reading inputs, performing calculations, and displaying outputs. Algorithms and step-by-step workings are provided for each problem

Uploaded by

vengai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
50% found this document useful (4 votes)
5K views

Python Lab Manual - 25.02.2022

The document contains code and explanations for solving several simple real-life problems using Python programs. These include: 1. An electricity billing program that calculates a bill based on electricity units consumed. 2. A retail shop billing program that calculates a total bill from items purchased. 3. A program to calculate the sum of terms in a sine series for a given value of x and number of terms. 4. Programs to calculate the weight of a motorbike and steel bar based on their parts/dimensions. The programs demonstrate developing flowcharts and Python code to solve technical problems by reading inputs, performing calculations, and displaying outputs. Algorithms and step-by-step workings are provided for each problem

Uploaded by

vengai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

1.

Identification and solving of simple real


life or scientific or technical problems,
and
Developing flow charts for the same.

(Electricity Billing, Retail shop billing, Sin series, weight of


a motorbike, Weight of a steel bar, compute Electrical
Current in Three Phase AC Circuit)

VSBEC-IT 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

VSBEC-IT 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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the Electricity Billing program has been executed and verified successfully.

VSBEC-IT 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

VSBEC-IT 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")

VSBEC-IT 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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result

VSBEC-IT Page 6
Thus the Retail Shopping Billing program has been executed and verified successfully.

VSBEC-IT Page 7
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.

VSBEC-IT Page 8
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))

VSBEC-IT Page 9
Output
Enter the value for x : 30
Enter the value for n : 5
The value of Sin( 30.0 )= 0.5

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the sine series program has been executed and verified successfully.

VSBEC-IT Page 10
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

VSBEC-IT Page 11
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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the weight of the motorbike program has been executed and verified successfully.

VSBEC-IT Page 12
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

VSBEC-IT Page 13
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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the weight of the steel bar program has been executed and verified successfully.

VSBEC-IT Page 14
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

VSBEC-IT Page 15
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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the Electrical Current in Three Phase AC Circuit program has been executed and verified
successfully.

VSBEC-IT Page 16
2. Python programming using
simple statements and
expressions

(Exchange the values of two variables, circulate the values of


n variables, distance between two points).

VSBEC-IT Page 17
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)

#without 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) a=a+b #without temporary variable
b=a-b
a=a-b
print("After Swapping\nA value is:",a,"B value is:",b)

VSBEC-IT Page 18
#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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the exchange the values of two variables program has been executed and verified
successfully.

VSBEC-IT Page 19
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]

VSBEC-IT Page 20
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])

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus circulate the values of n variables program has been executed and verified successfully.

VSBEC-IT Page 21
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))

VSBEC-IT Page 22
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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the distance between two points program has been executed and verified successfully.

VSBEC-IT Page 23
3. Scientific problems using Conditionals and
Iterative loops

(Number series, Number Patterns, pyramid pattern)

VSBEC-IT Page 24
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

VSBEC-IT Page 25
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

Step 5: Display sum


Step 6: Stop the program.
Program
print("Program for Number Series")
n=int(input("How many terms? "))
sum=0
for i in
range(1,n+1):
sum+=i**2
print("The sum of series = ",sum)

Output
Program for Number Series :
How many terms? 5
The sum of series = 55

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the number series program has been executed and verified successfully.
VSBEC-IT Page 26
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

VSBEC-IT Page 27
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

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

VSBEC-IT Page 28
Result
Thus the number patterns programs have been executed and verified successfully.

VSBEC-IT Page 29
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()

VSBEC-IT Page 30
Output
Program for Pyramid Pattern
Enter the number of rows: 4
*
***
*****
*******

Particulars Marks Allotted Marks Obtained


Performance 50
Viva-voce 10
Record 15
Total 75

Result
Thus the pyramid pattern program has been executed and verified successfully.

VSBEC-IT Page 31
4. Implementing
real-time/technical applications
using Lists, Tuples

(Items present in a library/Components of a car/


Materials required for construction of a building –
operations of list & tuples)

VSBEC-IT Page 1
4.A. Items present in a

library Algorithm

Step 1: Start the program


Step 2: Initialize the Library list with the following items "Books","e-Books”,
"Journals","Audiobooks","Manuscripts","Maps","Prints","Periodicals",
"Newspapers"
Step 3: Process the following from i in
Library Display i
Step 4: Remove an item “Prints” from Library
list Step 5: Display all items from Library list
Step 6: Remove 4th index item from Library list
Step 7: Display all items from Library list
Step 8: Delete all items from Library
list Step 9: Display the Library list
Step 10: Add an item "CD’s" to the Library list
Step 11: Insert an item "DVD's" at index 0 to the Library
list Step 12: Display the Library list
Step 13: Display an index of "DVD's" from the Library list
Step 14: Using slice operator deletes an item at index 0 from the Library
list Step 12: Display the Library list
Step 13: Stop the program

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")
print(Library)
print(Library.index("DVD's"))
del Library[0:1]
print(Library)

VSBEC-IT Page 2
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)

VSBEC-IT Page 3
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

4.C. Materials required for construction of a


building Program
print("Materials required for construction of a building")
print("Approximate Price: \n1.Cement:16%\n2.Sand:12%\n3.Aggregates:8%\n4.Steel
bars:24%\n5.Bricks:5%\n6.Paints:4%\n7.Tiles:8%\n8.Plumbing items:5%\n9.Electrical
items:5%\n10.Wooden products:10%\n11.Bathroom accessories:3%")
materials=("Cement/Bag","Sand/Cubic feet","Aggregates/Cubic feet","Steel
bars/Kilogram","Bricks/Piece","Paints/Litres","Tiles/Squre feet","Plumbing items/meter or
piece","Electrical items/meter or piece", "Wooden products/square feet", "Bathroom
accessories/piece")
price=[410,50,25,57,7,375,55,500,500,1000,1000]
for i in range(len(materials)):
print(materials[i],":",price[i])
print(" ")
#materials[0]="Glass items" -tuple is immutable
price[0]=500
for i in range(len(materials)):
print(materials[i],":",price[i])
print(" ")
print("Operations of tuple/list")
print(min(price))
print(max(price))
print(len(price))
print(sum(price))
print(sorted(price))
print(all(price))
print(any(price))

VSBEC-IT Page 4
Output
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

VSBEC-IT Page 5
5.Implementing real-time/technical
applications using Sets,
Dictionaries.

(Language, Components of an automobile, Elements of a


civil structure, etc.- operations of Sets & Dictionaries)

VSBEC-IT Page 6
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")
print("Dictionary values")
print(" ")
for i in components.values():
print(i)

VSBEC-IT Page 7
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']
['Roof panel', 'front panel', 'screen pillar', 'Lights', 'Tyres']

VSBEC-IT Page 8
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'])
{}

VSBEC-IT Page 9
5.C. Elements of a civil structure

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")
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

VSBEC-IT Page 10
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
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'}

VSBEC-IT Page 11
6. Implementing programs using Functions.

(Factorial, largest number in a list, area of shape)

VSBEC-IT Page 12
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

6.B. Largest number in a

list Program
def myMax(list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi=x
return maxi

list1 = [100, 200, 500, 150, 199, 487]


print("Largest element in the list is:", myMax(list1))

def myMax(list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi=x
return maxi

list1 = [100, 200, 500, 150, 199, 487]


print("Largest element in the list is:", myMax(list1))

Output
Largest element in the list is: 500

VSBEC-IT Page 13
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 rectangle


rect_area = l * b
print(f"The area of rectangle is {rect_area}.")

elif name == "square":


s = int(input("Enter square's side length: "))

# calculate area of square


sqt_area = s * s
print(f"The area of square is {sqt_area}.")

elif name == "triangle":


h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length:
"))

# calculate area of
triangle tri_area = 0.5 * b
*h
print(f"The area of triangle is {tri_area}.")

elif name == "circle":


r = int(input("Enter circle's radius length:
")) pi = 3.14

# calculate area of
circle circ_area = pi * r
*r
print(f"The area of circle is {circ_area}.")

elif name == 'parallelogram':


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length:
"))

# calculate area of
parallelogram para_area = b * h

VSBEC-IT Page 14
print(f"The area of parallelogram is {para_area}.")

else:
print("Sorry! This shape is not available")

VSBEC-IT Page 15
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.

VSBEC-IT Page 16
7. Implementing programs using Strings.
(reverse, palindrome, character count, replacing characters)

VSBEC-IT Page 17
7.A. String reverse

Program
def rev(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 function)


is:",end="") print(rev(s))

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.

VSBEC-IT Page 18
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

7.D. Replacing characters

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

VSBEC-IT Page 19
8. Implementing programs using
written modules and Python Standard
Libraries
(numpy, pandas, Matplotlib, scipy)

VSBEC-IT Page 20
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]]

2nd element on 1st row is: 2

3 D array:
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]

3rd element on 2nd row of the 1st matrix is 6

VSBEC-IT Page 21
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

{'cars': ['BMW', 'Volvo', 'Ford'], 'passings': [3, 7, 2]}


cars passings
0 BMW 3
1 Volvo 7
2 Ford 2

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)

VSBEC-IT Page 22
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. Ma

tplotlib

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()

VSBEC-IT Page 23
1. Output

VSBEC-IT Page 24
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

VSBEC-IT Page 25
9. Implementing
real-time/technical applications
using File handling.
(copy from one file to another, word count, longest word)

VSBEC-IT Page 26
9.A. 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()

Output
Source File Name: mega.txt
Hello India

Enter source file name: mega.txt


Enter destination file name: varnika.txt
File copied successfully!
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

Number of words in text file: 2

VSBEC-IT Page 27
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

Enter the file name:mega.txt


['Welcome']

VSBEC-IT Page 28
10. Implementing real-time/technical
applications using Exception handling

(divide by zero error, voter’s age validity, student mark


range validation)

VSBEC-IT Page 29
10.A. Divide by zero error

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!

10.B. Voter’s age

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

Enter your age:21


Eligible to vote
Thank you

Enter your age:17


Not eligible to vote
Thank you

Enter your age:varnika


invalid literal for int() with base 10:
'varnika' Thank you

VSBEC-IT Page 30
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

Enter marks of the Python subject: a


Entered data is wrong, Try Again
Thank you

VSBEC-IT Page 31

You might also like