[go: up one dir, main page]

0% found this document useful (0 votes)
19 views56 pages

Python Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 56

Ex: 1: Sequential programs in Python

1 a). Python program to convert Celsius to Fahrenheit


Aim:
To write a python program to convert Celsius to Fahrenheit.
Algorithm:
Step 1: Start the program
Step 2: Read Celsius
Step 3: Calculate Fahrenheit using the formula (Celsius*1.8)+32
Step 4: Print Fahrenheit
Step 5: Stop

Program:
Celsius=int(input("Enter the Celsius:"))
Fahrenheit=(Celsius*1.8)+32
print("The Fahrenheit for", Celsius, "degree Celsius is", Fahrenheit)

O/P:
Enter the Celsius: 40
The Fahrenheit for 40 degree Celsius is 104.0

Result:
Thus the python program for converting Celsius to Fahrenheit is executed and the
results are verified.

1 b) Python program to convert Fahrenheit to Celsius


Aim:
To write a python program to convert Fahrenheit to Celsius.
Algorithm:
Step 1: Start the program
Step 2: Read Fahrenheit
Step 3: Calculate Celsius using the formula (farenheit-32)/1.8
Step 4: Print Celsius
Step 5: Stop

Program:
Fahrenheit=int(input("Enter the Celsius:"))
Celsius=(Fahrenheit-32)/1.8
print("The Celsius for", Fahrenheit, "degree Fahrenheit is", Celsius)

O/P:
Enter the Celsius: 104
The Celsius for 104 degree Fahrenheit is 40.0

1
Result:
Thus the python program for converting Fahrenheit to Celsius is executed and the
results are verified.

1 c) Python program to find area of a circle.


Aim:
To write a python program to find area of a circle.
Algorithm:
Step 1: Start the program
Step 2: Read radius
Step 3: calculate the area of a circle by multiplying 3.14*radius*radius and store it in area
Step 4: Print area
Step 5: Stop

Program:
radius=int(input("Enter the radius of a circle"))
area=3.14*radius*radius
print("Area of a circle is", area)

O/P:
Enter the radius of a circle 4
Area of a circle is 50.24

Result:
Thus the python program for computing the area of circle is executed and the results
are verified.

1d ) Python program to swap two numbers with using third variable.


Aim:
To write a python program to swap two numbers with using a third variable.
Algorithm:
Step 1: Start the program
Step 2: Read two numbers in A and B
Step 3: print A and B before swapping
Step 4: store the value of A in temp
Step 5; store the value of B in A
Step 6: store the value of temp in B
Step 7: print the value of A and B after swapping
Step 8: Stop

2
Program:
A=int(input("Enter the A value:"))
B=int(input("Enter the B value:"))
print("Before Swapping")
print("A=", A)
print("B=", B)
temp=A
A=B
B=temp
print("After Swapping")
print("A=", A)
print("B=", B)

O/P:
Enter the A value: 10
Enter the B value: 20
Before Swapping
A= 10
B= 20
After Swapping
A= 20
B= 10

Result:
Thus the python program for swapping two numbers with using third variable is
executed and the results are verified.

1e) Python program to swap two numbers without using third variable.
Aim:
To write a python program to swap two numbers without using a third variable.
Algorithm:
Step 1: Start the program
Step 2: Read two numbers in A and B
Step 3: print A and B before swapping
Step 4: store the value of A in temp
Step 5; store the value of B in A
Step 6: store the value of temp in B
Step 7: print the value of A and B after swapping
Step 8: Stop

Program:
A=int(input("Enter the A value"))
B=int(input("Enter the B value"))

3
print("Before Swapping")
print("A=", A)
print("B=", B)
A=A+B
B=A-B
A=A-B
print("After Swapping")
print("A=", A)
print("B=", B)

O/P:
Enter the A value 10
Enter the B value 20
Before Swapping
A= 10
B= 20
After Swapping
A= 20
B= 10

Result:
Thus the python program for swapping two numbers without using third variable is
executed and the results are verified.

1f) Weight of a Motor Bike


Aim: To write a python program to calculate the weight of a motor bike.
Algorithm:
Step 1: Start the program
Step 2: Read the value of a mass
Step 3: Calculate the weight of a motor bike by multiplying mass with 9.8 and store it in weight
Step 4: Print the weight
Step 5: Stop

Program:
mass = float(input("Enter the Mass of the MotorBike: "))
Weight =mass*9.8
print(“ The weight of a Motor Bike for a given mass is ”,Weight)

O/P:
Enter the Mass of the MotorBike: 100
The weight of a Motor Bike for a given mass is 980.0000000000001

4
Result:
Thus the python program to calculate the weight of a motor bike is executed and the
results are verified.

1g) Weight of a Steel Bar


Aim: To write a python program to calculate the weight of a steel bar.
Algorithm:
Step 1: Start the program
Step 2: Read the value of a diameter and length
Step 3: Calculate the weight of a steel bar by using the formula of
((diameter*diameter)/162.28)*length and store it in weight.
Step 4: Print weight
Step 5: Stop

Program:
diameter = float(input("Enter the Diameter of the Rounded Steel Bar:"))
length = float(input("Enter the Length of the Rounded Steel Bar:"))
Weight =((diameter*diameter)/162.28)*length
Print(“Weight of a Steel Bar”,Weight)

O/P:
Enter the Diameter of the Rounded Steel Bar:2
Enter the Length of the Rounded Steel Bar:15
Weight of a Steel Bar is 0.3697313285679073

Result:
Thus the python program to calculate the weight of a steel bar is executed and the
results are verified.

1h) Electrical Current in Three Phase AC Circuit

Aim: To write a python program to calculate the electrical current in Three Phase AC Circuit
Algorithm:
Step 1: Start the program.
Step 2: Read all the values of resistance, frequency and voltage.
Step 3: Calculate the electrical current in three phase AC Circuit.
Step 4: Print the result.
Step 5: Stop

Program
from math import sqrt
R = 20# in ohm
X_L = 15# in ohm

5
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 Electrical Current in Three Phase AC Circuit",round(I_L,6))

O/P:
The Electrical Current in Three Phase AC Circuit 9.237604

Result:
Thus the python program to calculate the electrical current in Three Phase AC Circuit
is executed and the results are verified.

1i) Distance between two points

Aim: To write a python program to calculate the distance between 2 points


Algorithm:
Step 1: Start the program.
Step 2: Read all the values of x1,x2,y1,y2.
Step 3: Calculate the result.
Step 4: Print the result.
Step 5: Stop the program

Program :
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("Distance between",(x1,x2),"and",(y1,y2),"is : ",round(result,6))

O/P:
enter x1 : 4
enter x2 : 6
enter y1 : 0
enter y2 : 6
Distance between (4, 6) and (0, 6) is : 6.324555

6
Result:
Thus the python program to calculate the distance between 2 points is executed and the
results are verified.

1j) circulate the values of n variables

Aim: To write a python program to circulate the values of n variables


Algorithm:

Program:
list=[10,20,30,40,50]
n=3 #Shift 3 location
a=list[n:]+list[:n]
print(a)

O/P:
[40, 50, 10, 20, 30]

Result:
Thus the python program to circulate the values of n variables is executed and the
results are verified.

2. Scientific problems using Conditionals

2 a) Python program to find odd or even of a given number

Aim:
To write a python program find odd or even of a given number
Algorithm:
Step 1: Start
Step 2: Read the value in num
Step 3: find the remainder in rem of the given num by dividing num with 2
Step 4: if rem is equal to zero go to step 5, if not goto step 6
Step 5; print num is an even number
Step 6: if rem not equal to zero, print num is an odd number
Step 7: Stop

Program:
num=int(input("Enter the number"))
rem=num%2
if(rem == 0):
print(num,"is an even number")
else:

7
print(num,"is an odd number")

O/P:
Enter the number 20
20 is an even number

Result:
Thus the python program for testing a number as odd or even is executed and the results are
verified

2b) Electricity Billing


Aim:
To write a python program to print electricity bill.
Algorithm:
Step 1: Start the program
Step 2: Read the current reading in cr and previous reading in pr
Step 3: Calculate total consumed by subtracting cr with pr
Step 4: if total consumed is between 0 and 101, print amount to pay is consumed * 2
Step 5: if total consumed is between 100 and 201, print amount to pay is consumed * 3
Step 6: if total consumed is between 200 and 501, print amount to pay is consumed * 4
Step 7: if total consumed is greater than 500, print amount to pay is consumed * 5
Step 8: if total consumed is less than one print invalid reading
Step 9: Stop

Program:
cr=int(input("Enter current month reading"))
pr=int(input("Enter previous month reading"))
consumed=cr - pr
if(consumed >= 1 and consumed <= 100):
amount=consumed * 2
print("your bill is Rs.", amount)
elif(consumed > 100 and consumed <=200):
amount=consumed * 3
print("your bill is Rs.", amount)
elif(consumed > 200 and consumed <=500):
amount=consumed * 4
print("your bill is Rs.", amount)
elif(consumed > 500):
amount=consumed * 5
print("your bill is Rs.", amount)
else:
print("Invalid reading")

8
O/P:
Enter current month reading 500
Enter previous month reading 200
your bill is Rs. 1200

Result:
Thus the python program for generating electricity bill is executed and the results are
verified

2 c) Python program to find largest of three numbers

Aim:
To write a python program to find largest of three numbers
Algorithm:
Step 1: Start the program
Step 2: Read three values into a, b and c respectively.
Step 3: if a greater than b, check whether a is also greater than c, print a is largest; otherwise
goto next step.
Step 4: if b is greater than c than print b is largest; otherwise print c is largest.
Step 5: Stop

Program:
a=int(input("Enter the first number"))
b=int(input("Enter the second number"))
c=int(input("Enter the third number"))
if(a>b):
if(a>c):
print("A is the largest number")
else:
print("C is the largest number")
elif(b>c):
print("B is the largest number")
else:
print("C is the largest number")
O/P:
Enter the first number 100
Enter the second number 300
Enter the third number 50
B is the largest number

Result:
Thus the python program for finding largest among three numbers is executed and the results
are verified

9
2 d) Python program to compute quadratic equation

Aim:
To write a python program to compute quadratic equation
Algorithm:
Step 1: Start
Step 2: Read three values into a,b and c respectively.
Step 3: compute the discriminant d = b**2-4*a*c
Step 4: if d less than 0 then print “the equation has no real solution”; otherwise goto
next step
Step 5: if d equal to zero compute x = (-b+math.sqrt(b**2-4*a*c))/2*a and the print the
value of x; otherwise go to next step.
Step 6: Compute x1 = (-b+math.sqrt(b**2-4*a*c))/2*a and
x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
Step 6.1 Print “The equation has two solutions x1 and x2”
Step 7: Stop

Program:
import math
a=int(input("Enter the value of a"))
b=int(input("Enter the value of b"))
c=int(input("Enter the value of c"))
d = b**2-4*a*c # discriminant
if(d < 0):
print("This equation has no real solution")
elif(d == 0):
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print("This equation has one solutions: ", x)
else:
x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
print("This equation has two solutions: ", x1, " and", x2)

O/P:
Enter the value of a1
Enter the value of b5
Enter the value of c6
This equation has two solutions: -2.0 and -3.0

Result:
Thus the python program for computing the quadratic equation is executed and the results are
verified

10
2 e) Python program for Student mark list processing

Aim:
To write a python program to print grade of a student.
Algorithm:
Step 1: Start
Step 2: Read three values into m1, m2 and m3
Step 3: compute total = m1+m2 +m3
Step 4: compute average = total / 3
Step 5: if average greater than or equal to 75 and less than or equal to 100, print “Grade
– outstanding; otherwise goto next step
Step 6: : if average greater than or equal to 60 and less than 75, print “Grade – First
Class; otherwise goto next step
Step 7: if average greater than or equal to 50 and less than 60, print “Grade – Second
Class; otherwise goto next step.
Step 8: if average less than 50, print “Grade – Fail; otherwise print invalid mark
Step 9: Stop

Program:
m1=int(input("Enter mark 1"))
m2=int(input("Enter mark 2"))
m3=int(input("Enter mark 3"))
total = m1+m2+m3
average = total/3
print("Average = ",average)
if(average >= 75 and average <= 100):
print("Grade - Outstanding")
elif(average >= 60 and average<75):
print("Grade - First Class")
elif(average >=50 and average<60):
print("Grade - Second Class")
elif(average < 50):
print(" Grade - Fail")
else:
print("Invalid Mark")

O/P:
Enter mark 1 90
Enter mark 2 75
Enter mark 3 55
Average = 73.33333333333333
Grade - First Class

11
Result:
Thus the python program for computing student grade is executed and the results are verified

2 f) Python program for sin series

Aim: To write a python program for sin series.


Algorithm:
Step 1: Start
Step 2: Read the values of x and n
Step 3: Initialize sine=0
Step 4: Define a sine function using for loop, first convert degrees to radians.
Step 5: Compute using sine formula expansion and add each term to the sum variable.
Step 6: Print the final sum of the expansion.
Step 7: Stop.

Program:
import math
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
print(sine)

O/P:
Enter the value of x in degrees:3
Enter the number of terms:2
0.05235699888420977

Result:
Thus the python program for sin series is executed and the results are verified

3. Scientific programs using Iterative loops

3 a) Python program to find sum of first n natural numbers

Aim:
To write a python program to find sum of first n natural numbers.
.Algorithm:

12
Step 1: Start
Step 2: Read the limit in num.
Step 3: Initialize sum is equal to zero
Step 4: Calculate sum = sum + i, for i =1 to num.
Step 5: Print sum
Step 5: Stop

Program:
num=int(input("Enter the limit"))
sum=0
for i in range(1,num+1):
sum=sum+i
print("The sum of first", num, "natural numbers is", sum)

O/P:
Enter the limit 10
The sum of first 10 natural numbers is 55

Result:
Thus the python program for computing sum first n natural numbers is executed and the
results are verified

3 b) Python program to find factorial of given number

Aim:
To write a python program to find factorial of a given number.
.Algorithm:
Step 1: Start
Step 2: Read the value of n.
Step 3: Initialize fact is equal to 1
Step 4: Calculate fact = fact * i, for i =1 to num.
Step 5: Print fact
Step 6: Stop

Program:
n=int(input("Enter the number"))
fact=1
for i in range(1,n+1):
fact=fact*i
print("The factorail of the given number is", n, "is", fact)

O/P:
Enter the number 5

13
The factorail of the given number is 5 is 120

Result:
Thus the python program for computing factorial of a given number is executed and the
results are verified

3 c) Python program to check Armstrong number

Aim:
To write a python program to check whether given number is Armstrong number or not.
Algorithm:
Step 1: Start
Step 2: Read the value of n.
Step 3: Initialize sum = 0
Step 4: store the value of n in temp
Step 5: Execute the following until n is equal to zero
Step 5.1: rem = n % 10
Step 5.2: sum = sum + (rem*rem *rem)
Step 5.3: n = n / 10
Step 6: if sum is equal to temp, then print “Armstrong number”; otherwise goto next step
Step 7: if sum not equal to temp, the print “Not Armstrong number”;
Step 8: Stop

Program:
n=int(input("Enter the number"))
sum=0
temp=n
while(n>0):
rem=n%10
sum=sum+(rem*rem*rem)
n=n//10
if(sum == temp):
print("Armstrong number")
else:
print("Not an Armstrong number")

O/P:
Enter the number 153
Armstrong number

Result:
Thus the python program for checking Armstrong number or not is executed and the results
are verified

14
3 d) Python program to print sum of the digits of a given number

Aim:
To write a python program to print sum of the digits of given number.
Algorithm:
Step 1: Start
Step 2: Read the value of n.
Step 3: Initialize sum = 0
Step 4: Execute the following until n is equal to zero
Step 4.1: rem = n % 10
Step 4.2: sum = sum + rem
Step 4.3: n = n / 10
Step 5: print sum
Step 6: Stop

Program:
n=int(input("Enter the number"))
sum=0
while(n>0):
rem=n%10
sum=sum+rem
n=n//10
print("The sum of digits of the given number is", sum)

O/P:
Enter the number123
The sum of digits of the given number is 6

Result:
Thus the python program for finding sum of digits of a given number is executed and the
results are verified

3 e) Python program to print reverse of a given number

Aim:
To write a python program to print reverse of a given number.
Algorithm:
Step 1: Start
Step 2: Read the value of n.
Step 3: Initialize rev = 0
Step 4: Execute the following until n is equal to zero

15
Step 4.1: rem = n % 10
Step 4.2: rev = rev * 10 + rem
Step 4.3: n = n / 10
Step 5: print rev
Step 6: Stop

Program:
n=int(input("Enter the number"))
rev=0
while(n>0):
rem=n%10
rev=rev * 10 +rem
n=n//10
print("The reverse of the given number is", rev)

O/P:
Enter the number123
The reverse of the given number is 321

Result:
Thus the python program for finding reverse of a given number is executed and the results are
verified

3 f) Python program to find numbers from 100 to 200 which are divisible by 5 and not
divisible by 3.

Aim:
To write a python program to to find numbers from 100 to 200 which are divisible by 5 and
not divisible by 3.
.Algorithm:
Step 1: Start
Step 2: for i = 100 to 200, execute the following
Step 2.1: rem1=i%3 and rem2 = i%5
Step 2.2: if rem1 is equal to zero and rem2 not equal to zero; print i else not.
Step 3: Stop

Program:
print("Numbers from 100 to 200 divided by 5 and not divided by 3")
for i in range(100, 201):
rem1=i%5
rem2=i%3
if(rem1 == 0 and rem2 != 0):
print(i)

16
O/P:
Numbers from 100 to 200 divided by 5 and not divided by 3
100
110
115
125
130
140
145
155
160
170
175
185
190
200

Result:
Thus the python program to find numbers from 100 to 200 which are divisible by 5 and not
divisible by 3 is executed and the results are verified.

3 g) Python program for sin series

Aim: To write a python program for sin series.


Algorithm:
Step 1: Start
Step 2: Read the values of x and n
Step 3: Initialize sine=0
Step 4: Define a sine function using for loop, first convert degrees to radians.
Step 5: Compute using sine formula expansion and add each term to the sum variable.
Step 6: Print the final sum of the expansion.
Step 7: Stop.

Program:
import math
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)

17
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
print(sine)

O/P:
Enter the value of x in degrees:3
Enter the number of terms:2
0.05235699888420977

Result:
Thus the python program for sin series is executed and the results are verified.

3h) Python program to print number series

Aim: To write a python program to print numbers series.


Algorithm:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1,x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.

Program:
n=int(input(" enter the number of terms for the series "))
i=1
x=0
while(i<=n):
x=x*2+1
print(x, sep= "")
i+=1

O/P:
enter the number of terms for the series 5
1
3
7
15
31

Result:
Thus the python program to print numbers series is executed and verified.

18
3 i) Python program to print number patterns
Aim: To write a python program to print numbers patterns.
Algorithn:
Step 1: Start the program
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to i ;
Step 6: Set j in inner loop using range function and i integer will be initialized to j;
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.

Program:
rows = int(input('Enter the number of rows'))
for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')

O/P:
Enter the number of rows 6
1
22
333
4444
55555
666666

Result:
Thus the python program to print numbers patterns is executed and verified.

3 j) Pyramid Patterns:
Aim: To write a python program to print pyramid patterns
Algorithm:
Step 1: Start the program
Step 2: Read the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = 0 to rows ;
Step 6: Set j in inner loop using range function, j=0 to i+1;
Step 7: Print * until the condition becomes false in inner loop.

19
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.

Program:
rows = int(input(" enter the no. of rows"))
for i in range(0, rows):
# nested loop for each column
for j in range(0, i + 1):
# print star
print("*", end=' ')
# new line after each row
print(‘’)

O/P:
enter the no. of rows 5
*
**
***
****
*****

Result:
Thus the python program to print numbers pyramid patterns is executed and verified.

3 k) Python program to print first N Prime Numbers.

Aim:To write a python program to print first N Prime Numbers.


Algorithm:
Step 1: Start
Step 2: Read the limit in n
Step 3: for i from 1 to n+1 execute the following
Step 3.1: Store i in num and assign count= 0
Step 3.2: for j from 1 to num+1 execute the following
Step 3.2.1: if num% j == 0 increase count by 1.
Step 3.3: if count is equal to 2 then print i as a prime number
Step 4: Stop

Program:

n = int(input("Enter the upper limit: "))


print("Prime numbers are")
for i in range(1,n + 1):
num=i

20
count=0
for j in range(1,num+1):
if(num%j == 0):
count=count+1
if(count == 2):
print(i)

O/P:
Enter the upper limit: 10
Prime numbers are
2
3
5
7

Result:
Thus the python program to print first N prime numbers is executed and the results are
verified.

3 l) Python program to perform matrix multiplication

Aim:To write a python program to perform matrix multiplication.


Algorithm:
Step 1: Start
Step 2: Define two matrices X and Y
Step 3: Create a resultant matrix named ‘result’
Step 4: for i in range(len(X)):
Step 4.1: for j in range(len(Y[0])):
Step 4.1.1for k in range(len(Y))
Step 4.1.1.1 result[i][j] += X[i][k] * Y[k][j]
Step 5: for r in result, print the value of r
Step 6: Stop

Program:

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result = [[0,0,0,0],
[0,0,0,0],

21
[0,0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

O/P:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Result:
Thus the python program to perform matrix multiplication is executed and the results are
verified.

3 m) Retail Shop Billing

Aim: Aim: To write a python program for retail shop billing system.
Algorithm:
Step 1: Start the program
Step 2: Declare the list as prices.
Step 3: Read the total no. of items as n.
Step 4: Repeat the following until the range function in for loop becomes false.
Step 4.1: Read the value of item.
Step 4.2: sub_total=sub_total+item.
Step 4.3: Append the value of item to the prices.
Step 5: Calculate tax and total_price.
Step 6: Print tax and total_price.
Step 7: Stop the program.

Program :
prices = []
sub_total = 0.0
n=int(input(" Enter the no of items :"))
for i in range(n):
item = float( input("Enter the price of item #" + str(i+1) + ": "))
sub_total = sub_total + item
prices.append(item)
#compute the tax on the sub total @ rate of 7.25%
tax = sub_total * (7.25/100)
total_price = sub_total + tax

22
print("Sub total: ",sub_total)
print("Tax: {:0.2f}".format(tax))
print("Total: {:0.2f}".format(total_price))

O/P :
Enter the no of items :2
Enter the price of item #1: 101.1
Enter the price of item #2: 101.2
Sub total: 202.3
Tax: 14.67
Total: 216.97

Result:
Thus the python program for retail shop billing system is executed and verified.

4) Python program to find element in the list using linear search

Aim: To write a python program to search element in the list using linear search.
Algorithm:
Step 1: Start
Step 2: Read the limit of the list as n
Step 3: Read n elements into the list
Step 4: Read the key value to be searched in the list
Step 5: Let count = 0
Step 6: Repeat step 6.1 until the end of list
Step 6.1: if key = list element then count = count + 1
Step 7: if count > 0 then print “element is found”; otherwise goto Step 8
Step 8: Print “the element is not found”
Step 9: Stop

Program:
n=int(input("Enter the limit"))
list=[]
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
print("Which element to search")
key=int(input())
count=0
for i in range(0,n):

23
if(key == list[i]):
count=count+1
if(count>0):
print("Element found")
else:
print("Element not found")

O/P:
Enter the limit 5
Enter list elements one by one
100
200
300
400
500
The list elements are
[100, 200, 300, 400, 500]
Which element to search
200
Element found

Result:
Thus the python program to find element in the list using linear search is executed and the
results are verified.

5) Python program to find element in the list using Binary search

Aim: To write a python program to search element in the list using binary search.
Algorithm:
Step 1: Start
Step 2: Read the limit of the list as n
Step 3: Read n elements into the list
Step 4: Read the key value to be searched in the list
Step 5: Let first=0, locn=-1, last = n
Step 6: Repeat the following steps until first > last
Step 6.1: Let mid=(first+last)/2
Step 6.2: if list[mid] > key then last = mid – 1; otherwise goto step 6.3
Step 6.3: if list[mid] < key then first = mid + 1; otherwise goto step 6.4
Step 6.4: Let first = last + 1(forced exit)
Step 7: if list[mid]=key, then locn = mid
Step 8: if locn< 0, then the key is not found; otherwise goto step 9
Step 9: Print “the key is found at postion locn”
Step 10: Stop

24
Program
n=int(input("Enter the limit"))
list=[]
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
print("Which element to search")
key=int(input())
locn=-1
first=0
last=n-1
while(first<=last):
mid=(first+last)//2
if(list[mid]>key):
last=mid-1
elif(list[mid]<key):
first=mid+1
else:
first=last+1
if(list[mid]==key):
locn=mid
if(locn<0):
print("Element not found")
else:
print(key, "Found at postion", locn)

O/P:
Enter the limit 5
Enter list elements one by one
10
20
30
40
50
The list elements are
[10, 20, 30, 40, 50]
Which element to search
30
30 Found at postion 2

25
Result:
Thus the python program to find element in the list using binary search is executed and the
results are verified.

6) Python program to sort elements in the list using selection sort algorithm.

Aim:To write a python program to sort elements in the list using selection sort algorithm.
Algorithm:
Step 1: Read n number of values is the list named as “a”
Step 2: Pass the list as argument to the insertionSort function.
Step 3: Repeat the following from index 1 to length of the list
Step 3.1: Let currentvalue = a[index]
Step 3.2 Let position = index
Step 3.3: Repeat the following under the conditions position > 0 and
a[position – 1] > current value
Step 3.3.1: a[position] = a[position – 1]
Step 3.3.2: position = position – 1
Step 3.4: a[position]=currentvalue
Step 4: Print the sorted list in a
Step 5: Stop
Program
A = [23, 78, 45, 8, 32,56]
for i in range(0,len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
temp=A[i]
A[i]=A[min_idx]
A[min_idx]=temp
print ("Sorted List using selection sort")
print(A)

O/P:
Sorted List using selection sort
[8, 23, 32, 45, 56, 78]

Result:
Thus the python program sort element in the list using selection sort algorithm is executed
and the results are verified.

7) Python program to sort elements in the list using insertion sort algorithm.

26
Aim:To write a python program to sort elements in the list using insertion sort algorithm.
Algorithm:
Step 1: Read n number of values is the list named as “a”
Step 2: Pass the list as argument to the insertionSort function.
Step 3: Repeat the following from index 1 to length of the list
Step 3.1: Let currentvalue = a[index]
Step 3.2 Let position = index
Step 3.3: Repeat the following under the conditions position > 0 and
a[position – 1] > current value
Step 3.3.1: a[position] = a[position – 1]
Step 3.3.2: position = position – 1
Step 3.4: a[position]=currentvalue
Step 4: Print the sorted list in a
Step 5: Stop

Program
def insertionSort(a):
for index in range(1,len(a)):
currentvalue = a[index]
position = index
while position>0 and a[position-1]>currentvalue:
a[position]=a[position-1]
position = position-1
a[position]=currentvalue
a = [23,78,45,8,32,56]
insertionSort(a)
print("The sorted list using insertion sort is")
print(a)

O/P:
The sorted list using insertion sort is
[8, 23, 32, 45, 56, 78]

Result:
Thus the python program to sort element in the list using insertion sort algorithm is executed
and the results are verified.

8) Python program to sort elements in the list using merge sort algorithm.

Aim:To write a python program to sort elements in the list using merge sort algorithm.
Algorithm:
Step 1: Start
Step 2: Read n elements in list named “nlist”

27
Step 3: Create a function named mergesort and pass nlist as arguements
Step 4: Find the mid of the list using, mid = len(nlist) / 2
Step 5: Assign lefthalf = nlist[0 to mid-1] and righthalf = nlist[mid to n-1]
Step 6: Initialise i=j=k=0
Step 7: while i <len(lefthalf) and j <len(righthalf), perform the following
Step 7.1 if lefthalf[i] <righthalf[j]:
Step 7.1.1: nlist[k]=lefthalf[i]
Step 7.1.2: Increment i
Step 7.2: else
Step 7.2.1: nlist[k]=righthalf[j]
Step 7.2.2: Increment j
Step 7.3 Increment k
Step 8.while i <len(lefthalf),perform the following
Step 8.1: nlist[k]=lefthalf[i]
Step 8.2: Increment i
Step 8.3: Increment k
Step 9: while j <len(righthalf), perform the following
Step 9.1: nlist[k]=righthalf[j]
Step 9.2 Increment j
Step 9.3 Increment k
Step 10: Print the sorted list
Step 11: Stop

Program
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
28
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

OUTPUT:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]

29
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:
Thus the python program to sort element in the list using merge sort algorithm is executed
and the results are verified.

9. FUNCTIONS
9a) Python program to find GCD of given numbers using Euclid's Algorithm.

Aim: To write a python program to find gcd of given numbers using Euclids algorithm.
Algorithm:
Step 1: Start the program.
Step 2: Read the values of a and b as positive integers in function call gcd(a,b).
Step 3: recursively function call gcd(a,b) will be computed in (b, a % b) if b!=0.
Step 4: if b is equal to 0 return a.
Step 5: Print the result.
Step 6: Stop the program.

Program:
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
a=int(input("Enter the value of a"))
b=int(input("Enter the value of b"))
result=gcd(a,b)
print("The greatest common divisor is",result)

O/P:
Enter the value of a 24
Enter the value of b 54
The greatest common divisor is 6

Result:

30
Thus the python program to find gcd of given numbers using Euclid’s method is executed and
the results are verified.

9b) Python program to find square root of a given number using newtons method.

Aim: To write a python program to find to find square root of a given number using newtons
method.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of n, n being a positive integer in the function newtonSqrt(n)
Step 3: Let approx = 0.5 * n
Step 4: Let better = 0.5 * (apporx + n/approx)
Step 5: Repeat the following steps until better equals to approx
Step 5.1: Let approx = better
Step 5.2: Let better = 0.5 * (apporx + n/approx)
Step 6: Return the value approx as the square root of the given number n
Step 7: Print the result.
Step 8: Stop the program.

Program:
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while(better != approx):
approx = better
better = 0.5 * (approx + n/approx)
return approx
n=int(input("Enter the number"))
result=newtonSqrt(n)
print("The Square root for the given number is",result)
O/P:
Enter the number 25
The Square root for the given number is 5.0
Result:
Thus the python program to find square root of given number using newtons method is
executed and the results are verified.

9c) Factorial of a number using functions


Aim: To write a python program to find the factorial of a given number by using functions.
Algorithm:
Step 1: Start the program.

31
Step 2: Read the value of n as positive integers in function call factorial(n).
Step 3: if n is not equal to zero, recursively function call factorial will be computed as n*
factorial(n-1) and return the value of n.
Step 4: if n is equal to 0, return the value as 1
Step 5: Print the result.
Step 6: Stop the program.

Program:
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

O/P:
Input a number to compute the factorial : 5
120

Result:
Thus the python program to find the factorial of a given number by using functions is
executed and the results are verified.

9d) largest number in a list using functions


Aim: To write a python program to find the largest number in the list.

Algorithm:
Step 1: Start the program.
Step 2: Read the limit of the list as n.
Step 3: Read n elements into the list.
Step 4: Let large = list[0]
Step 5: Execute for loop i= 1 to n and repeat the following steps for the value of n until the
condition becomes false.
Step 5.1: if next element of the list > large then
Step 5.1.1: large = element of the list
Step 6: Print the large value.
Step 7: Stop the program.

Program:
def largest(n):
list=[]

32
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
large=list[0]
for i in range(1,n):
if(list[i]>large):
large=list[i]
print("The largest element in the list is",large)
n=int(input("Enter the limit"))
largest(n)

O/P:
Enter the limit5
Enter list elements one by one
10
20
30
40
50
The list elements are
[10, 20, 30, 40, 50]
The largest element in the list is 50

Result:
Thus the python program to find the largest number in the list by using functions is
executed and the results are verified.

9 e) Area of shape using functions.


Aim: To write a python program for area of shape using functions.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of l and b as positive integers in function call rect(l,b).
Step 3: Recursively call function(rect) will be computed as x*y and return the result to the
function call rect(l,b).
Step 4: Print area of the rectangle.
Step 5: Read the value of num as positive integers in function call circle(num).
Step 6: Recursively call the function circle) will be computed as PI*(r*r) and return the result to
the function call circle(num).
Step 7: Print area of the circle.
Step 8: Read the values in function call triangle as a parameters.

33
Step 9: Recursively call(triangle) will be computed with a,b,c as a parameter and print the result.
Step 10: Read the values as positive integers in function call parallelogram(base,height).
Step 11: Recursively call(parallelogram) will be computed as a*b and return the result to the
function call parallelogram(Base, Height).
Step 12: Print area of parallelogram.
Step 13: Stop the program.

Program:
def rect(x,y):
return x*y
def circle(r):
PI = 3.142
return PI * (r*r)
def triangle(a, b, c):
Perimeter = a + b + c
s = (a + b + c) / 2
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print(" The Perimeter of Triangle = %.2f" %Perimeter)
print(" The Semi Perimeter of Triangle = %.2f" %s)
print(" The Area of a Triangle is %0.2f" %Area)
def parallelogram(a, b):
return a * b;
# Python program to compute area of rectangle
l = int(input(" Enter the length of rectangle : "))
b = int(input(" Enter the breadth of rectangle : "))
a = rect(l,b)
print("Area =",a)
# Python program to find Area of a circle
num=float(input("Enter r value of circle:"))
print("Area is %.6f" % circle(num))
# python program to compute area of triangle
import math
triangle(6, 7, 8)
# Python Program to find area of Parallelogram
Base = float(input("Enter the Base : "))
Height = float(input("Enter the Height : "))
Area =parallelogram(Base, Height)
print("The Area of a Parallelogram = %.3f" %Area)

O/P:
Enter the length of rectangle : 1
Enter the breadth of rectangle : 2
34
Area = 2
Enter r value of circle:2
Area is 12.568000
The Perimeter of Triangle = 21.00
The Semi Perimeter of Triangle = 10.50
The Area of a Triangle is 20.33
Enter the Base : 2
Enter the Height : 3
The Area of a Parallelogram = 6.000

Result:
Thus the python program for area of shape using functions is executed and the results
are verified.

10. STRINGS

10 a) Reverse of a string:

Aim: To write a python program for reversing a string..


Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string .
Step 3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program

Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)

O/P:
dlroW ,olleH

Result:
Thus the python program for reversing a string is executed and the results are
verified.

35
10 b) Palindrome of a string
Aim: To write a python program for palindrome of a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method. .
Step 3: if string==string[::-1], print “ the string is palindrome ”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop the program

Program:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

O/P:
Enter a string: madam
The string is a palindrome
Enter a string: nice
Not a palindrome

Result:
Thus the python program for palindrome of a string is executed and the results are
verified.

10 c) Character count

Aim: To write a python program for counting the characters of string.

Algorithm:
Step 1: Start the program.
Step 2: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment the
count by 1.
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.
Step 5: Stop the program.

Program:
a=input(" enter the string")
count = 0;
36
#Counts each character except space
for i in range(0, len(a)):
if(a[i] != ' '):
count = count + 1;
#Displays the total number of characters present in the given string
print("Total number of characters in a string: " + str(count));

O/P:
enter the string hai
Total number of characters in a string: 3

Result: Thus the python program for counting the characters of string is executed and the
results are verified.

10 d) Replace of a string
Aim: To write a python program for replacing the characters of a string.

Algorithm:
Step 1: Start the program.
Step 2: Define a string.
Step 3: Determine the character 'ch' through which specific character need to be replaced.
Step 4: Use replace function to replace specific character with 'ch' character.
Step 5: Stop the program.

Program:
string = "Once in a blue moon"
ch = 'o'
#Replace h with specific character ch
string = string.replace(ch,'h')
print("String after replacing with given character: ")
print(string)

O/P:
String after replacing with given character:
Once in a blue mhhn

Result:
Thus the python program for replacing the given characters of string is executed and
the results are verified.

37
11. List & Tuples
11 a) Aim: To write a python program to implement the library functionality using list.

Algorithm
Step 1: Start the program
Step 2: Initialize the book list
Step 3: Get option from the user for accessing the library function 1. Add the book to list 2.
Issue a book 3. Return the book 4. View the list of book
Step 4: if choice is 1 then get book name and add to book list
Step 5: if choice is 2 then issue the book and remove from book list
Step 6: if choice is 3 then return the book and add the book to list
Step 7: if choice is 4 then the display the book list
Step 8: otherwise exit from menu
Step 9: Stop the program.

Program:
bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input(" \n 1. add the book to list \n 2. issue a book \n 3. return the book \n 4. view the
book list \n 5. Exit \n"))
if(ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break
O/P:
Welcome to library”
1. add the book to list
2. issue a book
38
3. return the book
4. view the book list
5. Exit
1
enter the book name NW
['OS', 'MPMC', 'DS', ' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
2
Enter the book to issue NW
['OS', 'MPMC', 'DS']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
3
enter the book to return NW
['OS', 'MPMC', 'DS', ' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
4
['OS', 'MPMC', 'DS', ' NW']

Result:
Thus the python program to implement the library functionality using list is executed
and the results are verified

11 b) Components of car using list.

Aim:
To write a python program to implement the operation of list for components of car.

Algorithm:
Step 1: Start the program.

39
Step 2: create a list of components for car
Step 3: get single component from user and append into list
Step 4: find the length of the list using len function
Step 5: find the minimum and maximum value of the list
Step 6: print the component using index of the list
Step 7: multiply the list element using multiplication operation
Step 8: check the component exist in the list or not using in operator
Step 9: Stop the program.

Program:
cc=['Engine','Front axle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print(cc)
print("length of the list:",len(cc))
print("maximum of the list:",max(cc))
print("minimum of the list:",min(cc))
print("indexing:",cc[3])
print("Battery" in cc)
print("multiplication of list element:",cc*2)

Output:
Enter the car components:tank
['Engine', 'Front axle', 'Battery', 'transmision', 'tank']
length of the list: 5
maximum of the list: transmision
minimum of the list: Battery
indexing: transmision
True
multiplication of list element: ['Engine', 'Front axle', 'Battery', 'transmision', 'tank', 'Engine',
'Front axle', 'Battery', 'transmision', 'tank']

Result
Thus the python program to create a list for components of car and performed the
various operation and result is verified.

11 c) Material required for construction of a building using list.

Aim:
To write a python program to create a list for materials requirement of construction and
perform the operation on the list.

Algorithm:

40
Step 1: Start the program.
Step 2: Create a list of construction material.
Step 3: Sort the list using sort function.
Step 4: Print cc.
Step 5: Reverse the list using reverse function.
Step 6: Print cc.
Step 7: Insert y value by using index position.
Step 8: Slice the values using del function with start value and end up value.
Step 9: Print the cc.
Step 10: Print the position of the value by using index function.
Step 11: Print the values in the list of the letter ‘n’ by using for loop and member ship operator.
Step 12: Stop the program.

Program
cc=['Engine','Front axle','Battery','transmision']
cc.sort()
print(cc)
cc.reverse()
print(cc)
cc.insert(0, 'y')
print(cc)
del cc[:2]
print(cc)
print(cc.index('Engine'))

new=[]
for i in cc:
if "n" in i:
new.append(i)
print(new)

O/P:
['Battery', 'Engine', 'Front axle', 'transmision']
['transmision', 'Front axle', 'Engine', 'Battery']
['y', 'transmision', 'Front axle', 'Engine', 'Battery']
['Front axle', 'Engine', 'Battery']
1
['Front axle', 'Engine']

Result:
Thus the python program to create a list for construction of a building using list is
executed and verified.

41
11 d) Library using tuples
Aim: To write a python program to implement the library functionality using tuples.

Algorithm
Step 1: Start the program
Step 2: Create a tuple named as book.
Step 3: Add a “NW” to a book tuple by using + operator.
Step 4: Print book.
Step 5: Slicing operations is applied to book tuple of the range 1:2 and print book.
Step 6: Print maximum value in the tuple.
Step 7: Print maximum value in the tuple.
Step 8: Convert the tuple to a list by using list function.
Step 9: Delete the tuple.
Step 10: Stop the program.

Program:
book=("OS","MPMC","DS")
book=book+("NW",)
print(book)
print(book[1:2])
print(max(book))
print(min(book))
book1=("OOAD","C++","C")
print(book1)
new=list(book)
print(new)
del(book1)
print(book1)

O/P:
('OS', 'MPMC', 'DS', 'NW')
('MPMC',)
OS
DS
('OOAD', 'C++', 'C')
['OS', 'MPMC', 'DS', 'NW']
Traceback (most recent call last):
File "C:\Python34\1.py", line 12, in <module>

42
print(book1)
NameError: name 'book1' is not defined

Result:
Thus the python program to implement the library functionality using tuple is executed
and the results are verified

11 e) Components of a car using tuples.


Aim: To write a python program to implement the components of a car using tuples.

Algorithm:
Step 1: Start the program
Step 2: Create a tuple named as cc
Step 3: Adding a value to a tuple is by converting tuple to a list and then assign “ Gear” value to
y[1] and convert it to a tuple.
Step 4: Step 3 is implemented for removing a value in tuple.
Step 5: Type function is used to check whether it is list or tuples.
Step 6: Stop the program.

Program:
cc=('Engine','Front axle','Battery','transmision')
y=list(cc)# adding a value to a tuple means we have to convert to a list
y[1]="Gear"
cc=tuple(y)
print(cc)
y=list(cc)# removing a value from tuple.
y.remove("Gear")
cc=tuple(y)
print(cc)
new=(" Handle",)
print(type(new))

O/P:
('Engine', 'Gear', 'Battery', 'transmision')
('Engine', 'Battery', 'transmision')
<class 'tuple'>

Result:
Thus the python program to implement components of a car using tuples is executed
and verified.

43
11 f) Construction of a materials
Aim: To write a python program to implement the construction of a materials using tuples.

Algorithm:
Step 1: Start the program
Step 2: Create a tuple named as cm
Step 3: tuple unpacking method is applied and print values.
Step 4: count the elements in the tuple using count function.
Step 5: Index function is used to get the position of an element.
Step 6: Convert the string to a tuple and print variable.
Step 7: Sort the values of a tuple to list using sorted function.
Step 8: Print the type function for sorted.
Step 9: Stop the program.

Program:
cm=('sand','cement','bricks','water')
a,b,c,d = cm # tuple unpacking
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
print(d)
print(cm.count('sand'))
print(cm.index('sand'))
new=tuple("sand")
print(new)
print(sorted(cm))
print(type(sorted(cm)))

O/P:
Values after unpacking:
sand
cement
bricks
water
1
0
('s', 'a', 'n', 'd')
['bricks', 'cement', 'sand', 'water']
<class 'list'>

Result:

44
Thus the python program to create a tuple for materials of construction and performed
the various operations and result is verified.

12 Dictionaries and Sets


12 a) Languages using dictionaries
Aim: To write a python program to implement the languages using dictionaries.
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: dict() is used to create a dictionary.
Step 4: To add a value, update() is used in key value pair.
Step 5: Calculate the total values in the dictionary using len() .
Step 6: Remove the particular key in the dictionary by using pop()
Step 7: Print the keys in the dictionary by using key()
Step 8: Print the values in the dictionary by using values()
Step 9: Print the key value pair in the dictionary using items()
Step 10: Clear the the key value pair by using clear()
Step 11: Delete the dictionary by using del dictionary

Program:
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"}#duplicate values can create
Language.update(New_Language)
print(" the updated languages are :",Language)
print(" the length of the languages :",len(Language))
Language.pop(5)
print(" key 5 has been popped with value :",Language)
print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
Language.clear()
print(" The items are cleared in dictionary ",Language)
del Language
print(Language)

45
O/P:
Empty Dictionary : {}
Using dict() the languages are : {'two': 'tamil', 1: 'english', 3: 'malayalam'}
the updated languages are : {'two': 'tamil', 1: 'english', 3: 'malayalam', 4: 'hindi', 5: 'hindi'}
the length of the languages : 5
key 5 has been popped with value : {'two': 'tamil', 1: 'english', 3: 'malayalam', 4: 'hindi'}
the keys are : dict_keys(['two', 1, 3, 4])
the values are : dict_values(['tamil', 'english', 'malayalam', 'hindi'])
the items in languages are : dict_items([('two', 'tamil'), (1, 'english'), (3, 'malayalam'), (4,
'hindi')])
The items are cleared in dictionary {}
Traceback (most recent call last):
File "C:\Python34\1.py", line 17, in <module>
print(Language)
NameError: name 'Language' is not defined

Result:
Thus the python program to implement languages using dictionaries is executed and
verified.

12 b) Automobile using dictionaries

Aim: To write a python program to implement automobile using dictionaries.

Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: dict() is used to create a dictionary.
Step 4: Get the value in the dictionary using get()
Step 5: adding [key] with value to a dictionary using indexing operation.
Step 6: Remove a key value pair in dictionary using popitem().
Step 7: To check whether key is available in dictionary by using membership operator in.
Step 8: Stop the program.

Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is ",auto_mobile.get(2))

46
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile)
print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile parts")
print(2 in auto_mobile)

O/P:
Empty dictionary {}
Automobile parts : {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'}
The value for 2 is Clutch
Updated auto_mobile {1: 'Engine', 2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
(1, 'Engine')
The current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is 2 available in automobile parts
True

Result:
Thus the python program to implement automobile using dictionaries is executed and
verified.

12 c) Elements of a civil structure


Aim: To write a python program to implement elements of a civil structure using dictionaries.
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using {}
Step 3: Create a dictionary using dict().
Step 4: To access the value in the dictionary indexing is applied.
Step 5: adding [key] with value to a dictionary using indexing operation..
Step 6: A copy of original dictionary is used by copy ().
Step 7: The length of the dictionary is by len().
Step 8: Print the values of the dictionary by using for loop
Step 9: Stop the program

Program:
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])

47
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print(" The copy of civil_ele",new)
print(" The length is ",len(civil_ele))
for i in civil_ele:
print(civil_ele[i])

O/P:
{}
the elements of civil structure are {1: 'Beam', 2: 'Plate'}
the value for key 1 is : Beam
{'three': 'concrete', 1: 'Beam', 2: 'Plate'}
The copy of civil_ele {'three': 'concrete', 1: 'Beam', 2: 'Plate'}
The length is 3
concrete
Beam
Plate

Result:
Thus the python program to implement elements of a civil structure using dictionaries
is executed and verified.

12 d)
Aim: To write a python program to implement library using sets.
Algorithm:
Step 1: Start the program
Step 2: Create set {} with string values.
Step 3: To insert a value in a set use add function.
Step 4: To return a new set with distinct elements from all the sets use union ().
Step 5: To returns a set that contains the similarity between two or more sets use
intersection().
Step 6: To clear all the values in a set use clear().
Step 7: Stop the program

Program:
Languages
old_books= {"MP","OOAD","NW"}
old_books.add("TOC")
print(old_books)

48
new_books= {"SE","AI"}
Library = old_books | new_books
print(" Union",Library)
Books1={"MP","OOAD","NW"}
Library = old_books & Books1
print(" Intersection ",Library)
print(old_books.clear())

Output:
{'OOAD', 'MP', 'NW', 'TOC'}
Union {'AI', 'SE', 'OOAD', 'MP', 'NW', 'TOC'}
Intersection {'OOAD', 'MP', 'NW'}
None

Result: Thus the python program to implement library using sets is executed and verified.

12 e) AutoMobile
Aim: To write a python program to implement automobile using sets.
Algorithm:
Step 1: Start the program
Step 2: Create a set.
Step 3: Update the values in the set by using update()
Step 4: Remove the value in the set using discard ()
Step 5: Print the values using set()
Step 6: check whether value in the set using membership operator in
Step 7: maximum value in the set using max()
Step 8: minimum value in the set using min()
Step 9: Stop the Program.

Program:
auto_mobile={"Engine","Clutch","GearBox"}
print(auto_mobile)
auto_mobile.update(["2","3","4"])
print(auto_mobile)
auto_mobile.discard("2")
print(auto_mobile)
new= set("Engine")
print(new)
print('a' in auto_mobile)
maxi=max(auto_mobile)

49
print(maxi)
mini=min(auto_mobile)
print(mini)

O/P:
{'Engine', 'Clutch', 'GearBox'}
{'3', 'Engine', '4', '2', 'Clutch', 'GearBox'}
{'3', 'Engine', '4', 'Clutch', 'GearBox'}
{'n', 'g', 'i', 'E', 'e'}
False
GearBox
3

Result:
Thus the python program to implement automobiles using set is executed and verified.

13. File handling


13 a) Count no of words

Aim: To write a python program to count number of words in a text file using command line
arguments.

Algorithm:
Step 1: Start the program.
Step 2: import sys package.
Step 2: Assign num_words=0.
Step 3: Open text file in reading mode from command line argument sys.argv[1] as f.
Step 4: Split each line from the text and count number of words and store it in num_words.
Step 5: Print the total number of words from num_words.
Step 6: Stop the program.

Program:
import sys
num_words=0
with open(sys.argv[1],"r")as f:
for line in f:
words=line.split()
num_words+=len(words)
print("Number of words")
print(num_words)

Method how to execute

50
1. Type and Save Count program as count.py.
2. Create a text file and type it as “hai how are you” and save it as sample.txt.
3. Copy it in C:\Python34
4. Go to run, type cmd, window will open..
O/P:

Result:
Thus the python program to count number of words in a text file using command line
arguments is executed and verified.

13 b) Copy file:

Aim: To write a python program to copy the content from one file to another file.

Algorithm:
Step 1: Start the program
Step 2: Open one file called test. txt in read mode.
Step 2: Open another file out. txt in write mode.
Step 3: Read each line from the input file and write it into the output file.
Step 4: Stop the program.

Program:
with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
# read content from first file
for line in firstfile:
# append content to second file
secondfile.write(line)

O/P:
Method how to execute
51
1. Type and Save python program as copy.py
2. Create a 2 text file and save it as first.txt and second.txt
3. Copy both text files in C:\Python34.
4. In first.txt write it as “hai”.
5. In second.txt, keep it as empty.
6. Go to run, type cmd, window will open..
7. Open second.txt and see, details of first.txt will be appended in second txt.

Result:
Thus the python program to copy the content from one file to another file is executed
and verified.

13 c) Longest word:

Aim: Aim: To write a python program to find the longest word in a text.
Algorithm:
Step 1: Start the program.
Step 2: By invoking call function, open text file in reading mode as infile.
Step 3: Split the word which was read by using infile.read().split() function and store it in
variable named as words.
Step 4: Calculate the length of each words and store the maximum words in max_len.
Step 5: Using for loop return the maximum word if len(word)==max_len is true.

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]

52
print(longest_word('longest.txt'))

O/P:
Method how to execute
1. Type and save the python program as longest.py.
2. Create a text file and type it as “Be confident in yourself ” save it as longest.txt.
3. Copy it in C:\Python34.
4. Go to run, type cmd, window will open..

Result: To write a python program to find the longest word in a text is executed and verified.

14 Exception handling
14 a) Voter’s age eligibility
Aim: To write a python program to check whether the person is eligible to vote or not
Algorithm:
Step 1: Start the program.
Step 2: Get the input from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the entered data is below zero, print it is “negative number”, else break.
Step 5: If no exception is there, print the result.
Step 6: Stop the program.

Program:
while True:
try:
age=int(input(" Please enter your age: "))
except ValueError:
print(" Sorry,this is not a number")
continue
53
if(age<0):
print(" Sorry, this is a negative number ")
continue
else:
break

if(age>=18):
print(" you are able to vote ")
else:
print(" you are not able to vote ")

O/P:
Please enter yout age: 18
you are able to vote
Please enter yout age: -1
Sorry, this is a negative number
Please enter yout age: abcc
Sorry, this is not a number

Result: Thus the python program to check whether the person is eligible to vote or not is
executed and verified

14 b) divide by zero error


Aim: To write a python program for divide by zero error exception.
Algorithm:
Step 1: Start the program
Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step 6: Stop the program.

Program:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
54
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

O/P:
Enter First Number: 432.12
Invalid Input Please Input Integer...
Enter First Number: 43
Enter Second Number: 0
division by zero
Enter First Number: 331 2
Enter Second Number: 4
83.0

Result: Thus the python program for divide by zero error exception is executed and verified.

14 c) student mark range validation


Aim: To write a python program for student mark range validation.
Algorithm:
Step 1: Start the program
Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program.
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")

55
main()

O/P:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed

Result: Thus the python program for student mark range validation is executed and verified.

56

You might also like