0% found this document useful (0 votes)
10 views

Python Record 1

Uploaded by

hemasivasri0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Record 1

Uploaded by

hemasivasri0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Om Sakthi

ADHIPARASAKTHI COLLEGE OF ENGINEERING


G.B.Nagar, Kalavai – 632 506, Ranipet District, Tamil Nadu

DEPARTMENT OF SCIENCE AND HUMANITIES

GE3171-PYTHON PROGRAMMING LABORATORY


Om Sakthi

ADHIPARASAKTHI COLLEGE OF ENGINEERING


G.B.Nagar, Kalavai – 632 506, Ranipet District, Tamil Nadu

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Name :

Register Number :

Subject Code : GE3171

Subject Name : Python Programming Laboratory

Semester : 01 Year: I
CERTIFICATE

Certified that this is the bonafide record of work done by the above student in the

laboratory during the year 2024-2025.

SIGNATURE OF FACULTY-IN-CHARGE SIGNATURE OF HEAD OF THE DEPARTMENT

Submitted for the Practical Examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


TABLE OF CONTENTS

S.No. Date List Of Experiments Page Mark Faculty


No. Signature
1. SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
A Electricity Billing
B Retail Shop Billing

C Sin Series
D Weight Of A Steel Bar
E Weight Of A Motorbike
F Electric Current In A 3 Phase Ac Circuit
2. SIMPLE STATEMENTS AND EXPRESSIONS
A Exchange The Values Of Two Variables
B Circulate The Values Of N Variables
C Calculate The Distance Between Two
Points
D Exponentiation Of A Number
E Square Root Of A Number
F Gcd Of Two Numbers
3. SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE LOOPS
(i) Number Series

A (ii) Number Series


(iii) Number Series
(i) Number Pattern
(ii) Alternate Number Pattern
B (iii) Pascal’s Triangle
(iv) Floyd’s Triangle
(i) Pyramid Pattern

C (ii) Diamond Pattern


(iii) Hour Glass Pattern
4. OPERATIONS ON LIST
A Library
B Components Of A Car
OPERATIONS ON TUPLE
C Components Of A Car
D Building Construction Material
5. OPERATIONS ON SET
A Language
B Components Of An Automobile

C Elements Of A Civil Structure

6. PROGRAMS USING FUNCTIONS

A Factorial Of A Number

B Maximum And Minimum Number In A


List
C Area Of Shapes

D List As Array

E Linear Search

F Binary Search

7. PROGRAMS USING STRINGS

A Reverse A String

B Palindrome Checking

C Count The Characters

D Replace Characters

E Anagram Checking

F Other String Operations

8. PANDAS, NUMPY, MATPLOTLIB, SCIPY PROGRAMS

A. PANDAS

i Comparing Two List

ii Using Dataframe

B. NUMPY

i Checking Non-Zero Value

ii Matrix Addition And Multiplication

C. MATPLOTLIB

i Plotting Graph

ii Plotting Bar Graph


D. SCIPY

i Hour, Minute & Seconds Conversion

ii Numerical Integration

9. FILE HANDLING

A Copying, Word Count & Longest Word

B Command Line Arguments (Word Count)

C Finding Most Frequent Words

10. EXCEPTION HANDLING

A Divide By Zero Error Using Exception


Handling
B Voter’s Age Validity

C Student Mark Range Validation

11 & 12. PYGAME LIBRARY

11 Exploring Pygame

12 Simulate Bouncing Ball Using Pygame


EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: a) ELECTRICITY BILLING
AIM:
To write a python program to calculate Electricity bill.

ALGORITHM:
Step 1: Start the program.
Step 2: Get the total units of current consumed by the customer using the variable
unit.
Step 3: Check is the units consumed less than or equal to 100 units, then the bill
amount is 0.
Step 4: Otherwise, check is units consumed between 101 to 500 then calculate the
bill amount as follows.
i. For the units consumed between 101to 200 units, calculate the charge as (unit
– 100) *2.25.
ii. For the units consumed between 201to 400 units, calculate the charge as (unit
– 200) *4.50.
iii. For the units consumed between 401to 500 units, calculate the charge as (unit
– 400) *6.00.
Step 5: Otherwise, check is units consumed above 500 then calculate the bill amount
as follows.
i. For the units consumed between 101to 400 units, calculate the charge as (unit
– 100) *4.50.
ii. For the units consumed between 401to 500 units, calculate the charge as (unit
– 400) *6.00.
iii. For the units consumed between 501to 600 units, calculate the charge as (unit
– 500) *8.00.
iv. For the units consumed between 601to 800 units, calculate the charge as (unit
– 600) *9.00.
v. For the units consumed between 801to 1000 units, calculate the charge as
(unit – 800) *10.00.
vi. For the units consumed above 1000 units, calculate the charge as (unit – 1000)
*11.00.
Step 6: Print the Bill Amount.
Step 7: Stop the program.

PROGRAM:
# EB bill
units = int(input(" Please enter Number of Units Consumed : "))
if (units <= 500):
if (units > 100) & (units < 201):
units = units - 100
amount = units * 2.25
elif (units > 200) & (units < 401):
units = units - 200
amount = 100 * 2.25 + units * 4.5
elif (units > 400):
units = units - 400
amount = 100 * 2.25 + 200 * 4.5 + units * 6
else:
amount = 0
print("First 100 units free of cost")
elif (units > 500) & (units < 1001):
if (units > 500) & (units < 601):
units = units - 500
amount = 300 * 4.5 + 100 * 6 + units * 8
elif (units > 600) & (units < 801):
units = units - 600
amount = 300 * 4.5 + 100 * 6 + 100 * 8 + units * 9
else:
units = units - 800
amount = 300 * 4.5 + 100 * 6 + 100 * 8 + 200 * 9 + units * 10
else:
units = units - 1000
amount = 300 * 4.5 + 100 * 6 + 100 * 8 + 200 * 9 + 200 * 10 + units * 11
print("Electricity Bill = ",amount)

OUTPUT:
Please enter Number of Units Consumed: 90
First 100 units free of cost
Electricity Bill = 0
Please enter Number of Units Consumed: 125
Electricity Bill = 56.25

Please enter Number of Units Consumed: 275


Electricity Bill = 562.5

Please enter Number of Units Consumed: 410


Electricity Bill = 1185.0

Please enter Number of Units Consumed: 515


Electricity Bill = 2070.0

Please enter Number of Units Consumed: 666


Electricity Bill = 3344.0

Please enter Number of Units Consumed: 850


Electricity Bill = 5050.0

Please enter Number of Units Consumed: 1200


Electricity Bill = 8750.0

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: b) RETAIL SHOP BILLING

AIM
To write a Python program for Retail shop billing (Ex. Supermarket)

ALGORITHM:
Step 1: Start the program
Step 2: Read item name, amount & price.
Step 3: Continue receiving input until all item details are read.
Step 4: Calculate Total Price += amount * price
Step 5: Print Total Price
Step 6: Stop the program.

PROGRAM:
#Retail Shopping Bill
a=0
b=0
c=0
while True:
item = input('Item: ')
a = int(input('Amount:'))
b = int(input('Price: '))
c += a * b
print('Please choose between Yes or No')
next_item = input('Is there another item? ')
if next_item != 'Yes':
break
print('Total: ', c)
OUTPUT:
Item: Apple
Amount:2
Price: 200
Please choose between Yes or No
Is there another item? Yes
Item: Orange
Amount:1
Price: 80
Please choose between Yes or No
Is there another item? Yes
Item: Grapes
Amount:2
Price: 100
Please choose between Yes or No
Is there another item? No
Total: 680

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: c) SIN SERIES

AIM:
To write a Python program for Sin series (Ex: sin x = x - x 3 /3! + x5 /5! - x 7
/7!….

ALGORITHM:
Step 1: Start the program
Step 2: Get the values x and n
Step 3: Verify the following condition i<=n
Step 4: Calculate sum = sum + sign* p/fact
Step 5: Print Sign Sum
Step 6: Stop the program.

PROGRAM:
#Sin Series
x=int(input("Enter the value of x: "))
n=int(input("Enter the value of n: "))
sign=-1
fact=i=1
Sum=0
while i<=n:
p=1
fact=1
for j in range(1,i+1):
p=p*x
fact=fact*j
sign=-1*sign
Sum=Sum+sign*p/fact
i=i+2
print("sin(",x,") =",Sum)

OUTPUT:
Enter the value of x: 2
Enter the value of n: 4
sin (2) = 0.6666666666666667

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: d) WEIGHT OF A STEEL BAR

AIM:
To write a python program to calculate weight of a steel bar.

ALGORITHM:
Step 1: Start the program
Step 2: Read the value for diameter (D)
Step 3: Calculate weight=(D*D)/162.
Step 4: Print the weight.
Step 5: Stop the program.

PROGRAM:
#Weight of a Steel bar
d=int(input("Enter a value for Diameter:"))
L=int(input("Enter a value for Length:"))
#calculate weight
weight=d*d*L/162
print('The Weight of the Steel Bar is:',weight)

OUTPUT:
Enter a value for Diameter:10
Enter a value for Length:100
The Weight of the Steel Bar is: 61.72839506172839

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: e) WEIGHT OF A MOTORBIKE

AIM:
To write a python program to find the weight of a motor bike.

ALGORITHM:
Step 1: Start the Program.
Step 2: Read the bike name.
Step 3: Retrieve the weight of the bike from the List.
Step 4: Display the weight of the bike.
Step 5: Stop the program.

PROGRAM:

# Weight of a motor bike


Bike = {"Chopper":315, "Adventurebike":250, "Dirtbike":100, "Touringbike":400,
"Sportbikes":180, "Bagger":340, "Cruiser":250, "Cafe racer":200, "Scooter":115,
"Moped":80 }
B = input("Enter bike : ")
print("Weight of", B, "is", Bike[B],"kg.")

OUTPUT:

Enter bike: Touringbike


Weight of Touringbike is 400 kg.

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:1 SIMPLE REAL LIFE OR SCIENTIFIC OR TECHNICAL PROBLEMS
DATE: f) ELECTRIC CURRENT IN A 3 PHASE AC CIRCUIT

AIM:
To write a python program to calculate electrical current in 3 phase AC circuit.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for power in Watts.
Step 3: Read the value for power factor.
Step 4: Read the value for Voltage.
Step 5: Calculate CL=P/√3*VL*pf.
Step 6: Print the value of Line current (CL).
Step 7: Stop the program.

PROGRAM:
#Electrical Current in Three Phase AC Circuit
import math
P = eval(input("Enter Power (in Watts) : "))
pf = eval(input("Enter Power factor (pf<1): "))
VL = eval(input("Enter Line Voltage (in Volts) : "))
CL = P/(math.sqrt(3)*VL*pf)
print("Line Current =", round(CL,2),"A")

OUTPUT:

Enter Power (in Watts) : 5000


Enter Power factor (pf<1): 0.839
Enter Line Voltage (in Volts) : 400
Line Current = 8.6 A

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS DATE:
a) EXCHANGE THE VALUES OF TWO VARIABLES
AIM:
To Write a python program to exchange the values of two variables
ALGORITHM:
Main function
Step 1: Start the program
Step 2: Read the values for two variables X and Y.
Step 3: Display the values before exchanging.
Step 4: Call function exchange(X,Y)
Step 5: Exchange the values of X variable and Y variable using Tuple assignment.
Step 6: End the program
Sub Function Exchange
Step 1: Start the function call.
Step 2: Exchange the values of X variable and Y variable using Tuple assignment.
Step 3: Display the values after exchanging.
Step 4: End the function call.

PROGRAM:
#Exchanging two variables
def exchange(x,y): #Function Definition
x,y = y,x #Swapping with Tuple Assignment
print("After the exchange of x,y")
print("X=",x)
print("Y=",y)

#Main Function
x=input("Enter the value of X:")
y=input("Enter the value of Y:")
print("Before the Exchange of X,Y")
print("X=",x)
print("Y=",y)
exchange(x,y) #Function call
OUTPUT:
Enter the value of X:8
Enter the value of Y:3
Before the Exchange of X,Y
X= 8
Y= 3
After the exchange of x,y
X= 3
Y= 8

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS
DATE: b) CIRCULATE THE VALUES OF N VARIABLES

AIM:
To write a python program to circulate the values of n variables
ALGORITHM:
Main function
Step 1: Start the program.
Step 2: Create an empty list.
Step 3: Read the number of elements
Step 4: Read the elements of the list and add them into list.
Step 5: Choose between Left or Right Circulate
Step 6: Call either LeftCirculate or RightCirculate function call as per user’s
choice.
Step 7: Display the modified list
Step 8: End the program
Sub Function Left Circulate
Step 1: Start the subfunction
Step 2: Assign the first element to leftVal.
Step 3: Left Shift all the elements by one position.
Step 4: Store the first element in the last position.
Step 5: Return the list
Step 6: Stop the subfunction.
Sub Function Right Circulate
Step 1: Start the subfunction
Step 2: Assign the last element to rightVal.
Step 3: Right Shift all the elements by one position.
Step 4: Store the last element in the first position.
Step 5: Return the list
Step 6: Stop the subfunction.

PROGRAM:
#Circulation of N values
def leftCirculate(lst):
leftVal = lst[0]
for index in range(1, len(lst)):
lst[index-1] = lst[index]
lst[len(lst) - 1] = leftVal
def rightCirculate(lst):
rightVal = lst[len(lst) - 1]
for index in range(len(lst) - 2, -1, -1):
lst[index+1] = lst[index]
lst[0] = rightVal
def main():
lst = []
n = int(input('Enter the Number of Elements:'))
for i in range(0,n):
a=int(input("Enter the Elements"))
lst.append(a)
print('Choices')
print('1 - Left Circulate')
print('2 - Right Circulate')
choice = int(input('Enter your Choice:'))
if choice == 1:
leftCirculate(lst)
print('Modified List:',lst)
else:
rightCirculate(lst)
print('Modified List:',lst)

if name == '_main_':
main()
OUTPUT:
Output 1:
main()
Enter the Number of Elements:5
Enter the Elements10
Enter the Elements20
Enter the Elements30
Enter the Elements40
Enter the Elements50
Choices
1 - Left Circulate
2 - Right Circulate
Enter your Choice:1
Modified List: [20, 30, 40, 50, 10]

Output 2:
main()
Enter the Number of Elements:5
Enter the Elements10
Enter the Elements20
Enter the Elements30
Enter the Elements40
Enter the Elements50
Choices
1 - Left Circulate
2 - Right Circulate
Enter your Choice:2
Modified List: [50, 10, 20, 30, 40]

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS DATE:
c) CALCULATE THE DISTANCE BETWEEN TWO POINTS
AIM:
To write a python program to calculate the distance between two points.
ALGORITHM:
Step 1: Start the program
Step 2: Read the input values for (x1,y1) & (x2,y2) coordinates
Step 3: Calculate result= ((((x2 - x1 )**2) + ((y2 - y1 )**2) )**0.5)
Step 4: Display the distance as result.
Step 5: Stop the program.
PROGRAM:
#Distance between two points
import math
x1 = int(input("enter x1 : "))
y1 = int(input("enter y1 : "))
x2 = int(input("enter x2 : "))
y2 = int(input("enter y2 : "))
p1 = [x1,y1]
p2 = [x2,y2]
distance = math.sqrt(((p2[0] - p1[0])**2) + ((p2[1] - p1[1])**2))
print("distance between",(x1,y1),"and",(x2,y2),"is : ",distance)

OUTPUT:
enter x1 : 2
enter y1 : 5
enter x2 : 5
enter y2 : 5
distance between (2, 5) and (5, 5) is: 3.0

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS
DATE: d) EXPONENTIATION OF A NUMBER
AIM:
To write a python program to find the exponentiation of a number.
ALGORITHM:
Step 1. Define a function named power()
Step 2. Read the values for base and exponent
Step 3. Check is exponent equal to 1 or not
i. if exponent is equal to 1, then return base
ii. if exponent is not equal to 1, then return (base*power(base,exp-1))
Step 4. Print the result
PROGRAM:
#Exponentiation
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

OUTPUT:
Enter base: 5
Enter exponential value: 3
Result: 125

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS
DATE: e) SQUARE ROOT OF A NUMBER

AIM:
To write a python program to find the square root of a number by Newton’s
Method.

ALGORITHM:
Step 1: Define a function named newtonSqrt().
Step 2: Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
Step 3: Use a while loop with a condition better!=approx to perform the following,
Step 3.1: Set approx = better
Step 3.2: Better = 0.5*(approx.+n/approx.)
Step 4: Print the value of approx

PROGRAM:
#Squareroot
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
print('The square root is' ,newtonSqrt(144))

OUTPUT:
The square root is 12.0

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:2 SIMPLE STATEMENTS AND EXPRESSIONS
DATE: f) GCD OF TWO NUMBERS
AIM:
To write a Python program to find GCD of two numbers.
ALGORITHM:
Step 1: Start
Step 2: Read the values for two numbers
Step 3: Check is m < n then
Step 3.1: Exchange m and n
Step 4: Otherwise
Step 4.1: Calculate remainder = m mod n
Step 5: Repeat the following steps until remainder not equal to 0
Step 5.1: Assign m = n
Step 5.2: Assign n = remainder
Step 5.3: Calculate remainder = m mod n
Step 6: Display the GCD
Step 7: Stop the Program.
PROGRAM:
#GCD
m = int(input("Enter a number:"))
n = int(input("Enter another number:"))
if n > m:
m,n = n,m #Exchange m and n
rem = m % n
while (rem != 0):
m=n
n = rem
rem = m % n
print ("gcd of given numbers is :", n)

OUTPUT:
Enter a number:8
Enter another number:16
gcd of given numbers is : 8

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:3 SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE LOOPS
DATE: a) (i) NUMBER SERIES
AIM:
To write a python program using conditional and iterative statements for printing
Number Series.
Ex. “1+2+…+n=”.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for n.
Step 3: Create an empty list.
Step 4: For i value between 1 and n Repeat step 5,6 & 7
Step 5: In each iteration, the value of i is added to list.
Step 6: Display the value of i.
Step 7: ‘+’ operator is printed between each term.
Step 8: Display ‘=’ & the sum of i values.
Step 9: Stop the program.
PROGRAM:
n=int(input("Enter a number: ")) a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()

OUTPUT:
Enter a number: 4
1 + 2 + 3 + 4 = 10

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 a) (ii) NUMBER SERIES
DATE:

AIM:
To write a python program using conditional and iterative statements for printing
Number Series 12+22+32+….+N2.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for n.
Step 3: Create an empty list.
Step 4: For i value between 1 and n Repeat step 5,6 & 7
Step 5: In each iteration, the value of i2 is added to list.
Step 6: Display the value of i.
Step 7: ‘^ 2 +’ displayed between each term.
Step 8: Display ‘^2 =’ & the sum of i2 values.
Step 9: Stop the program.

PROGRAM:
n = int(input('Enter a number: '))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("^ 2 +",sep=" ",end=" ")
a.append(i*i)
print("^ 2 =",sum(a))
print()

OUTPUT:
Enter a number: 5
1 ^ 2 + 2 ^ 2 + 3 ^ 2 + 4 ^ 2 + 5 ^ 2 = 55

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 a) (iii) NUMBER SERIES
DATE:

AIM:
To write a python program using conditional and iterative statements for printing
Number Series 13+23+33+….+N3.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for n.
Step 3: Create an empty list.
Step 4: The while loop iterates for i value between 1 and n.
Step 5: In each iteration, the value of i3 is added to list.
Step 6: Display the value of i.
Step 7: ‘^ 3 +’ displayed between each term.
Step 8: Display ‘^3 =’ & the sum value at the end.
Step 9: Stop the program.
PROGRAM:
n = int(input('Enter a Number:'))
a=[]
i=1
while i<=n:
print(i,sep=" ",end=" ")
if(i<n):
print("^ 3 +",sep=" ",end=" ")
a.append(i*i*i)
i+=1
print("^ 3 =",sum(a))
print()

OUTPUT:
Enter a Number:8
1 ^ 3 + 2 ^ 3 + 3 ^ 3 + 4 ^ 3 + 5 ^ 3 + 6 ^ 3 + 7 ^ 3 + 8 ^ 3 = 1296

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 b) (i) NUMBER PATTERN
DATE:

AIM:
To write a python program using iterative statement (for loop) to print Number
Pattern.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the number of rows.
Step 3: for i in range of rows.
Step 4: for j in range of i.
Step 5: Display the value of i.
Step 6: Print a new line after each row.
Step6: Stop the program.
PROGRAM:
rows = 6
# if you want user to enter a number, uncomment the below line
# rows = int(input('Enter the number of rows'))
# outer loop
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')

OUTPUT:
1
22
333
4444
55555

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 b) (ii) ALTERNATE NUMBER PATTERN
DATE:
AIM:
To write a python program using iterative statement (while loop) to print Alternate
Number Pattern.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the number of rows.
Step 3: Initialize i as 1.
Step 4: Repeat Steps 5 – 9, until i<= rows.
Step 5: Initialize j as 1.
Step 6: Repeat Steps 7,8 until j<=i.
Step 7: Compute i * 2 – 1 and display it.
Step 8: Increment j.
Step 9: Increment i.
Step 10: Stop the program.

PROGRAM:
rows = 5
i=1
while i <= rows:
j=1
while j <= i:
print((i * 2 - 1), end=" ")
j=j+1
i=i+1
print('')

OUTPUT:
1
33
555
7777
99999

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 b) (iii) PASCAL’S TRIANGLE
DATE:

AIM:
To write a python program using iterative statements (for loop) to display Pascal’s
Triangle Pattern.

ALGORITHM:
Step1: Start the program.
Step 2: Define the number of rows.
Step 3: for i in range of rows, repeat steps 4-8.
Step 4: for j in range of 1 to rows -1, repeat step 5.
Step 5: Display the space.
Step 6: for k in range of 0 to i+1, repeat step 7.
Step 7: Compute nCr(i,k) using fact function.
Step 8: Display the computed value.
Step 9: Move to next row of the triangle.
Step 10: Stop the program.

PROGRAM:
#pascal's triangle
def fact(n):
res = 1
for c in range(1,n+1):
res = res * c
return res
rows = int(input("Enter the Number of rows:"))
for i in range(0, rows):
for j in range(1, rows - i):
print(" ",end="")
for k in range(0, i+1):
coff = int(fact(i)/(fact(k)*fact(i-k)))
print(" ",coff,end="")
print()
OUTPUT:
Enter the Number of rows:8
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:3 b) (iv) FLOYD’S TRIANGLE
DATE:

AIM:
To Write a Python program using iterative statement (while loop) to display Floyd’s
Triangle Pattern.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for rows.
Step 3: Initialize number and i as 1.
Step 4: Repeat step 5 - 10, until i<=rows.
Step 5: Assign j as 1.
Step 6: Repeat steps 7&8, until j<=i.
Step 7: Print number.
Step 8: Increment number and j by 1.
Step 9: Increment i by 1.
Step 10: Move to next row.
Step 11: Stop the program.

PROGRAM:
# Python Program to Print Floyd's Triangle
rows = int(input("Please Enter the total Number of Rows : "))
number = 1
print("Floyd's Triangle")
i=1
while(i <= rows):
j=1
while(j <= i):
print(number, end = ' ')
number = number + 1
j=j+1
i=i+1
print()
OUTPUT:
Please Enter the total Number of Rows: 10
Floyd's Triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:3 c) (i) PYRAMID PATTERN
DATE:

AIM:
To write a python program using iterative statements to print Pyramid Pattern.
ALGORITHM:
Step 1: Start the program
Step 2: Read the value for N.
Step 3: for i value between 1 to N+1,repeat steps 4,5.
Step 4: Print (N-i) times space.
Step 5: Print (2*i)-1 times *.
Step 6: Display Pyramid pattern.
Step 7: Stop the program.
PROGRAM:
N = int(input("Enter number of Rows : "))
print("Pyramid Pattern : ")
for i in range(1,N+1,1):
print(" "*(N-i),end="")
print(" * "*((2*i)-1))

OUTPUT:
Enter number of Rows : 10
Pyramid Pattern :
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:3 c) (ii) DIAMOND PATTERN
DATE:

AIM:
To write a python program with iterative statements to print Diamond Pattern.

ALGORITHM:
Step1: Start the program.
Step2: Assign n to 5.
Step3: Compute k as 2 * n - 2.
Step4: Using nested for loop print the triangle shape.
Step5: Now compute k as n - 2.
Step6: Using nested for loop print the inverted triangle.
Step7: Stop the program.

PROGRAM:
def pattern(n):
k=2*n-2
for i in range(0 , n):
for j in range(0 , k):
print(end=" ")
k =k - 1
for j in range(0 , i + 1 ):
print("* ", end="")
print("\r")
k=n-2
for i in range(n, -1, -1):
for j in range(k , 0 , -1):
print(end=" ")
k=k+1
for j in range(0, i + 1):
print("* ",end="")
print("\r")
pattern(5)
OUTPUT:
*
**
***
****
*****
******
*****
****
***
**
*

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO.3 c) (iii) HOUR GLASS PATTERN
DATE:

AIM:
To write a python program using iterative statements to print Hour Glass Pattern.

ALGORITHM:
Step 1: Start the program.
Step 2: Assign n to 5.
Step 3: Now compute k as n - 2.
Step 4: Using nested for loop print the inverted triangle.
Step 5: Compute k as 2 * n - 2.
Step 6: Using nested for loop print the triangle shape.
Step 7: Stop the program.

PROGRAM:
def pattern(n):
k=n-2
for i in range(n , -1 , -1):
for j in range(k , 0 , -1):
print(end=" ")
k=k+1
for j in range(0, i+1):
print("* ", end="")
print("\r")
k=2*n-2
for i in range(0, n+1):
for j in range(0, k):
print(end=" ")
k=k-1
for j in range(0, i + 1):
print("* ", end="")
print("\r")
pattern(5)
OUTPUT:

******
*****
****
***
**
*
*
**
***
****
*****
******

RESULT:
Thus, the above program was successfully executed and verified.
Ex.No.4 OPERATIONS ON LIST

Date: a) Library
AIM:
To write a python program to implement operations in a library list.
ALGORITHM:
Step 1: Start the program
Step 2: Declare variable library to list the items present in a library
Step 3: Do the operations of list like append, pop, sort, remove, etc on the list.
Step 4: Print the result.
Step 5: Stop the program.
PROGRAM:
# declaring a list of items in a Library
library
=['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','Ebooks']
print('Library: ',library)
print('first element: ',library[0])
print('fourth element: ',library[3])
print('Items in Library from 0 to 4 index: ',library[0: 5])
library.append('Audiobooks')
print('Library list after append Audiobooks: ',library)
print('index of \'Newspaper\': ',library.index('Newspaper'))
library.sort()
print('after sorting: ', library);
print('Popped elements is: ',library.pop())
print('after pop(): ', library);
library.remove('Maps')
print('after removing \'Maps\': ',library)
library.insert(2, 'CDs')
print('after insert CDs: ', library)
print(' Number of Elements in Library list : ',len(library))
OUTPUT:
Library: ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps', 'Prints',
'Documents', 'Ebooks']
first element: Books
fourth element: Manuscripts
Items in Library from 0 to 4 index: ['Books', 'Periodicals', 'Newspaper', 'Manuscripts',
'Maps']
Library list after append Audiobooks: ['Books', 'Periodicals', 'Newspaper',
'Manuscripts', 'Maps', 'Prints', 'Documents', 'Ebooks', 'Audiobooks']
index of 'Newspaper': 2
after sorting: ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',
'Newspaper', 'Periodicals', 'Prints']
Popped elements is: Prints
after pop(): ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',
'Newspaper', 'Periodicals']
after removing 'Maps': ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts',
'Newspaper', 'Periodicals']
after insert CDs: ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks', 'Manuscripts',
'Newspaper', 'Periodicals']
Number of Elements in Library list : 8

RESULT:
Thus, the above program was successfully executed and verified.
Ex.No.4 OPERATIONS ON LIST

Date: b) Components Of A Car

AIM:
To write a python program to implement operations in a car list.
ALGORITHM:
Step1: Start the program.
Step2: Declare a list variable car to list the components of a car.
Step3: Print the elements of list.
Step4: Stop the program.
PROGRAM:
Car_Main_components = ['Chassis','Engine',{'Body':['Steering system','Braking
system','Suspension']},{'Transmission_System':['Clutch','Gearbox','Differential','Axle']}]
Car_Auxiliaries = ['car lightening system','wiper and washer system','power door locks
system','car instrument panel','electric windows system','car park system']
def fnPrint(L):
for ele in L:
if(isinstance(ele,dict)):
for k,v in (ele.items()):
print("\t",k,":",", ".join(v))
continue
print("\t",ele)
else:
print("\t",ele)
print("Car Main Components:")
fnPrint(Car_Main_components)
print("Car Auxiliaries:")
fnPrint(Car_Auxiliaries)
OUTPUT:
Car Main Components:
Chassis
Engine
Body : Steering system, Braking system, Suspension
Transmission_System : Clutch, Gearbox, Differential, Axle
Car Auxiliaries:
car lightening system
wiper and washer system
power door locks system
car instrument panel
electric windows system
car park system

RESULT:
Thus, the above program was successfully executed and verified.
Ex.No.4 OPERATIONS ON TUPLE
Date: c) Components Of A Car
AIM:
To write a python program to implement operations in a car tuple.
ALGORITHM:
Step1: Start the program.
Step2: Declare a car tuple to list the components of a car.
Step3: Print the elements of Tuple.
Step4: Stop the program.
PROGRAM:
#declaring a tuple for car components
car = ('Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt')
#printing the tuple
print("Components of a Car:",car)
#printing first element
print("First Element:",car[0])
#printing fourth element
print("Fourth Element:",car[3])
#printing tuple elements from 0th index to 4th index
print("Components of a car from 0 to 4 index:",car[0:5])
#printing tuple -7th element
print("-7th Element:",car[-7])
#finding index of a specified element
print('Index of \'Alternator\': ',car.index('Alternator'))
#Number of elements in car tuple
print("Number of element \'Seat Belt\' in car tuple:",car.count('Seat Belt'))
#Length of car tuple
print("Length of elements in car tuple:",len(car))
OUTPUT:
Components of a Car: ('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break',
'Seat Belt')
First Element: Engine
Fourth Element: Radiator
Components of a car from 0 to 4 index: ('Engine', 'Battery', 'Alternator', 'Radiator',
'Steering')
-7th Element: Engine
Index of 'Alternator': 2
Number of element 'Seat Belt' in car tuple: 1
Length of elements in car tuple: 7

RESULT:
Thus, the above program was successfully executed and verified.
Ex.No.4 OPERATIONS ON TUPLE
Date: d) Building Construction Material
AIM:
To write a python program to implement operations on Tuple for building
construction material.
ALGORITHM:
Step1: Start the program.
Step2: Declare a dictionary building to list the elements of a civil structure.
Step3: Do the dictionary operations add, update, pop and length.
Step4: Print the result.
Step5: Stop the program.
PROGRAM:
BuildingMaterials = ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and
Fixtures', 'Natural Stones','Doors', 'Windows', 'Modular Kitchen',
'Sand','Aggregates','Tiles')
ElectricalMaterials = ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular
switches and sockets', 'Electric Panels', 'Switch Gear')
print("Created tuple : ")
print("Building Materials : ",BuildingMaterials)
print("Electrical Materials : ",ElectricalMaterials)
# Accessing elements by index
print("First element in tuple : ",BuildingMaterials[0])
print("Last element in tuple : ",BuildingMaterials[-1])
# Slicing
print("First 5 elements in tuple : ",BuildingMaterials[0:5])
# length of tuple
print("Length of tuple : ",len(BuildingMaterials))
# Concatenation,repetition
print("Concatenation operation")
AllMaterials = BuildingMaterials+ElectricalMaterials
print("All materials")
print(AllMaterials)
print("Repetition operation")
print(AllMaterials*2)
# Membership operator
SearchMaterial = input("Enter material to search : ")
if SearchMaterial in AllMaterials:
print("Material present in tuple.")
else:
print("Material not present in tuple.")
# Iteration operation
print("Iteration operation")
print("Materials required for construction of a building: ")
for mat in AllMaterials:
print(mat)
OUTPUT:
Created tuple :
Building Materials : ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and
Fixtures', 'Natural Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates',
'Tiles')
Electrical Materials : ('Conduit Pipes and Fittings', 'Wires and Cables', 'Modular
switches and sockets', 'Electric Panels', 'Switch Gear')
First element in tuple : Cement
Last element in tuple : Tiles
First 5 elements in tuple : ('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware
and Fixtures')
Length of tuple : 12
Concatenation operation
All materials
('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures', 'Natural
Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles', 'Conduit
Pipes and Fittings', 'Wires and Cables', 'Modular switches and sockets', 'Electric
Panels', 'Switch Gear')
Repetition operation
('Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and Fixtures', 'Natural
Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates', 'Tiles', 'Conduit
Pipes and Fittings', 'Wires and Cables', 'Modular switches and sockets', 'Electric
Panels', 'Switch Gear', 'Cement', 'Bricks', 'Blocks', 'Wooden Products', 'Hardware and
Fixtures', 'Natural Stones', 'Doors', 'Windows', 'Modular Kitchen', 'Sand', 'Aggregates',
'Tiles', 'Conduit Pipes and Fittings', 'Wires and Cables', 'Modular switches and
sockets', 'Electric Panels', 'Switch Gear')
Enter material to search : Tiles
Material present in tuple.
Iteration operation
Materials required for construction of a building:
Cement
Bricks
Blocks
Wooden Products
Hardware and Fixtures
Natural Stones
Doors
Windows
Modular Kitchen
Sand
Aggregates
Tiles
Conduit Pipes and Fittings
Wires and Cables
Modular switches and sockets
Electric Panels
Switch Gear

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 5 a. OPERATIONS ON SET
DATE: LANGUAGE
AIM:
To write a python program to implement operations in a set using components of a
Language.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare two sets with components of language in it.
Step 3: Do the set operations union, intersection, difference and symmetric difference.
Step 4: Display the result.
Step 5: Stop the program.
PROGRAM:
L1={'Pitch','Syllabus','Script','Grammar','Sentences'}
L2={'Grammar','Syllabus','Context','Words','Phonetics'}
#set Union
print("Union of L1 and L2 is",L1|L2)
#set Intersection
print("Intersection of L1 and L2",L1&L2)
#set difference
print("Difference of L1 and L2 is",L1-L2)
#set symmetric difference
print("Symmetric Difference of L1 an L2 is",L1^L2)
OUTPUT:
Union of L1 and L2 is {'Syllabus', 'Script', 'Words', 'Context', 'Phonetics', 'Pitch', 'Grammar',
'Sentences'}
Intersection of L1 and L2 {'Grammar', 'Syllabus'}
Difference of L1 and L2 is {'Script', 'Sentences', 'Pitch'}
Symmetric Difference of L1 an L2 is {'Phonetics', 'Pitch', 'Script', 'Words', 'Context',
'Sentences'}

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 5 b. OPERATIONS ON SET
DATE: COMPONENTS OF AN AUTOMOBILE
AIM:
To write a python program to implement operations on an automobile set.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare set variables car and motorbike to list the components of a car and
motorbike.
Step 3: Do the set operations union, intersection, difference and symmetric difference.
Step 4: Display the result.
Step 5: Stop the program.
PROGRAM:
#declaring a set of Components of a car
car = {'Engine','Battery','Alternator','Radiator','Steering','Break','Seat Belt'}
#declaring a set of Components of a motorbike
motorbike={'Engine','Fuel tank','Wheels','Gear','Break'}
#Elements of the set car
print('Components of Car: ',car)
#Elements of the set motorbike
print('Components of motorbike: ',motorbike)
#union operation
print('Union of car and motorbike: ',car | motorbike)
#intersection operation
print('Intersection of car and motorbike: ',car & motorbike)
#difference operation
print('Difference operation: ', car - motorbike)
#Symmetric difference
print('Symmetric difference operation: ',car ^ motorbike)
OUTPUT:
Components of Car: {'Battery', 'Seat Belt', 'Engine', 'Radiator', 'Break', 'Alternator', 'Steering'}
Components of motorbike: {'Fuel tank', 'Engine', 'Gear', 'Wheels', 'Break'}
Union of car and motorbike: {'Fuel tank', 'Engine', 'Radiator', 'Seat Belt', 'Break', 'Alternator',
'Steering', 'Battery', 'Gear', 'Wheels'}
Intersection of car and motorbike: {'Break', 'Engine'}
Difference operation: {'Radiator', 'Seat Belt', 'Alternator', 'Steering', 'Battery'}
Symmetric difference operation: {'Fuel tank', 'Radiator', 'Seat Belt', 'Alternator', 'Steering',
'Battery', 'Gear', 'Wheels'}
RESULT:
Thus, the above program was successfully executed and verified.
EX.NO: 5 c. OPERATIONS ON DICTIONARY
DATE: ELEMENTS OF A CIVIL STRUCTURE
AIM:
To write a python program to implement operations on elements of a civil structure
dictionary.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare a dictionary building to list the elements of a civil structure.
Step 3: Do the dictionary operations add, update, pop and length.
Step 4: Display the result.
Step 5: Stop the program.
PROGRAM:
#declare a dictionary building
building={1:'foundation',2:'floor',3:'beams',4:'columns',5:'roof',6:'stair'}
#Elements in dictionary
print('Elements in dictionary building: ',building)
#length of a dictionary
print('Length of the dictionary building: ',len(building))
#value of the key 5
print('The value of the key 5',building.get(5))
#update key 6 :stair as lift
building.update({6:'lift'})
print('After updation of stair as lift: ',building)
#Add element window in the dictionary
building[7]='window'
print('After adding window: ',building)
#using pop operation to remove element
building.pop(3)
print('After removing element beams from building: ',building)
OUTPUT:
Elements in dictionary building: {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof',
6: 'stair'}
Length of the dictionary building: 6
The value of the key 5 roof
After updation of stair as lift: {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof', 6:
'lift'}
After adding window: {1: 'foundation', 2: 'floor', 3: 'beams', 4: 'columns', 5: 'roof', 6: 'lift', 7:
'window'}
After removing element beams from building: {1: 'foundation', 2: 'floor', 4: 'columns', 5: 'roof',
6: 'lift', 7: 'window'}

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 6 PROGRAMS USING FUNCTIONS
DATE: a) FACTORIAL OF A NUMBER

AIM:
To write a python program to calculate the factorial of a number using
functions.

ALGORITHM:
Step 1: Start the program.
Step 2: Read a number from user.
Step 3: If number=1, then return 1.
Step 4: Otherwise,
calculate the factorial of that number using recursive function.
Step 5: Print the result.
Step 6: Stop the program.

PROGRAM:
#factorial using function
def fnfact(N):
if(N==0):
return 1
else:
return(N*fnfact(N-1))
Num = int(input("Enter Number : "))
print("Factorial of", Num, "is", fnfact(Num))

OUTPUT:
Enter Number : 5
Factorial of 5 is 120

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 6 PROGRAMS USING FUNCTIONS
DATE: b) MAXIMUM AND MINIMUM NUMBER IN A LIST

AIM:
To write a python program to find the largest and smallest number in
a list using functions.

ALGORITHM:
Step 1: Start the program.
Step 2: Read number of elements from user.
Step 3: Read the elements of list using for loop.
Step 4: Find the largest element from list using max() function.
Step 5: Find the smallest element from list using min() function.
Step 5: Print the result.
Step 6: Stop the program.

PROGRAM:

# maximum and minimum number using function


def maxmin():
lst=[]
a=int(input("Enter the number of elements: "))
for i in range(1,a+1):
num=int(input("Enter the values one by one: "))
lst.append(num)
maximum = max(lst)
minimum = min(lst)
return maximum,minimum
output=maxmin()
print("The smallest value in the list is: ",output[1])
print("The largest value in the list is: ",output[0])
OUTPUT:
Enter the number of elements: 5
Enter the values one by one: 65
Enter the values one by one: 78
Enter the values one by one: 52
Enter the values one by one: 99
Enter the values one by one: 56
The smallest value in the list is: 52
The largest value in the list is: 99

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 6 PROGRAMS USING FUNCTIONS
DATE: c) AREA OF SHAPES

AIM:
To write a python program to implement Area of Shapes using
functions.
ALGORITHM:
Step 1: Start the program
Step 2: Define calculate area of shape
Step 3: if shape name “rectangle”
get the length & breadth value then
calculate rect_area =l * b
display rectangle area.
Step 4: elif shape name “square”
get the square’s side length value then
calculate sqt_area =s*s
display square area.
Step 5: elif shape name “triangle”
get the height & base length value then
calculate tri_area =0.5*b*h
display triangle area.
Step 6: elif shape name “circle”
get the radius value then
calculate circle_area = pi* r *r
display circle area.
Step 7: elif shape name “parallelogram”
get base & height length value then
calculate para_area = b *h
display parallelogram area.
Step 8: else display Sorry! This shape is not available.
Step 9: Stop the program.
PROGRAM:
#Area of shapes
def calculate_area(name):
name=name.lower()
if name=="rectangle":
l=int(input("Enter rectangle's length:"))
b = int(input("Enter rectangle's breadth: "))
rect_area =l * b
print(f"The area of rectangle is {rect_area}.")
elif name =="square":
s = int(input("Enter square's side length: "))
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 base length: "))
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
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:"))
para_area=b * h
print(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
if name == " main ":
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to
find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find: circle
Enter circle's radius length: 6
The area of circle is 113.03999999999999.

Calculate Shape Area


Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length:5
Enter rectangle's breadth: 6
The area of rectangle is 30.
Calculate Shape Area
Enter the name of shape whose area you want to find: square
Enter square's side length: 5
The area of square is 25.

Calculate Shape Area


Enter the name of shape whose area you want to find: triangle
Enter triangle's height length: 8
Enter triangle's base length: 5
The area of triangle is20.0.

Calculate Shape Area


Enter the name of shape whose area you want to find: parallelogram
Enter parallelogram's base length: 6
Enter parallelogram's height length:4
The area of parallelogram is 24.

Calculate Shape Area


Enter the name of shape whose area you want to find: trapezium
Sorry! This shape is not available

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:6 PROGRAMS USING FUNCTIONS
DATE: d) LIST AS ARRAY

AIM:
To write a Python program to perform various operations on array.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a List.
Step 3: Convert it into an Array
Step 4: Perform slicing operation and display the result
Step 5: Print the index of an element.
Step 6: Update an element of the array and display the result.
Step 7: Remove an element and display the result.
Step 8: Append an element to array and display the result.
Step 9: Insert an element to array and display the result.
Step 10: Perform pop operation and display the result.
Step 11: Find the sum of array and display the result.
Step 12: Stop the program.

PROGRAM:
import array as arr
# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', [] )
#converting a list into Array
a.fromlist(l)
print("\nList as Array: ")
for i in a:
print(i, end =" ")
# print elements of a range using Slice operation
Sliced_array = a[3:8]
print("\n\nSlicing elements in a range 3-8: ")
print(Sliced_array)
# print index of 1st occurrence of 6
print ("\nThe Index of 6 is : ", end =" ")
print (a.index(6))
# updating a element in an array
a[2] = 6
print("\nArray after Updating 2nd index : ", end =" ")
for i in range(0, 10):
print (a[i], end =" ")
print()
#removing elements in an array
a.remove(6)
print("\nArray after Removing first occurrence of 6 : ", end =" ")
for i in range(0, 9):
print (a[i], end =" ")
print()
#append operation
a.append(11)
print("\nArray after Append operation : ", end =" ")
for i in range(0, 10):
print (a[i], end =" ")
print()
#insert operation
a.insert(2,3)
print("\nArray after Insert operation @ 2nd index: ", end =" ")
for i in range(0, 11):
print (a[i], end =" ")
print()
#pop operation
ele = a.pop()
print("\nThe Popped Element is:",ele)
print("\nArray after Pop operation : ", end =" ")
for i in range(0, 10):
print (a[i], end =" ")
print()
#Sum of an array
sum = 0
for i in range(0, 11):
sum = sum + i
print("\nThe sum of the array is:",sum)
OUTPUT:
List as Array:
1 2 3 4 5 6 7 8 9 10

Slicing elements in a range 3-8:


array('i', [4, 5, 6, 7, 8])

The Index of 6 is : 5

Array after Updating 2nd index : 1 2 6 4 5 6 7 8 9 10

Array after Removing first occurrence of 6 : 1 2 4 5 6 7 8 9 10

Array after Append operation : 1 2 4 5 6 7 8 9 10 11

Array after Insert operation @ 2nd index: 1 2 3 4 5 6 7 8 9 10 11

The Popped Element is: 11

Array after Pop operation : 1 2 3 4 5 6 7 8 9 10

The sum of the array is: 55

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:6 PROGRAMS USING FUNCTIONS
DATE: e) LINEAR SEARCH

AIM:
To write a python program with function to perform Linear Search.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the search element from the user
Step 3: Compare, the search element with the first element in the list.
Step 4: If both are matching, then
display “Key found” and terminate the function.
Step 5: If both are not matching, then
compare search element with the next element in the list.
Step 6: Repeat step 3 and 4 until
the search element is compared with the last element in the list
Step 7: If the last element in the list is also doesn’t match, then
display “Key not found” and terminate the function.
Step 8: Stop the program.

PROGRAM:
def linearSearch(A,item):
found = False
for i in range(0,n):
if key == A[i]:
found = True
print("Key Found")
break
else:
continue
if found == False:
print("Key not Found")
#driver function
X=[]
n = int(input("Enter the number of elements:"))
for i in range(0,n):
a=int(input("Enter Element:"))
X.append(a)
key = int(input("Enter The Element To Be Searched:"))
linearSearch(X,key)
OUTPUT:
Enter the number of elements:6
Enter Element:34
Enter Element:56
Enter Element:23
Enter Element:45
Enter Element:78
Enter Element:67
Enter The Element To Be Searched:65
Key not Found

RESULT:
Thus, the above program was successfully executed and verified.
EX.NO:6 PROGRAMS USING FUNCTIONS
DATE: f) BINARY SEARCH
AIM:
To write a python program with function to perform Binary Search.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the search element from the user.
Step 3: Find the middle element in the sorted list.
Step 4: Compare, the element with the middle element in the sorted list.
Step 5: If both are matching, then
display “Key Found” and terminate the function.
Step 6: If both are not matching, then
check whether the search element is smaller or larger than the
middle element.
Step 8: If the search element is smaller than the middle element, then
repeat step 2,3 4 & 5 for the left sublist of the middle element.
Step 9: If the search element is larger than the middle element, then
repeat step 2,3 4 & 5 for the right sublist of the middle element.
Step 10: Repeat the same process until we find the search element in the list
or until sublist contains only one element.
Step 11: If that element also doesn’t match with the search element, then
display “Key not found in the list” and terminate the function.
Step 12: Stop the program.
PROGRAM:
def binarySearch(A,item):
first = 0
last = len(A) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if A[midpoint] == item:
found = True
else:
if item < A[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
if found == True:
print("Key Found")
return
else:
print("Key not Found")
return
X=[]
n = int(input("Enter the number of elements:"))
print("Enter the numbers in sorted order:")
for i in range(0,n):
a=int(input("Enter Element:"))
X.append(a)
key = int(input("Enter The Element To Be Searched:"))
binarySearch(X,key)

OUTPUT:
Enter the number of elements:5
Enter the numbers in sorted order:
Enter Element:23
Enter Element:33
Enter Element:45
Enter Element:65
Enter Element:78
Enter The Element To Be Searched:35
Key not Found

RESULT:
Thus, the above program was successfully executed and verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: a) REVERSE A STRING

AIM:
To write a python program to reverse the given string.
ALGORITHM:
Step 1: Start the program.
Step 2: Read a string from user.
Step 3: Perform reverse operation.
Step 4: Print the result.
Step 5: Stop the program.
PROGRAM:
#reverse a string
def reverse(string):
string = string[::-1]
return string
s ="Firstyear"
print("The original string is: ",end="")
print(s)
print("The reversed string is : ",end="")
print(reverse(s))

OUTPUT:
The original string is: Firstyear
The reversed string is : raeytsriF

RESULT:
Thus, the above program was executed and the output was verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: b) PALINDROME CHECKING

AIM:
To write a python program to check whether the given string is
palindrome or not.
ALGORITHM:
Step 1: Start the program.
Step 2: Read a string from user.
Step 3: Perform reverse operation of the input string.
Step 4: Check whether the strings are equal or not.
Step 5: If both are equal print it is a palindrome.
Step 6: Otherwise print it is not a palindrome.
Step 7: Stop the program.
PROGRAM:
#palindrome
string=input(("Enter a string: "))
if(string==string[::-1]):
print("The string is a palindrome.")
else:
print("Not a palindrome.")

OUTPUT:
Enter a string:malayalam
The string is a palindrome.

RESULT:
Thus, the above program was executed and the output was verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: c) COUNT THE CHARACTERS

AIM:
To write a python program to find the number of vowels and
characters present in a string.
ALGORITHM:
Step 1: Start the program.
Step 2: Read a string from user.
Step 3: Count the number of vowels present in the string.
Step 4: Count the number of characters present in the string.
Step 5: Display the result.
Step 6: Stop the program
PROGRAM:
# To Count Total Characters & Vowels in a String
test_str = input("Please Enter Your Own String : ")
vowels = 0
total = 0
# To Count Vowels in a String
for i in test_str:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A'
or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowels = vowels + 1
# To Count Total Characters in a String
for i in test_str:
total = total + 1
print("Total Number of Vowels in this String = ", vowels)
print("Total Number of Characters in this String = ", total)
OUTPUT:
Please Enter Your Own String : I am a programmer
Total Number of Vowels in this String = 6
Total Number of Characters in this String = 17

RESULT:
Thus, the above program was executed and the output was verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: d) REPLACE CHARACTERS

AIM:
To write a python program to replace characters in a string.
ALGORITHM:
Step 1: Start the program.
Step 2: Store the input string in a variable.
Step 3: Store the pattern to be replaced in a variable.
Step 4: Store the pattern to replace with in another variable.
Step 5: Replace the old string with new string using replace() method.
Step 6: Stop the program.
PROGRAM:
# replace characters in a string
def replaceABwithC(input, pattern, replaceWith):
return input.replace(pattern, replaceWith)

# Driver program
if name == " main ":
input = 'helloABworld'
pattern = 'AB'
replaceWith = 'C'
print (replaceABwithC(input,pattern,replaceWith))

OUTPUT:
helloCworld

RESULT:
Thus, the above program was executed and the output was verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: e) ANAGRAM CHECKING
AIM:
To write a python program to check whether the given strings are anagram
are not.
ALGORITHM:
Step 1: Start the program.
Step 2: Read two input strings.
Step 3: Check whether the length of the strings is same.
Step 4: Compare the sorted strings.
Step 5: if both the length and sorted strings are same then
Step 5.1: Display that both the strings are Anagram
Step 6: Otherwise, display it as not Anagram.
Step 7: Stop the program
PROGRAM:
#to check for anagram string
def Anagram(str1,str2):
flag = False
if(len(str1) == len(str2)):
if (sorted(str1)== sorted(str2)):
flag = True
if(flag == True):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
#driver function
A = input("Enter the First String:")
B = input("Enter the Second String:")
Anagram(A,B)
OUTPUT:
Enter the First String:earth
Enter the Second String:heart
earth and heart are anagram.

RESULT:
Thus, the above program was executed and the output was verified.
EX NO: 7 PROGRAMS USING STRINGS
DATE: f) OTHER STRING OPERATIONS

AIM:
To write a python program to perform various operations on string.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input string.
Step 3: Perform various operations on the input.
Step 4: Find the string length and display the result.
Step 5: Compare both the strings and display the result.
Step 6: Copy the input string to another string and display the new string.
Step 7: Read two strings then perform concatenation and display the result.
Step 8: Store a list of names in a string.
Step 9: Split the names then perform sorting and display the result.
Step 10: Stop the program
PROGRAM:
#other string operations
#string length
print("Finding String Length")
string = input("Enter a String:")
print("Length of the String = ",len(string),"\n")
#string comparison
print("Comparing two strings")
string1 = input("Enter String1:")
string2 = input("Enter String2:")
if string1 == string2:
print("Both strings are Equal\n")
else:
print("Strings are not Equal\n")
#string copy
print("Copying one string to another")
strg = input("Enter a string:")
str_copy = strg
print("The Copied String is ",str_copy,"\n")
#string concatenation
print("String Concatenation")
str1 = input("Enter the First String:")
str2 = input("Enter the Second String:")
str3 = str1 + str2
print("String after Concatenation =",str3,"\n")
#string sorting
print("Sorting names in ascending order")
my_str = "Venila Daniel Gandhi Siddiq Alice Elora Bargavi"
words = my_str.split()
words.sort()
print("The Sorted Names are:")
for word in words:
print(word)
OUTPUT:
Finding String Length
Enter a String:Python programming
Length of the String = 18

Comparing two strings


Enter String1:Hello
Enter String2:Hai
Strings are not Equal

Copying one string to another


Enter a string:Donkey
The Copied String is Donkey

String Concatenation
Enter the First String:Hello
Enter the Second String:World!
String after Concatenation = HelloWorld!

Sorting names in ascending order


The Sorted Names are:
Alice
Bargavi
Daniel
Elora
Gandhi
Siddiq
Venila

RESULT:
Thus, the above program was executed and the output was verified.
Ex No: 8 A) PANDAS
Date: i) COMPARING TWO LIST

AIM:
To write a python program to compare the elements of the two Pandas Series
using Pandas’ library.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 10]
ALGORITHM:
Step 1: Start the program.
Step 2: Import pandas from python standard libraries.
Step 3: Assign data series as ds1 and ds2.
Step 4: Compare the elements of the series and
print equals, greater than and less than comparison results.
Step 5: Stop the program.
PROGRAM:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)
OUTPUT:
Series1:
02
14
26
38
4 10
dtype: int64
Series2:
01
13
25
37
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Less than:
0 False
1 False
2 False
3 False
4 False
dtype: bool

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO: 8 A) PANDAS
DATE: ii) USING DATAFRAME

AIM:
To implement a python program with Pandas’ modules using Dataframe to
print List of tuples and dictionary.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare and define list of tuples and dictionary with some values.
Step 3: Import the module pandas using the keyword, import pandas.
Step 4: Use alias name for the pandas module as pd.
Step 5: Using Dataframe() function, generate the values for List of tuples &
Dictionary
Step 6: Print the datas of List of tuples and Dictionary
Step 7: Stop the Program.
PROGRAM:
import pandas as pd
list=[("OlgaRajee","Ranipet",39,"Female",9952380056),
("Kamalraj", "Kalpakkam",38,"Male",9999999999),
("Suja","Tiruvallur",28,"Female",6666666666)]
dict={"Name":["OlgaRajee","Kamalraj","Suja"],
"Place":["Ranipet","Kalpakkam","Tiruvallur"],
"Age":[39,38,28],
"Mobile":[9952380056,9999999999,6666666666]}
list_of_tuples=pd.DataFrame(list)
dictionary=pd.DataFrame(dict)
print("LIST OF TUPLE VALUES USING DATAFRAME")
print(list_of_tuples)
print("DICTIONARY VALUES USING DATAFRAME")
print(dictionary)
OUTPUT:
LIST OF TUPLE VALUES USING DATAFRAME
0 1 2 3 4
0 OlgaRajee Ranipet 39 Female 9952380056
1 Kamalraj Kalpakkam 38 Male 9999999999
2 Suja Tiruvallur 28 Female 6666666666
DICTIONARY VALUES USING DATAFRAME
Name Place Age Mobile
0 OlgaRajee Ranipet 39 9952380056
1 Kamalraj Kalpakkam 38 9999999999
2 Suja Tiruvallur 28 6666666666

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 B) NUMPY
DATE: i) CHECKING NON-ZERO VALUE

AIM:
To write a program to test whether none of the elements of a given array is
zero using NumPy.
ALGORITHM:
Step 1: Start the program.
Step 2: Import numpy from python standard library.
Step 3: Declare an array and print the original array.
Step 4: Test whether none of the elements of the array is zero or not.
Step 5: If it contains zero print False otherwise print True.
Step 6: Stop the program.

PROGRAM:

import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))

OUTPUT:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero: True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero: False

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 B) NUMPY
DATE: ii) MATRIX ADDITION AND MULTIPLICATION

AIM:
To implement a python program with matrix addition modules using NumPy.

ALGORITHM:
Step 1: Start the Program.
Step 2: Import the module “numpy”
Step 3: Declare the matrices and assign elements for a & b as numpy arrays.
Step 4: Add the two matrices using numpy function “numpy.add()”
Step 5: Multiply the two matrices using numpy function “numpy.multiply()”
Step 7: Print the Resultant Matrices.
Step 8: Stop the Program.

PROGRAM:
import numpy
a=numpy.array([[10,20,30],[40,50,60]])
b=numpy.array([[10,20,30],[40,50,60]])
print("A Matrix \n", a)
print("B Matrix \n", b)
print("Resultant Matrix - Addition")
c=numpy.add(a,b)
print(c)
print("Resultant Matrix - Multiplication")
d=numpy.multiply(a,b)
print(d)

OUTPUT:
A Matrix
[[10 20 30]
[40 50 60]]
B Matrix
[[10 20 30]
[40 50 60]]
Resultant Matrix - Addition
[[ 20 40 60]
[ 80 100 120]]
Resultant Matrix - Multiplication
[[ 100 400 900]
[1600 2500 3600]]

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 C) MATPLOTLIB
DATE: i) PLOTTING GRAPH

AIM:
To implement a python program using matplotlib package.
ALGORITHM:
Step 1: Start the Program.
Step 2: Import matplotlib.pyplot by renaming as p.
Step 3: Declare the x and y axis with scales and values.
Step 4: Label the X and Y axis.
Step 5: Print the graph as “My First Graph” and display the graph.
Step 6: Stop the Program.
PROGRAM:
import matplotlib.pyplot as p
x=[1,2,3,4,5,6,7,8]
y=[1,2,1,3,1,4,1,6]
p.plot(x,y)
p.xlabel("X AXIS")
p.ylabel("Y AXIS")
p.title("My First Graph")
p.show()
OUTPUT:

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 C) MATPLOTLIB
DATE: ii) PLOTTING BAR GRAPH
AIM:
To implement a python program using Matplotlib package.
Matplotlib is an amazing visualization library in Python for 2D plots of arrays.
ALGORITHM:
Step1: Start the Program.
Step2: Install and Import NumPy and Matplotlib package.
Step3: x axis and y axis values are stored in array.
Step4: Using bar function draw bar graphs.
Step5: Print the bar graph.
Step6: Stop the program.
PROGRAM:
import matplotlib.pyplot as plt
import numpy as np
x=np.array([“A”, “B”, “C”, “D”])
y=np.array([3,8,1,10])
plt.bar(x,y,color= “red”)
plt.show()
OUTPUT:

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 D) SCIPY
DATE: i) HOUR, MINUTE & SECONDS CONVERSION

AIM:
To write a python program to return the specified unit in seconds (eg. Hour
returns 3600.0) using scipy library.

ALGORITHM:
Step 1: Start the program.
Step 2: Import scipy from python standard library.
Step 3: Print specified units like minute, hour, day, etc in seconds.
Step 4: Stop the program.

PROGRAM:
from scipy import constants
print('1 minute=',constants.minute,'seconds')
print('1 hour=',constants.hour,'seconds')
print('1 day=',constants.day,'seconds')
print('1 week=',constants.week,'seconds')
print('1 year=',constants.year,'seconds')
print('1 Julian year=',constants.Julian_year,'seconds')

OUTPUT:
('1 minute=', 60.0, 'seconds')
('1 hour=', 3600.0, 'seconds')
('1 day=', 86400.0, 'seconds')
('1 week=', 604800.0, 'seconds')
('1 year=', 31536000.0, 'seconds')
('1 Julian year=', 31557600.0, 'seconds')

RESULT:
Thus, the above program was executed successfully and the output was
verified.
EX NO:8 D) SCIPY
DATE: ii) NUMERICAL INTEGRATION

AIM:
To implement a python program to execute Numerical Integration using the
module “Scipy” and Standard libraries.

SciPy provides functionality to integrate function with numerical integration.


scipy.integrate library has single integration, double, triple, multiple, Gaussian
quadrate, Romberg, Trapezoidal and Simpson’s rules.
Here a is the upper limit and b is the lower limit.

ALGORITHM:
Step 1: Start the Program.
Step 2: Import “integrate” from Scipy.
Step 3: Call a “lambda” function to calculate f=x**2.
Step 4: Find integration by Calling Scipy function integrate.quad(f,a=0,b=1).
Step 5: Print the output.
Step 6: Stop the Program.

PROGRAM:
from scipy import integrate
f=lambda x: x**2
integration = integrate.quad(f,0,1)
print(integration)

OUTPUT:

(0.333333333333333337, 3.700743415417189e-15)

RESULT:
Thus, the above program was executed successfully and the output
was verified.
EX NO: 9 FILE HANDLING
DATE: a) COPYING, WORD COUNT & LONGEST WORD
AIM:

To write a python program to perform various operations on File.


ALGORITHM:
Step1: Start the program
Step2: Create a file, and save as text1.txt in notepad.
Step3: Open the file text1.txt in read mode.
Step3: Open a new file text2.txt in write mode.
Step4: Read the contents from text1.txt file using read function.
Step5: Write the contents to text2.txt using write function.
Step6: Display the word count (text1.txt)
Step7: And display the longest word in the file (text1.txt)
Step8: Stop the program.

PROGRAM:
f1=open("text1.txt","r")
f2=open("text2.txt","w")
str=f1.read() f2.write(str)
print("content of file(text1.txt) is copied to file(text2.txt)")
f1.close()
f2.close()
print("\nThe contents of file(text2.txt) is:")
c=open("text2.txt","r")
print(c.read())
c.close()
f3=open("text1.txt","r")
words=f3.read().split()
print("The word count in the file(text1.txt) is:",len(words))
max_len=len(max(words,key=len))
for word in words:
if len(word)==max_len:
print("The longest word in the file(text1.txt) is:",word)
f3.close()

OUTPUT:
content of file(text1.txt) is copied to file(text2.txt)

The contents of file(text2.txt) is:


Hello
This is python programming lab.

The word count in the file(text1.txt) is: 6


The longest word in the file(text1.txt) is: programming

RESULT:
Thus, the above program was executed successfully and the output was verified.
EX. NO: 9 FILE HANDLING
DATE: b) COMMAND LINE ARGUMENTS (WORD COUNT)
AIM:
To write a Python program to count the words in a file given in command line arguments.
ALGORITHM:
Step 1: Start the program.
Step 2: Open the file given in the command line arguments in read mode.
Step 3: Read the contents of the file.
Step 4: Count the number of words in the file.
Step 5: Display the number of words.
Step 6: Stop the program.
PROGRAM:
import sys
def countWords(sentence):
wordCount = 0
data = sentence.split('\\n')
for line in data:
line = line.lower().split(' ')
line = [word.strip(',.;!?') for word in line]
wordCount += len(line)
return wordCount
def main():
if len(sys.argv) == 2:
f = open(sys.argv[1],'r')
sentence = f.read()
count = countWords(sentence)
print("Number of words in the given sentence:",count)
else:
print("Unexpected number of command line arguments!")
f.close()
if name ==' main ': main()

inp.txt
I LOVE PYTHON PROGRAMMING TO THE CORE

OUTPUT:
C:\Users\olgar\AppData\Local\Programs\Python\Python311\Scripts>py cmdlnargs.py inp.txt
Number of words in the given sentence: 7

RESULT:
Thus, the above program was executed successfully and the output was verified.
EX. NO: 9 FILE HANDLING
DATE: c) FINDING MOST FREQUENT WORDS
AIM:
To write a Python program to find the frequency of words in a text file.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the filename.
Step 3: Open the file in read mode.
Step 4: Read each line from the file and perform following operations on it.
Step 4.1: Change it to lowercase.
Step 4.2: Remove the punctuations.
Step 4.3: Split each line into words and count them.
Step 5: Print the words and it count.
Step 6: Stop the program.
PROGRAM:
def main():
filename=input("enter the file: ").strip()
infile=open(filename,"r")
wordcounts={}
for line in infile:
processLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())
items=[[x,y] for (y,x) in pairs] items.sort()
for i in range(0, len(items), 1):
print(items[i][1]+"\t"+str(items[i][0]))
def processLine(line,wordcounts):
line=replacePunctuations(line)
words=line.split()
for word in words:
if word in wordcounts:
wordcounts[word]+=1
else:
wordcounts[word]=1
def replacePunctuations(line):
for ch in line:
if ch in "~@#$%^&*()_-+=<>?/.,:;!{}[]''":
line=line.replace(ch," ")
return line
main()
data.txt
A file is a collection of data stored on a secondary storage device like hard disk. They can be
easily retrieved when required.
Python supports two types of files:
They are Text files & Binary files.

OUTPUT:
enter the file:data.txt
are 1
be 1
binary 1
can 1
collection 1
data 1
device 1
disk 1
easily 1
file 1
hard 1
is 1
like 1
on 1
python 1
required 1
retrieved 1
secondary 1
storage 1
stored 1
supports 1
text 1
two 1
types 1
when 1
of 2
they 2
a 3
files 3

RESULT:
Thus, the above program was executed successfully and the output was verified.
EX NO: 10 EXCEPTION HANDLING
DATE: A) DIVIDE BY ZERO ERROR USING EXCEPTION HANDLING

AIM:
To write a python program to handle divide by zero error using exception
handling.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value for price and weight.
Step 3: Calculate result as price / weight in try block.
Step 4: If ZeroDivisionError arise print Division by Zero.
Step 5: otherwise,

Check for other Errors and display them.


Step 6: Display the price per unit weight in case of no errors.
Step 7: Stop the program.
PROGRAM:
import sys
def main():
price = input('Enter the price of item purchased:')
weight = input('Enter the weight of item purchased:')
try:
if price == '': price = None
try:
price = float(price)
except ValueError:
print('Invalid Inputs: ValueError')
if weight == '': weight = None
try:
weight = float(weight)
except ValueError:
print('Invalid Inputs: ValueError')
assert price >= 0 and weight >= 0
result = price / weight
except TypeError:
print('Invalid Inputs: TypeError')
except ZeroDivisionError:
print('Invalid Inputs: ZeroDivisionError')
except:
print(str(sys.exc_info()))
else:
print('Price per unit weight:',result)
if name == ' main ':
main()
OUTPUT 1:
Enter the price of item purchased:20
Enter the weight of item purchased:x
Invalid Inputs: ValueError

Invalid Inputs: TypeError


OUTPUT 2:
Enter the price of item purchased:-20
Enter the weight of item purchased:10
(<class 'AssertionError'>, AssertionError(), <traceback object at
0x0000026F1294BBC0>)
OUTPUT 3:
Enter the price of item purchased:20
Enter the weight of item purchased:0
Invalid Inputs: ZeroDivisionError

OUTPUT 4:
Enter the price of item purchased:20
Enter the weight of item purchased:
Invalid Inputs: TypeError
OUTPUT 5:
Enter the price of item purchased:-20
Enter the weight of item purchased:0
(<class 'AssertionError'>, AssertionError(), <traceback object at
0x0000028FAFAB3B80>)
OUTPUT 6:
Enter the price of item purchased:20
Enter the weight of item purchased:2
Price per unit weight: 10.0

Result:
Thus, the above program was executed successfully and the output was
verified.
EX NO: 10 EXCEPTION HANDLING
DATE: b) VOTER’S AGE VALIDITY

AIM:
To write a python program to check Voter’s age validity.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the year of birth from user.
Step 3: Calculate age by subtracting year of birth from current year.
Step 4: Check whether the age is less than 0 inside try block.
Step 4.1: Then raise Invalid year of birth error.
Step 5: Handle the error in except block.
Step 6: If Age is less than or equal to 18,
print “You are eligible to vote”.
Step 7: Otherwise,
print “You are not eligible to vote”
Step 8: Stop the program.

PROGRAM:
import datetime
Year_of_birth = int(input("Enter your year of birth:- "))
Current_year = datetime.datetime.now().year
Current_age = Current_year-Year_of_birth
try:
if Current_age < 0:
raise ValueError('Invalid Year of Birth')
except:
print('Invalid Year of Birth:Value Error')
Year_of_birth = int(input("Enter your correct year of birth:- "))
Current_age = Current_year-Year_of_birth
print("Your current age is ",Current_age)
if(Current_age<=18):
print("You are not eligible to vote")
else:
print("You are eligible to vote")
OUTPUT 1:
Enter your year of birth:- 1984
Your current age is 39
You are eligible to vote
OUTPUT 2:
Enter your year of birth:- 2026
Invalid Year of Birth:Value Error
Enter your correct year of birth:- 1981
Your current age is 42
You are eligible to vote

Result:
Thus, the above program was executed successfully and the output was
verified.
EX NO: 10 EXCEPTION HANDLING
DATE: c) STUDENT MARK RANGE VALIDATION
AIM:
To write a python program to perform student mark range validation
ALGORITHM:

Step 1: Start the program.


Step 2: Read student mark from user.
Step 3: If the mark is in between 0 and 100,
print “The mark is in the range”

Step 4: Otherwise,
print “The value is out of range”

Step 5: Stop the program.

PROGRAM:
def getMark(subject):
print("Subject:",subject)
mark = int(input('Enter the mark:'))
try:
if mark < 0 or mark > 100:
raise ValueError('Marks out of range')
else:
return mark
except ValueError:
print('Invalid Input: ValuError')
mark = int(input('Enter valid mark(0 - 100):'))
return mark
finally:
print('Processing Wait......... ')
def main():
a = getMark(subject = 'English')
b = getMark(subject = 'Math')
c = getMark(subject = 'Physics')
d = getMark(subject = 'Chemistry')
e = getMark(subject = 'Python')
avg = ((a+b+c+d+e)/500)*100
if avg >= 80:
print('Congrats! You have secured First Class & ur percentage is',avg)
elif avg >= 60 and avg < 80:
print('Congrats! You have secured Second Class & ur percentage is',avg)
elif avg >= 50 and avg < 60:
print('Congrats! You have secured Third Class & ur percentage is',avg)
else:
print('Sorry! You are Fail. Try again......... ')
print('End of Program')
main()
OUTPUT:
Subject: English
Enter the mark:102
Invalid Input: ValuError
Enter valid mark(0 - 100):96
Processing Wait......
Subject: Math
Enter the mark:65
Processing Wait......
Subject: Physics
Enter the mark:98
Processing Wait......
Subject: Chemistry
Enter the mark:95
Processing Wait......
Subject: Python
Enter the mark:96
Processing Wait......
Congrats! You have secured First Class & ur percentage is 90.0
End of Program

Result:
Thus, the above program was executed successfully and the output was
verified.
Ex.No.11 EXPLORING PYGAME
Date:
AIM:
To install Pygame Module.
PROCEDURE:
1: Install python 3.6.2 into C:\
2: Go to this link to install pygame www.pygame.org/download.shtml

3: Click
pygame-1.9.6.tar.gz ~ 3.1M and download zar file
4: Extract the zar file into C\Python36-32\Scripts folder
5: Open command prompt
6: Type the following command in command prompt
C:> py -m pip install pygame –user
(Or)
To install module without downloading from website execute the following
command in command prompt
C:> Pip install Pygame
7: Now, pygame installed successfully
8: To see if it works, run one of the include examples in pygame-2.6.0 or check the
version of the module by executing following command in command prompt.

RESULT:
Thus, the above program was successfully executed and verified
Ex.No.12 SIMULATE BOUNCING BALL USING PYGAME
Date:

AIM:
To write a python program to bouncing ball in Pygame.
ALGORITHM:
Step 1: Start the program.
Step 2: Initialize Pygame.Step3: Print the elements of list.
Step 3: Define ball properties and window size.
Step 4: Move the ball and check for bounce.
Step 5: Update the display.
Step 6: Stop the program.
PROGRAM:
import pygame
pygame.init()
window_w = 800
window_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 120
window = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w / 2
pos_y = window_h / 2
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + block_size > window_w or pos_x < 0:
velocity[0] = -velocity[0]
if pos_y + block_size > window_h or pos_y < 0:
velocity[1] = -velocity[1]
window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size, block_size])
pygame.display.update()
clock.tick(FPS)

game_loop()
OUTPUT:

RESULT:
Thus, the above program was successfully executed and verified

You might also like