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

python lab record AIDS (1)

The document outlines the structure and objectives of the Problem Solving & Python Programming Laboratory for the Department of Artificial Intelligence and Data Science at Vel Tech Multi Tech Engineering College. It includes details on the institution's accreditation, course objectives, experiments, and expected outcomes for students. The laboratory aims to equip students with practical programming skills and problem-solving techniques using Python.

Uploaded by

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

python lab record AIDS (1)

The document outlines the structure and objectives of the Problem Solving & Python Programming Laboratory for the Department of Artificial Intelligence and Data Science at Vel Tech Multi Tech Engineering College. It includes details on the institution's accreditation, course objectives, experiments, and expected outcomes for students. The laboratory aims to equip students with practical programming skills and problem-solving techniques using Python.

Uploaded by

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

Approved by AICTE, Affiliated to Anna University, Chennai.

ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with ‘A’ Grade (3.49 / 4 scale)
#42, Avadi - Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

231CS21A / PROBLEM SOLVING & PYTHON PROGRAMMING LABORATORY

Name :

Register No :

Roll No :

Branch :

Year :

Semester :

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

Vision
 To promote centre of excellence through effectual Teaching and Learning, imparting the contemporary knowledge
centric education through innovative research in multidisciplinary fields.
Mission
 To impart quality technical skills through practicing, knowledge updating in recent technology and produce
professionals with multidisciplinary and leadership skills.
 To promote innovative thinking for design and development of software products of varying complexity with
intelligence to fulfil the global standards and demands.
 To inculcate professional ethics among the graduates and to adapt the changing technologies through lifelong
learning.
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE,
EEE, IT & MECH),Accredited by NAAC with 'A' Grade with CGPA of 3.49.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India

CERTIFICATE
Name …………………….……………… Year: ……………… Semester: ………
Branch: B.TECH – ARTIFICIAL INTELLIGENCE AND DATA SCIENCE University Register
No .......................... College Roll No: Certified that this is the bonafide record of
work done by the above student in the 231CS21A-PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY during the academic year 2024-2025.

Signature of Course In charge Signature of Head of the Department

Submitted for the End Semester Practical Examination held on ....................at VEL TECH MULTI TECH
Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, No.42, AVADI – VEL TECH
ROAD, AVADI, CHENNAI- 600062.

Signature of Examiners

Internal Examiner:…………… External Examiner:………………

Date:………………
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEOs PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

Train the graduates with the potential of strong knowledge in the respective
PEO1 field and to create innovative multidisciplinary solutions for challenges in
the society

Groom the engineers to understand, analyse different nature of data and use
PEO2 Machine Learning techniques to develop software systems with varying
complexity for data intensive applications

To practice professionalism among the graduates and reflect good


PEO3 leadership skills with ethical standards and continued professional
development through lifelong learning.

PROGRAMME SPECIFIC OUTCOMES (PSOs)

PSO’s PROGRAMME SPECIFIC OUTCOMES (PSOs)

To impart theoretical knowledge in the respective field along with recent


PSO1 industrial tools and techniques to solve societal problems

Apply the core competency obtained in the field of Machine Learning for
PSO2
analysis, design and development of computing systems for multi-
disciplinary problems

Acquire knowledge in the field of intelligence, deep learning and develop


PSO3
software solutions for security and analytics of large volume of data.
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

POs Programme Outcomes (POs)

Engineering Knowledge: Apply knowledge of mathematics, natural science,


computing, engineering fundamentals and an engineering specialization as specified
PO1
in WK1 to WK4 respectively to develop to the solution of complex engineering
problems.
Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions with consideration for sustainable
PO2 development. (WK1 to WK4)
Design/Development of Solutions: Design creative solutions for complex engineering
problems and design/develop systems/components/processes to meet identified needs with
PO3 consideration for the public health and safety, whole-life cost, net zero carbon, culture,
society and environment as required. (WK5)
Conduct Investigations of Complex Problems: Conduct investigations of complex
PO4 engineering problems using research-based knowledge including design of experiments,
modelling, analysis & interpretation of data to provide valid conclusions. (WK8).
Engineering Tool Usage: Create, select and apply appropriate techniques, resources and
PO5 modern engineering & IT tools, including prediction and modelling recognizing their
limitations to solve complex engineering problems. (WK2 and WK6)
The Engineer and The World: Analyze and evaluate societal and environmental aspects
while solving complex engineering problems for its impact on sustainability with reference
PO6
to economy, health, safety, legal framework, culture and environment. (WK1, WK5, and
WK7).
Ethics: Apply ethical principles and commit to professional ethics, human values,
PO7 diversity and inclusion; adhere to national & international laws. (WK9)
Individual and Collaborative Team work: Function effectively as an individual, and as a
PO8 member or leader in diverse/multi-disciplinary teams.

Communication: Communicate effectively and inclusively within the engineering


PO9 community and society at large, such as being able to comprehend and write effective reports
and design documentation, make effective presentations considering cultural, language, and
learning differences
Project Management and Finance: Apply knowledge and understanding of engineering
management principles and economic decision-making and apply these to one’s own work,
PO1 0
as a member and leader in a team, and to manage projects and in multidisciplinary
environments.
Life-Long Learning: Recognize the need for, and have the preparation and ability for
PO1 1 i) Independent and life-long learning ii) Adaptability to
new and emerging technologies and
iii) Critical thinking in the broadest context of technological change. (WK8)
COURSE OBJECTIVES

The student should be made to:

 Investigate the problem solving approaches.

 Learn and execute the basic programming constructs in Python.

 Practice various computing strategies for Python-based solutions to real world problems.

 Apply Python data structures - lists, tuples, and dictionaries.

 Exercise the input/output with files in Python.


LIST OF EXPERIMENTS

PAGE SIGNATURE
S.NO. DATE NAME OF THE PROGRAM
NO.
1 Identification and solving of simple real life or scientific or technical problems, and
developing
1a Electricity Billing
1b Retail shop billing
1c Sin series
1d Weight of a motorbike
1e Weight of a steel bar
1f Compute Electrical Current in Three Phase AC Circuit
2 Python programming using simple statements and expressions
2a Exchange the values of two variables
2b Circulate the values of n variables
2c Distance between two points
3 Scientific problems using Conditionals and Iterative loops.
3a Number series
3b Number Patterns
3c Pyramid pattern of star
3d Pyramid pattern of number
4 Implementing real-time/technical applications using Lists, Tuples
4a(i) Components of a car using List
4a(ii) Components of a car using Tuple
4b(i) Materials required for construction of a building using
List
4b(ii) Materials required for construction of a building using
Tuple
4c(i) Items present in a library using List
4c(ii) Items present in a library using Tuple
5 Implementing real-time/technical applications using Sets, Dictionaries.
5a(i) Application Language using sets
5a(ii) Application Language using Dictionaries
5b(i) Components of an automobile using sets
5b(ii) Components of an automobile using Dictionaries
5c(i) Elements of a civil structure using Sets
5c(ii) Elements of a civil structure using Dictionaries
6 Implementing programs using Functions.
6a Factorial of given number
6b Implementing two Largest number in a list
6c Area of shape
7 Implementing programs using Strings
7a Reverse string program
7b Implementing Palindrome program
7c Implementing character count program
7d Implementing Replacing characters program
8 Implementing programs using written modules and Python Standard Libraries
8a Implementing Pandas program
8b Implementing Numpy program
8c Implementing Matplotlib program
8d Implementing Scipy program
9 Implementing real-time/technical applications using File handling
9a Implementing copy from one file to another
9b Implementing word count program
9c Implementing longest word program
10 Implementing real-time/technical applications using Exception handling
10a Implementing divide by zero error program
10b Implementing voter’s age validity program
10c Implementing student mark range validation program
11 Exploring Pygame tool
12 Developing a game activity using Pygame like
bouncing ball, car race etc
13 Mini project

SUPPORTING MARKS (75)


Attendance
Pre-Lab Practical Skills and Lab
and Post-Lab Quiz TOTAL
Preparation Experimentation Record(s)
Punctuality

10 15 25 15 10 75
COURSE OUTCOMES

At the end of the course, the student should be able to

Course
Outcome CO Statements
Develop algorithmic solutions for simple real life scientific
CO1
computational problems
CO2 Develop and execute simple Python programs using simple
statement and expression.
CO3 Implement programs in Python using conditionals, loops, lists
and tuples for solving problems.

Mapping CO's with PO's & PSO’S


Course

PSO3
PSO1

PSO2
PO10

PO11
PO 1

PO 2

PO 3

PO 4

PO 5

PO 6

PO 7

PO 8

Outcome PO 9

CO1 3 2 2 - 2 - - - - - 1 3 - -
CO2 3 2 2 - 2 - - - - - 1 3 2 -
CO3 3 2 2 - 2 - - - - - 1 3 2 1
CO 3 2 2 - 2 - - - - - 1 3 2 1

1 – Low 2 – Medium 3 – High


EX. NO:1a Identification and solving of simple real life or scientific or technical
DATE: problems and developing flow charts for the Electricity Billing.

AIM:

To develop a flowchart for electricity billing.

ALGORITHM:

Step1: Start.
Step2: Read the previous unit and current unit.
Step 3: Calculate the used units by subtracting the current unit and previous unit.
Step4: Calculate the Electricity bill from the used units.
Step 5: Print the amount of electricity bill.
Step6: Stop.

PSEUDOCODE:

READ Previous unit,Current Unit


CALCULATE Used Unit = Current Unit – Previous Unit
ElectricityBill=Used Unit x 2
PRINT ElectricityBill

1
FLOWCHART:

INFERENCE:

RESULT:
Thus, the flowchart for the electricity billing is developed.

2
EX. NO:1b. Identification and solving of simple real life or scientific or technical
DATE: problems and developing flow charts for the Retail Shop Billing

AIM:

To develop a flowchart for the retail shop billing.

ALGORITHM:
Step1: Start.
Step2: Read the barcode of the product.
Step3: Display the product name and the amount.
Step 4: Check if more products is available, if available go to Step 2, otherwise go to Step 5.
Step5: Calculate the total cost of the products.
Step6: Print total cost.
Step7: Stop.

PSEUDOCODE:

IF more products available THEN


READ bar code
DISPLAY Product name, amount
ELSE
CALCULATE Total Cost
PRINT Total Cost
ENDIF

3
FLOWCHART:

INFERENCE:

RESULT:
Thus, the flowchart for retail shop billing is developed.

4
EX. NO:1c. Identification and solving of simple real life or scientific or technical
DATE: problems and developing flow charts for the Sin Series

AIM:

To develop a flowchart for the Sine Series.

ALGORITHM:

Step1: Start
Step2: Read x and n.
Step3: Print x and n.
Step 4: Convert x values into radian using formula x = x * 3.1412/180.
Step5: Substitute t=x and sum=x.
Step 6: Set the for loop for doing the calculation as initialize i to 1 and check i is less
thann+1and increment i by 1.
Step 7: Calculate t=(t*pow(-1),(2*i-1))*x*x)/(2*i*(2*i+1).
Step8: Calculate sum = sum + t.
Step9: Print sum.
Step10: Stop

PSEUDOCODE:

READ x, n
PRINT x, n
CONVERT x =x * 3.1412/180
SUBSTITUTE t=x, sum=x
FORi=1; i<n+1;i++
t= (t*pow (-1), (2*i-1))*x*x)/(2*i*(2*i+1).
sum = sum + t
END FOR
PRINT sum

5
FLOWCHART:

INFERENCE:

RESULT:
Thus, the flowchart for the sine series is developed.
6
EX. NO:1d Identification and solving of simple real life or scientific or technical
DATE: problems and developing flow charts for the Weight of a Motorbike.

AIM:

To develop a flowchart for finding the weight of a motor bike.

ALGORITHM:

Step1: Start.
Step2: Read the size of the motor bile in cc.
Step3:Check whether the size of the motor bike is less than or equal to 300 cc, if so, Print
Average weight is 350 pounds otherwise go to step 4.
Step4: Check whether the size of the motor bike is less than or equal to 500 cc, if so, Print
Average weight is 410 pounds otherwise go to step 5.
Step5: Check whether the size of the motor bike is less than or equal to 900cc, if so, Print
Average weight is 430 pounds otherwise go to step 6.
Step6:Check whether the size of the motor bike is equal to 1100 cc, if so, Print Average weight is
500 pounds otherwise go to step 7.
Step 7: Print Average weight is 600 pounds.
Step 8: Stop.

PSEUDOCODE:

READ size in cc
IF size<=300 THEN
PRINT Average weight = 350 pounds
ELSEIF size <=500 THEN
PRINT Average weight = 410 pounds
ELSEIF size <=900 THEN
PRINT Average weight = 430 pounds
ELSEIF size =1100 THEN
PRINT Average weight=500pounds
ELSE
PRINT Average weight=600pounds
ENDIF

7
FLOWCHART:

INFERENCE:

RESULT:

Thus, the flowchart for finding the weight of the motor bike is developed.

8
EX. NO:1e Identification and solving of simple real life or scientific or technical
DATE: problems and developing flow charts for the Weight of a steel bar.

AIM:

To develop a flowchart for finding weight of a steel bar.

ALGORITHM:

Step1:Start.
Step2:Read the diameter in mm and length of the steel bar.
Step3:Check whether the length is in meter if so, calculate weight as diameter x diameter x
length and divide it by 162, otherwise go to step4.
Step 4: calculate weight as diameter x diameter x length and divide it by 533.
Step5: Print the weight.
Step6: Stop.

PSEUDOCODE:

READ diameter, length


IF length in meter, THEN
Weight=diameter*diameter*length/162
ELSE
Weight=diameter*diameter*length/533
ENDIF

PRINT Weight

9
FLOWCHART:

INFERENCE:

RESULT:

Thus, the flowchart for finding the weight of a steel bar is developed.
10
EX. NO:1f Identification and solving of simple real life or scientific or technical
problems and developing flow charts for the Compute Electrical Current
DATE: in Three Phase AC Circuit.

AIM:

To develop a flowchart to compute electrical current in three phase AC circuit.

ALGORITHM:

Step1: Start.
Step2: Get the value of voltage, resistance, current and power factor.
Step3: Compute the electric current by multiplying voltage, resistance, current and power factor
with 3.
Step 4: Print the calculated electric current.
Step5: Stop.

PSEUDOCODE:

READ voltage, resistance, current and power factor


COMPUTE Electric Current = 3 x voltage x resistance x current x power factor
PRINT Electric Current

11
FLOWCHART:

INFERENCE:

RESULT:

Thus, the flowchart for computing the electric current in three phase AC circuit is
developed.
12
EX. NO:2a Python programming exchange the values of two variables using simple
DATE: statements and expressions.

AIM:

To write a Python Program to exchange the value of two variables.

ALGORITHM:

STEP 1: Start the program


STEP2: Enter two variables and assign value for it(x, y)
STEP3: simply exchange the variables(y, x) and assign it to variables(x, y)
STEP 4: print ‘x’ value
STEP5: print ‘y’ value
STEP6: End the program

PROGRAM:

x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)

OUTPUT:

x = 10
y=5

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

13
EX. NO:2b Python programming circulate the values of n variables using simple
DATE: statements and expressions.

AIM:
To write a Python Program to circulate the values of n variables.

ALGORITHM:
STEP1: Start the program
STEP2: Read the total number of values
STEP3: Enter the values
STEP4: Append the value in the list1
STEP5: Print the list1 of elements
STEP6: check the range of values and pop the first element from the list1 and append it at the
last in thelist1
STEP7: Continue until range (0 to 3) exit.
STEP8: End the program.

PROGRAM:
no_of_terms = int(input("Enter number of values:"))
list1 = []
for val in range(0,no_of_terms,1):
ele=int(input("Enter integer:"))
list1.append(ele)
print("Circulating the elements of list",list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)

OUTPUT:
Enter number of values : 4
Enter integer : 5
Enter integer : 3
Enter integer : 6
Enter integer : 1
Circulating the elements of list [5, 3, 6, 1]
[3, 6, 1, 5]
[6, 1, 5, 3]
[1, 5, 3, 6]
[5, 3, 6, 1]

INFERENCE:

RESULT:
Thus the Python Program to circulate the values of n variables was written and executed
successfully.
14
EX. NO:2c Python programming distance between two points using simple
DATE: statements and expressions.

AIM:

To write a Python Program to find the distance between two points

ALGORITHM:

STEP1: Start the program


STEP2: Import math library
STEP 3: Take a two points as an input from an user.
STEP 4: Calculate the difference between the corresponding X-coordinates i.e.:X2 - X1 and Y-
coordinates i.e.:Y2 - Y1 of two points.
STEP 5: Apply the formula derived from Pythagorean Theorem
i.e.: sqrt ((X2 - X1) ^2 + (Y2 - Y1) ^2)
STEP 6 : End the program

PROGRAM:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

OUTPUT:
6.324555320336759

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
15
EX. NO:3a
Scientific problems Number series using Conditionals and Iterative loops.
DATE:

AIM

To write python program to print number series

ALGORITHM

STEP1: Start the program

STEP2: Initialize the values of a and b

STEP3: Read the number of terms in the sequence; n

STEP4: Print value of a, b

STEP5: add the values of a, b and store in c

STEP6: Print the values of a, b and assign value of b, c into a, b

STEP7: Repeat the step5 & 6 for n-2 times.

PROGRAM:

a=0
b=1
n=int(input("Enter the number of terms in the sequence: "))
print(a,b,end=" ")
while(n-2):
c=a+b
a,b = b,c
print(c,end=" ")
n=n-1

OUTPUT:
Enter the number of terms in the sequence: 8
0 1 1 2 3 5 8 13

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
16
EX. NO:3b Scientific problems number patterns using Conditionals and Iterative
DATE: loops.

AIM:

To write python program to print number pattern.

ALGORITHM:

STEP1: Start

STEP2: Range (10) –Range function takes values from 0 to 9

STEP3: str (i) prints string version of i .(i.e i value)

STEP4: Using for loop print str (i) values i times in every iteration

PROGRAM:

for i in range(10):
print(str(i) * i)

OUTPUT:
1
22
333
4444
55555
666666
7777777
88888888
999999999

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
17
EX. NO:3c Scientific problems pyramid pattern of a star using Conditionals and
DATE: Iterative loops.

AIM:

To write a python program to print Pyramid pattern of a star.

ALGORITHM:

STEP1: First, we get the height of the pyramid rows from the user.
STEP2: In the first loop, we iterate from i = 0 to i = rows.
STEP3: The second loop runs from j = 0 to i + 1.
STEP4: In each iteration of this loop, we print i + 1 number of * without a new line.
STEP5: Here, the row number gives the number of * required to be printed on that row.
STEP6: Once the inner loop ends, we print new line and start printing * in a new line.

PROGRAM:
def triangle(n):
k=n-1
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")
n=5
triangle(n)

OUTPUT:
*
**
***
****
*****

INFERENCE:

RESULT:
Thus the python program to print Pyramid pattern of a star was written and executed
successfully.
18
EX. NO:3d Scientific problems pyramid pattern of a number using Conditionals and
DATE: Iterative loops.

AIM:

To write a python program to print Pyramid pattern of a number.

ALGORITHM:

STEP1: First, we get the height of the pyramid rows from the user.
STEP2: In the first loop, we iterate from i = 0 to i = rows.
STEP3: In the second loop, we print numbers starting from 1 to j, where j ranges from 0 to i.
STEP4: After each iteration of the first loop, we print a new line.

PROGRAM:
rows = int(input("Enter number of rows:"))
k=0
count=0
count1=0
for i in range(1,rows+1):
for space in range(1, (rows-i)+1):
print(" ",end=" ")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k,end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1),end=" ")
k+= 1
count1=count=k=0
print()

OUTPUT:
1
232
34543

INFERENCE:

RESULT:
Thus the python program to print Pyramid pattern of a number was written and executed
successfully.

19
EX. NO:4.a.(i) Implementing real-time/technical applications Components of a car using
DATE: Lists.

AIM:
To write a python program to implement components of a car using List

ALGORITHM:
Step1:Start the program
Step2:Assign list of car parts
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

Program:
carparts =['Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery']
print(carparts)
print(carparts[0])
print(carparts[1])
print(carparts.index('Wheel'))
print(len(carparts))
carparts.append('Headlights')
print(carparts)
carparts.insert(2,'Radiator')
print(carparts)
carparts.remove('Headlights')
print(carparts)
carparts.pop(2)
print(carparts)
carparts[2]='Tyre'
print(carparts)
carparts.sort()
print("After sorting: ",carparts)
carparts.reverse()
print("Reversed list: ", carparts)
New = carparts[:]
print(New)
x = slice(2)
print(carparts[x])
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
for i in test_list2 :
test_list1.append(i)
print("Concatenated list using naive method : ", str(test_list1))

20
Output:
['Engine', 'Transmission', 'Wheel', 'Gear','Brake', 'Battery']

Engine
Transmission

2
6
['Engine', 'Transmission', 'Wheel', 'Gear','Brake', 'Battery', 'Headlights']
['Engine', 'Transmission','Radiator', 'Wheel', 'Gear','Brake', 'Battery', 'Headlights']
['Engine', 'Transmission', 'Radiator', 'Wheel','Gear', 'Brake', 'Battery']
['Engine', 'Transmission', 'Wheel', 'Gear','Brake', 'Battery']
['Engine', 'Transmission', 'Tyre','Gear', 'Brake', 'Battery']

After sorting:['Battery', 'Brake', 'Engine','Gear','Transmission','Tyre']

Reversed list:['Tyre','Transmission', 'Gear','Engine','Brake','Battery']

['Tyre', 'Transmission', 'Gear','Engine', 'Brake', 'Battery']

['Tyre', 'Transmission']

Concatenated list using naive method: [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]

INFERENCE:

RESULT:
Thus the program was executed successfully.

21
EX. NO:4.a.(ii) Implementing real-time/technical applications Components of a car using
DATE: Tuples.

AIM:

To write a python program to implement components of a car using Tuples

ALGORITHM:
Step1:Start the program
Step2:Assign list of car parts
Step3Perform all the Tuples operation
Step4:Print the result
Step5:End the program

Program:
carparts=('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery')
print('Our tuple is: ',carparts)
print('Item in the first position is: ',carparts[0])
print('Item in the 5th position is: ',carparts[4])
indexOfWheel=carparts.index('Wheel')
print('Index of Wheel is: ', indexOfWheel)
lengthcarpartsTuple = len(carparts)
print('Length of the carparts tuple is: ',lengthcarpartsTuple)
for item in carparts:
print(item)
print(carparts*2)
print(carparts[1:4])
if "Brake" in carparts:
print("Brake is available in the carparts tuple")
else:
print("Brake is not available in the carparts tuple")

22
Output:
Our tuple is:('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery')

Itemin the first position is: Engine

Itemin the 5th position is: Brake

Index of Wheel is: 2

Length of the carparts tuple is: 6

Engine
Transmission
Wheel
Gear
Brake
Battery

('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery', 'Engine', 'Transmission', 'Wheel', 'Gear',
'Brake', 'Battery')

('Transmission', 'Wheel', 'Gear')

Brake is available in the carparts tuple

INFERENCE:

RESULT
Thus the program was executed successfully.

23
EX. NO:4.b.(i) Implementing real-time/technical applications Components of a Building
DATE: constructions using Lists.

AIM:
To write a python program to implement components of a Building constructions using List

ALGORITHM:
Step1:Start the program
Step2:Assign list of building materials
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

PROGRAM
buildingconstructions=['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']
print(buildingconstructions)
print(buildingconstructions[0])
print(buildingconstructions[1])
print(buildingconstructions.index('sand'))
print(len(buildingconstructions))
buildingconstructions.append('wood')
print(buildingconstructions)
buildingconstructions.insert(2,'marbles')
print(buildingconstructions)
buildingconstructions.remove('wood')
print(buildingconstructions)
buildingconstructions.pop(2)
print(buildingconstructions)
buildingconstructions[2]='tiles'
print(buildingconstructions)
buildingconstructions.sort()
print("After sorting: ",buildingconstructions)
buildingconstructions.reverse()
print("Reversed list: ", buildingconstructions)
New = buildingconstructions[:]
print(New)
x = slice(2)
print(buildingconstructions[x])
test_list1 = ['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']
test_list2 = ['sand','wood','marbles','tiles']
for i in test_list2 :
test_list1.append(i)
print("Concatenated list using naive method : ", str(test_list1))

24
OUTPUT:

['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']


bricks
cement
2
6
['bricks', 'cement', 'sand', 'water', 'gravels', 'steel', 'wood']
['bricks', 'cement', 'marbles', 'sand', 'water', 'gravels', 'steel', 'wood']
['bricks', 'cement', 'marbles', 'sand', 'water', 'gravels', 'steel']
['bricks', 'cement', 'sand', 'water', 'gravels', 'steel']
['bricks', 'cement', 'tiles', 'water', 'gravels', 'steel']
After sorting: ['bricks', 'cement', 'gravels', 'steel', 'tiles', 'water']
Reversed list: ['water', 'tiles', 'steel', 'gravels', 'cement', 'bricks']
['water', 'tiles', 'steel', 'gravels', 'cement', 'bricks']
['water', 'tiles']
Concatenated list using naive method : ['bricks', 'cement', 'sand', 'water', 'gravels', 'steel', 'sand',
'wood', 'marbles', 'tiles']

INFERENCE:

RESULT:
Thus the program was executed successfully.

25
EX. NO:4.b.(ii) Implementing real-time/technical applications Components of a Building
DATE: constructions using Tuples.

AIM:
To write a python program to implement components of a Building constructions using Tuple

ALGORITHM:
Step1:Start the program
Step2:Assign list of building materials
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

PROGRAM

buildingconstruction=('bricks', 'cement', 'sand', 'water', 'gravels', 'steel')


print('Our tuple is:',buildingconstruction)
print('Item in the first position is: ',buildingconstruction[0])
print('Item in the 5th position is: ',buildingconstruction[4])
indexOfwater=buildingconstruction.index('water')
print('Index of water is: ', indexOfwater)
Tuplelength=len(buildingconstruction)
print('Length of the buildingconstruction tuple is: ',Tuplelength)
for item in buildingconstruction:
print(item)
print(buildingconstruction*2)
print(buildingconstruction[1:4])
if "brick" in buildingconstruction:
print("bricks is available in the buildingconstruction tuple")
else:
print("bricks is not available in the buildingconstruction tuple")

26
OUTPUT

Our tuple is: ('bricks', 'cement', 'sand', 'water', 'gravels', 'steel')


Item in the first position is: bricks
Item in the 5th position is: gravels
Index of water is: 3
Length of the buildingconstruction tuple is: 6
bricks
cement
sand
water
gravels
steel
('bricks', 'cement', 'sand', 'water', 'gravels', 'steel', 'bricks', 'cement', 'sand', 'water', 'gravels', 'steel')
('cement', 'sand', 'water')
bricks is not available in the buildingconstruction tuple

INFERENCE:

RESULT:
Thus the program was executed successfully.

27
EX. NO:4.c.(i) Implementing real-time/technical applications Components of a Library
DATE: using Lists.

AIM:
To write a python program to implement components of a Library using List

ALGORITHM:
Step1:Start the program
Step2:Assign list of library materials
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

PROGRAM
librarycomp=['books', 'newspaper', 'computer', 'magazine', 'journals']
print(librarycomp)
print(librarycomp[0])
print(librarycomp[1])
print(librarycomp.index('computer'))
print(len(librarycomp))
librarycomp.append('projects')
print(librarycomp)
librarycomp.insert(2,'newsletter')
print(librarycomp)
librarycomp.remove('projects')
print(librarycomp)
librarycomp.pop(2)
print(librarycomp)
librarycomp[2]='library attendance'
print(librarycomp)
librarycomp.sort()
print("After sorting: ",librarycomp)
librarycomp.reverse()
print("Reversed list: ", librarycomp)
New = librarycomp[:]
print(New)
x = slice(2)
print(librarycomp[x])
test_list1 = ['books', 'newspaper', 'computer', 'magazine', 'journals']
test_list2 = ['project','newsletter']
for i in test_list2 :
test_list1.append(i)
print("Concatenated list using naive method : ", str(test_list1))

28
OUTPUT
['books', 'newspaper', 'computer', 'magazine', 'journals']
books
newspaper
2
5
['books', 'newspaper', 'computer', 'magazine', 'journals', 'projects']
['books', 'newspaper', 'newsletter', 'computer', 'magazine', 'journals', 'projects']
['books', 'newspaper', 'newsletter', 'computer', 'magazine', 'journals']
['books', 'newspaper', 'computer', 'magazine', 'journals']
['books', 'newspaper', 'library attendance', 'magazine', 'journals']
After sorting: ['books', 'journals', 'library attendance', 'magazine', 'newspaper']
Reversed list: ['newspaper', 'magazine', 'library attendance', 'journals', 'books']
['newspaper', 'magazine', 'library attendance', 'journals', 'books']
['newspaper', 'magazine']
Concatenated list using naive method : ['books', 'newspaper', 'computer', 'magazine', 'journals',
'project', 'newsletter']

INFERENCE:

RESULT:
Thus the program was executed successfully.

29
EX. NO:4.c.(ii) Implementing real-time/technical applications Components of a Library
DATE: using Tuple.

AIM:
To write a python program to implement components of a Library using Tuple

ALGORITHM:
Step1:Start the program
Step2:Assign list of library materials
Step3Perform all the list operation
Step4:Print the result
Step5:End the program

PROGRAM

libcomp=('books', 'newspaper', 'computer', 'magazine', 'journals')


print('Our tuple is:',libcomp)
print('Item in the first position is: ',libcomp[0])
print('Item in the 5th position is: ',libcomp[4])
indexOfcomputer=libcomp.index('computer')
print('Index of computer is: ', indexOfcomputer)
Tuplelength=len(libcomp)
print('Length of the libcomp tuple is: ',Tuplelength)
for item in libcomp:
print(item)
print(libcomp*2)
print(libcomp[1:4])
if "journal" in libcomp:
print("journals is available in the libcomp tuple")
else:
print("journals is not available in the libcomp tuple")

30
OUTPUT
Our tuple is: ('books', 'newspaper', 'computer', 'magazine', 'journals')
Item in the first position is: books
Item in the 5th position is: journals
Index of computer is: 2
Length of the libcomp tuple is: 5
books
newspaper
computer
magazine
journals
('books', 'newspaper', 'computer', 'magazine', 'journals', 'books', 'newspaper', 'computer', 'magazine',
'journals')
('newspaper', 'computer', 'magazine')
journals is not available in the libcomp tuple

INFERENCE:

RESULT:
Thus the program was executed successfully.

31
EX. NO:5.a.(i)
Implementing real-time/technical applications Language using Sets.
DATE:
AIM:
To write a python program to implement language using set.

ALGORITHM:
Step1: Start the program.
Step2: Assign the languages.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
language1={'C','C++','JAVA'}
language2={'VB','PYTHON','ORACLE','JAVA'}
print(language1)
print(language2)
language1.add('SQL')
print(language1)
language1.remove('SQL')
print(language1)
print(language1 | language2)
print(language2.union(language1))
print(language1 & language2)
print(language1.intersection(language2))
print(language1 -language2)
print(language2.difference(language1))
print(language1 ^ language2)

OUTPUT:
{'JAVA', 'C', 'C++'}
{'PYTHON', 'VB', 'ORACLE', 'JAVA'}
{'JAVA', 'SQL', 'C', 'C++'}
{'JAVA', 'C', 'C++'}
{'JAVA', 'PYTHON', 'C++', 'ORACLE', 'VB', 'C'}
{'PYTHON', 'JAVA', 'VB', 'C', 'ORACLE', 'C++'}
{'JAVA'}
{'JAVA'}
{'C', 'C++'}
{'PYTHON', 'VB', 'ORACLE'}
{'C', 'ORACLE', 'PYTHON', 'C++', 'VB'}

RESULT:
Thus the python program to implement language using set was written and executed
successfully.
32
EX. NO:5.a.(ii) Implementing real-time/technical applications Language using
DATE: Dictionaries.

AIM:

To write a python program to implement language using dictionaries.

ALGORITHM:

Step1: Start the program.


Step2: Assign the languages.
Step3: Perform all the dictionary operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:

language={"C":5, "C++":3, "ORACLE":9, "PYTHON":7}


print(language)
x = language.copy()
print(x)
x = language.get("PYTHON")
print(x)
x = language.items()
print(x)
language.update({"JAVA":5})
print(language)
x = language.pop("C")
print(x)
print(language)
x = language.setdefault ("C++", 5)
print(x)
print(language)
x = language.values()
print(x)
y=5
thisdict = dict.fromkeys(language, y)
print(thisdict)
x = language.keys()
print(x)
language.clear()
print (language)

33
OUTPUT:
{'C': 5, 'C++': 3, 'ORACLE': 9, 'PYTHON': 7}
{'C': 5, 'C++': 3, 'ORACLE': 9, 'PYTHON': 7}
7
dict_items([('C', 5), ('C++', 3), ('ORACLE', 9), ('PYTHON', 7)])
{'C': 5, 'C++': 3, 'ORACLE': 9, 'PYTHON': 7, 'JAVA': 5}
5
{'C++': 3, 'ORACLE': 9, 'PYTHON': 7, 'JAVA': 5}
3
{'C++': 3, 'ORACLE': 9, 'PYTHON': 7, 'JAVA': 5}
dict_values([3, 9, 7, 5])
{'C++': 5, 'ORACLE': 5, 'PYTHON': 5, 'JAVA': 5}
dict_keys(['C++', 'ORACLE', 'PYTHON', 'JAVA'])
{}

INFERENCE:

RESULT:
Thus the python program to implement language using dictionaries was written and executed
successfully.

34
EX. NO:5.b.(i) Implementing real-time/technical applications components of an
DATE: automobile using Sets.

AIM:
To write a python program to implement components of an automobile using set.

ALGORITHM:
Step1: Start the program.
Step2: Assign the components of automobile.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
components1={'Engine','Chassis','Transmission'}
components2={'Steering','Tire','Engine'}
print(components1)
print(components2)
components1.add('Gearbox')
print(components1)
components1.remove('Gearbox')
print(components1)
print(components1 | components2)
print(components2.union(components1))
print(components1 & components2)
print(components1.intersection(components2))
print(components1 - components2)
print(components2.difference(components1))
print(components1 ^ components2) //Set symmetric difference

OUTPUT:
{'Transmission', 'Chassis', 'Engine'}
{'Engine', 'Steering', 'Tire'}
{'Transmission', 'Chassis', 'Engine', 'Gearbox'}
{'Transmission', 'Chassis', 'Engine'}
{'Steering', 'Tire', 'Transmission', 'Chassis', 'Engine'}
{'Steering', 'Tire', 'Transmission', 'Chassis', 'Engine'}
{'Engine'}
{'Engine'}
{'Transmission', 'Chassis'}
{'Steering', 'Tire'}
{'Steering', 'Tire', 'Transmission', 'Chassis'}

35
INFERENCE:

RESULT:
Thus the program was executed successfully.
36
EX. NO:5.b.(ii) Implementing real-time/technical applications components of an
DATE: automobile using Dictionaries.

AIM:
To write a python program to implement components of an automobile using dictionary.

ALGORITHM:

Step1: Start the program.


Step2: Assign the components of automobile.
Step3: Perform all the dictionary operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:

components = {"Break": 2,"Tire": 4,"Steering": 1}


print(components)
x = components.copy()
print(x)
x = components.get("Tire")
print(x)
x = components.items()
print(x)
components.update({"color": "White"})
print(components)
x = components.pop("Break")
print(x)
print(components)
x = components.setdefault("Break", "Tire")
print(x)
print(components)
x = components.values()
print(x)
y=1
thisdict = dict.fromkeys(components, y)
print(thisdict)
x = components.keys()
print(x)
components.clear()
print(components)

37
OUTPUT:

{'Break': 2, 'Tire': 4, 'Steering': 1}


{'Break': 2, 'Tire': 4, 'Steering': 1}
4
dict_items([('Break', 2), ('Tire', 4), ('Steering', 1)])
{'Break': 2, 'Tire': 4, 'Steering': 1, 'color': 'White'}
2
{'Tire': 4, 'Steering': 1, 'color': 'White'}
Tire
{'Tire': 4, 'Steering': 1, 'color': 'White', 'Break': 'Tire'}
dict_values([4, 1, 'White', 'Tire'])
{'Tire': 1, 'Steering': 1, 'color': 1, 'Break': 1}
dict_keys(['Tire', 'Steering', 'color', 'Break'])
{}

INFERENCE:

RESULT:
Thus the program was executed successfully.
38
EX. NO:5.c.(i) Implementing real-time/technical applications Elements of a civil
DATE: structure using Sets.

AIM:
To write a python program to implement components of an automobile using set .

ALGORITHM:
Step1: Start the program.
Step2: Assign the components of automobile.
Step3: Perform all the set operation.
Step4: Print the result.
Step5: End the program.

PROGRAM:
elements1={'columns','roof', 'stair','floors'}
elements2={'foundation','floors','walls'}
print(elements1)
print(elements2)
elements1.add('beams')
print(elements1)
elements1.remove('beams')
print(elements1)
print(elements1 | elements2)
print(elements2.union(elements1))
print(elements1 & elements2)
print(elements1.intersection(elements2))
print(elements1 - elements2)
print(elements2.difference(elements1))
print(elements1 ^ elements2)

OUTPUT:
{'roof', 'floors', 'columns', 'stair'}
{'walls', 'foundation', 'floors'}
{'stair', 'roof', 'floors', 'beams', 'columns'}
{'stair', 'roof', 'floors', 'columns'}
{'floors', 'stair', 'roof', 'foundation', 'walls', 'columns'}
{'floors', 'stair', 'roof', 'foundation', 'walls', 'columns'}
{'floors'}
{'floors'}
{'roof', 'columns', 'stair'}
{'foundation', 'walls'}
{'stair', 'roof', 'walls', 'foundation', 'columns'}

INFERENCE:

RESULT:
Thus the program was executed successfully.
39
EX. NO:5.c.(ii) Implementing real-time/technical applications Elements of a civil
DATE: structure using Dictionaries.

Aim: To write a python program to implement components of an automobile using dictionary.


Algorithm:
Step1: Start the program.
Step2: Assign the components of automobile.
Step3: Perform all the dictionary operation.
Step4: Print the result.
Step5: End the program.
Program:
elements = {"foundation":14, "floors":3, "walls":19, "beams":7}
print(elements)
x = elements.copy()
print(x)
x = elements.get("beams")
print(x)
x = elements.items()
print(x)
elements.update({"roof":5})
print(elements)
x = elements pop("foundation")
print(x)
print(elements)
x = elements.setdefault ("foundation", 5)
print(x)
print(elements)
x = elements.values()
print(x)
y=5
thisdict = dict.fromkeys(elements, y)
print(thisdict)
x = c elements.keys()
print(x)
elements.clear()
print(elements)
Output:
{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7}
{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7}
7
dict_items([('foundation', 14), ('floors', 3), ('walls', 19), ('beams', 7)])
{'foundation': 14, 'floors': 3, 'walls': 19, 'beams': 7, 'roof': 5}
14
{'floors': 3, 'walls': 19, 'beams': 7, 'roof': 5}
5

40
{'floors': 3, 'walls': 19, 'beams': 7, 'roof': 5, 'foundation': 5}
dict_values([3, 19, 7, 5, 5])
{'floors': 5, 'walls': 5, 'beams': 5, 'roof': 5, 'foundation': 5}
dict_keys(['floors', 'walls', 'beams', 'roof', 'foundation'])
{}

INFERENCE:

Result:
Thus the program was executed successfully.

41
EX. NO:6.a
Implementing Factorial of given number programs using Functions.
DATE:

AIM:
To write a Python Program to find factorial of a given number using function.

ALGORITHM:

STEP1: Start the program


STEP2: Define a function name factorial ()
STEP3: Assign or Get the value of n from the user.

STEP3: Return 1 if n==1 or 0(since 1! &0! is 1)


STEP4: Else compute n * factorial (n - 1)
STEP5: Print the factorial value for a given number
STEP6: End the program

PROGRAM:

def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1);
num = 5;
print("Factorial of",num,"is",
factorial(num))

OUTPUT:
Factorial of 5 is 120

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
42
EX. NO:6.b.
Implementing two Largest numbers in a list programs using Functions.
DATE:

AIM:
To write a Python Program to find two largest numbers in a list using functions.

ALGORITHM:

Step1: Start the program


Step2: Take a list of values
Step3: using max () function finds first largest number
Step4: using remove () function remove first largest largest function
Step5: Again using max () function finds second largest number
Step6: print the two largest number
Step7: End the program

PROGRAM:

integers = [1, 16, 3, 39, 26, 4, 8, 16]


copy_of_integers = integers[:]
largest_integer = max(copy_of_integers)
copy_of_integers.remove(largest_integer)
second_largest_integer = max(copy_of_integers)
print(largest_integer)
print(second_largest_integer)

OUTPUT:
39
26

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

43
EX. NO:6.c.
Implementing Area of shape programs using Functions.
DATE:

AIM:

To write a Python Program to find area of shape using functions.

ALGORITHM:

STEP1: Start the program

STEP2: Define a function name area calculator ()

STEP3: Assign area and Pie value

STEP4: Enter the shape you want to calculate

STEP5: print the area of the shape

STEP6: If shape is not found, print select a valid shape

STEP7: End the program

PROGRAM:
def areacalculator():
_input_ = input("Enter the shape you want to calculate area of: ")
area = 0
pie = 3.14
if _input_ == "Square":
side = int(input("Enter the value of side: "))
area = area + (side ** 2)
elif _input_ == "Circle":
radius = int(input("Enter the value of radius: "))
area = area + (2 * pie * radius)
elif _input_ == "Rectangle":
length = int(input("Enter the value of length: "))
width = int(input("Enter the value of length: "))
area = area + (length * width)
elif _input_ == "Triangle":
base = int(input("Enter the value of base: "))
height = int(input("Enter the value of height: "))
area = area +(0.5 * base * height)
else:
print ("Select a valid shape")
print ("%.2f" % area)
areacalculator()

44
OUTPUT:
Enter the shape you want to calculate area of: Square
Enter the value of side: 3
9.00
Enter the shape you want to calculate area of: square
Select a valid shape
0.00

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
45
EX. NO:7.a.
Implementing Reverse string programs using Strings.
DATE:

AIM:

To write a Python Program to reverse a string.

ALGORITHM:

STEP1:Start the program

STEP2:Define a function name myfunction ()

STEP3: Enter text to reverse

STEP4: Reverse the string using slice statement [::-1]

STEP5: Print the reversed string

STEP6: End the program

PROGRAM:
defmy_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)

OUTPUT:
sdrawkcabekilskooltxetsihtwohrednow I

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

46
EX. NO:7.b.
Implementing Palindrome programs using Strings.
DATE:

AIM:

To write a Python Program to find palindrome for the given string.

ALGORITHM:

STEP1: Start the program

STEP2: Get the string from the user

STEP3: Check given string is equal to slice statement

STEP4: Print string is palindrome or else not palindrome

STEP5: Stop the program

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

OUTPUT:
Enter a string:qwert
Not a palindrome
Trewq

Enter a string:malayalam
The string is a palindrome
Malayalam

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

47
EX. NO:7.c.
Implementing Character Count programs using Strings.
DATE:

AIM:
To write a Python Program to count the given character.

ALGORITHM:

STEP1: Start the program

STEP2: Assign the sentence to the variable

STEP3: Get the character from the user

STEP4: count the character using count ()

STEP5: print the number of occurrences of character

STEP6: Stop the program

PROGRAM:
message = 'python is popular programming language'
print('Number of occurrence of p:', message.count('p'))

OUTPUT:
Number of occurrence of p: 4

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
48
EX. NO:7.d.
Implementing Replacing Characters programs using Strings.
DATE:

AIM:

To write a Python Program to replace the character.

ALGORITHM:

STEP1: Start the program

STEP2: Get a string from the user

STEP3: Get a replace character from the user and replace the character using replace ()

STEP4: print the string

STEP5: Stop the program

PROGRAM:
a_string = "aba"
a_string = a_string.replace("a", "b")
print(a_string)

OUTPUT:
bbb

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
49
EX. NO:8.a. Implementing Pandas programs using written modules and Python
DATE: Standard Libraries.

AIM:

To implement pandas using written modules and Python Standard Libraries

ALGORITHM:

STEP1: Start the program

STEP2: import pandas library

STEP3: create alias for pandas

STEP4: create a simple pandas series from a list

STEP5: store the series in variable

STEP6: print the series using variable

STEP7: Stop the program

PROGRAM:
import pandas as pd
S = pd.Series([11, 28, 72, 3, 5, 8])
print(S)

OUTPUT:
0 11
1 28
2 72
3 3
4 5
5 8
Dtype : int64

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
50
EX. NO:8.b. Implementing Numpy programs using written modules and Python
DATE: Standard Libraries.

AIM:
To implement Numpy using written modules and Python Standard Libraries.

ALGORITHM:

STEP1: Start the program

STE2: Import numpy library

STEP3: create alias for numpy

STEP4: create an array of list

STEP5: Print the array

STEP6: print the shape of array

STEP7: Stop the program

PROGRAM:
importnumpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array
print(a.shape)
b = a[1:, 2:]
print(b)

OUTPUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

51
EX. NO:8.c. Implementing Matplotlib programs using written modules and Python
DATE: Standard Libraries.

AIM:

To implement matplotlib using written modules and Python Standard Libraries

ALGORITHM:

STEP1: Install Matplotlib

STEP2: Import pyplot and create alias for it.

STEP3: Define the x-axis and corresponding y-axis values as lists.

STEP4: Plot and name them using plt.xlabel () and plt.ylabel () functions

STEP5: Give a title to your plot using .title () function.

STEP6: Finally, to view your plot using show () function.

52
PROGRAM:
frommatplotlib import pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='r',width=.1)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Audi", color='b',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()

OUTPUT:

INFERENCE:

RESULT:
Thus the program was written and executed successfully.
53
EX. NO:8.d. Implementing Scipy programs using written modules and Python Standard
DATE: Libraries.

AIM:
To implement Scipy using written modules and Python Standard Libraries.

ALGORITHM:

STEP1: Install Scipy library and import special function

STEP2: using special function calculate exponential, sin and cos values

STEP3: Print the values

PROGRAM:
fromscipy import special
a = special.exp10(3)
print(a)
b = special.exp2(3)
print(b)
c = special.sindg(90)
print(c)
d = special.cosdg(45)
print(d)

OUTPUT:
1000.0
8.0
1.0
0.707106781187

INFERENCE:

RESULT:
Thus the program was written and executed successfully.

54
EX. NO:9.a. Implementing real-time/technical applications to copy from one file to
another using File Handling
DATE:

AIM:
To write a python program to copy from one file to another using file handling.

ALGORITHM:
Step 1: Start
Step 2: Open first.txt in read mode and read the contents of first.txt.
Step 3: Open second.txt in append mode and append the content of first.txt into second.txt.
Step 4: Stop

PROGRAM:

with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:


for line in firstfile:
secondfile.write(line)

OUTPUT:

first.txt
Welcome to Jaya Sakthi Engineering college, Thiruninravur, Chennai
second.txt
open second file ( all lines are copied successful )
Welcome to Jaya Sakthi Engineering college, Thiruninravur, Chennai

INFERENCE:

RESULT:

Thus, the python program to copy from one file to another using file handling was written
and executed successfully.

55
EX. NO:9.b. Implementing real-time/technical applications for word count using File
Handling
DATE:

AIM :

To write a python program to count the words in a file using file handling.

ALGORITHM:
Step 1: Start
Step 2: Open the file in read mode and handle it in text mode.
Step 3: Read the text using read() function.
Step 4: Split the text using space separator.
Step 5: Refine the count by validating the words after splitting.
Step 6: Print the number of words in the text file.
Step 7: Stop

PROGRAM:

file = open("first.txt", "rt")


data = file.read()
words = data.split()
print('Number of words in text file :', len(words))

OUTPUT:

first.txt
Welcome to Jaya Sakthi Engineering college Thiruninravur Chennai

Number of words in text file : 8

INFERENCE:

RESULT:

Thus, the python program to count the words in a file using file handling was written and
executed successfully.

56
EX. NO:9.c. Implementing real-time/technical applications for longest word using File
Handling
DATE:

AIM:

To write a python program to find the longest word in a file using file handling.

ALGORITHM:

Step 1: Start
Step 2: Read the file which contains the text
Step 3: Open the file in the read mode
Step 4: Read and split the words in the file
Step 5: calculate the length of the words
Step 6: compare the length of the words and return the longest word.
Step 7: Stop

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]
print(longest_word('first.txt'))

OUTPUT:

first.txt
Welcome to Jaya Sakthi Engineering college Chennai

['Engineering,']

INFERENCE:

RESULT:

Thus, the python program to find the longest word in a file using file handling was written and
executed successfully.

57
EX. NO:10.a. Implementing real-time/technical applications for Divide by Zero Error
using Exception Handling
DATE:

AIM:

To write a python program to demonstrate the divide by zero error using Exception Handling.

ALGORITHM:
Step 1: Start
Step 2: Get inputs from the user, two numbers.
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.

PROGRAM:

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

OUTPUT:

Enter First Number: 5


Enter Second Number: 0
division by zero

INFERENCE:

RESULT:

Thus, the python program to demonstrate the divide by zero error using Exception Handling
was written and executed successfully.

58
EX. NO:10.b. Implementing real-time/technical applications for voter’s age validity using
Exception Handling
DATE:

AIM:

To write a python program to validate voter’s age using Exception Handling.

ALGORITHM:

Step 1: Start
Step 2: Get the age as input
Step 3: If the entered value is a value apart from number, throw an exception
Step 4: If the value is less than zero, print an error message.
Step 5: If the value is number, check whether the number is greater than or equal to 18.
Step 6: If the age is 18, print able to vote else print not able to vote
Step 7: Stop

59
PROGRAM:

while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible to vote.")

OUTPUT:

Please enter your age: 12


You are not eligible to vote.

Please enter your age: 18


You are eligible to vote

INFERENCE:

RESULT:

Thus, the python program to validate voter’s age using Exception Handling was written and
executed successfully.

60
EX. NO:10.c. Implementing real-time/technical applications for student mark range
validation using Exception Handling
DATE:

AIM:

To write a python program to validate the student mark range using Exception Handling.

ALGORITHM:
Step 1: Start
Step 2: Read the mark
Step 3: Check whether the marks is less than zero and greater than 100 and print the result
Step 4: Stop.

PROGRAM:

while True:
studentmark = int(input("Enter the student Mark: "))
if studentmark< 0 or studentmark> 100:
print("The student Mark value is out of range, try again.")
else:
print("The student Mark entered is Valid.")
break

OUTPUT:

Enter the student Mark: 75


The student Mark entered is Valid.

Enter the student Mark: 104


The student Mark value is out of range, try again.

INFERENCE:

RESULT:

Thus, the python program to validate the student mark range using Exception Handling was
written and executed successfully.
61
EX. NO:11
Exploring Pygame tool
DATE:

AIM:

To explore Pygame tool.

PYGAME:
Pygame is a set of Python modules designed to make games. It uses SDL which is a cross
platform library that abstracts the multimedia components of a computer as audio and video and
allows an easier development of programs that uses these resources.

INSTALLATION:
Before starting the installation process, you must have python installed at your system.
The pygame installation itself can be different from an OS.

pip install pygame

HELLO WORLD:

As usual, when learning something new in programming we start as small as possible to


check it everything is working properly before proceeding with the studies.
To make that let’s create a file called hello.py with the following content:

Coding:

import time
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
pygame.display.set_caption('Hello World')
screen.fill([0, 0, 0])
pygame.display.flip()
time.sleep(5)

Then just need to run it. So, the result will be this:

62
import pygame - This provides access to the pygame framework and imports all functions of
pygame.

pygame.init() - This is used to initialize all the required module of the pygame.

pygame.display.set_mode((width, height)) - This is used to display a window of the desired size.


The return value is a Surface object which is the object where we will perform graphical operations.

pygame.event.get()- This is used to empty the event queue. If we do not call this, the window
messages will start to pile up and, the game will become unresponsive in the opinion of the
operating system.

pygame.QUIT - This is used to terminate the event when we click on the close button at the corner
of the window.

pygame.display.flip() - Pygame is double-buffered, so this shifts the buffers. It is essential to call


this function in order to make any updates that you make on the game screen to make visible.

63
Uploading image using pygame tool:

import pygame
pygame.init()
white = (255, 255, 255)
# assigning values to height and width variable
height = 400
width = 400
# creating the display surface object
# of specific dimension..e(X, Y).
display_surface = pygame.display.set_mode((height, width))

# set the pygame window name


pygame.display.set_caption('Image')

# creating a surface object, image is drawn on it.


image = pygame.image.load(r'C:\Users\DEVANSH SHARMA\Desktop\download.png')

# infinite loop
while True:
display_surface.fill(white)
display_surface.blit(image, (0, 0))

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
# quit the program.
quit()
Output:

64
Key Pressing and Releasing using pygame tool
import pygame
pygame.init()
# sets the window title
pygame.display.set_caption(u'Keyboard events')
# sets the window size
pygame.display.set_mode((400, 400))

while True:
# gets a single event from the event queue
event = pygame.event.wait()
# if the 'close' button of the window is pressed
if event.type == pygame.QUIT:
# stops the application
break
# Detects the 'KEYDOWN' and 'KEYUP' events
if event.type in (pygame.KEYDOWN, pygame.KEYUP):
# gets the key name
key_name = pygame.key.name(event.key)
# converts to uppercase the key name
key_name = key_name.upper()
# if any key is pressed
if event.type == pygame.KEYDOWN:
# prints on the console the key pressed
print(u'"{}" key pressed'.format(key_name))

65
# if any key is released
elif event.type == pygame.KEYUP:
# prints on the console the released key
print(u'"{}" key released'.format(key_name))

Output:

INFERENCE:

Result:
Thus, the Pygame tool is explored.

66
EX. NO:12
Developing a game activity using Pygame like bouncing ball, car race etc.
DATE:

AIM:

To developing a game activity using Pygame like bouncing ball, car race etc.

ALGORITHM:

Step 1: Start the program.


Step 2: Import the sys and pygame packages
Step 3: Initialize the pygame by using pygame.init
Step 4: Initialize the x & y axis for the ball
Step 5: set moveX, moveY = 0, 0
Step 6: set the R,B,G value for wite, blue, yellow , grey and black colors
Step 7: set the screen size to show the output
Step 8: Load the ball image and initialize the scale for transformation using
pygame.transform.scale(pygame.image.load('ball.png'), (70, 70))
Step 9 : While true call the event listener to
Step 10: stop the program

PROGRAM:

import sys, pygame


pygame.init()

size = width, height = 320, 240


speed = [1, 1]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("intro_ball.gif")
ballrect = ball.get_rect()

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]

67
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()

OUTPUT:

INFERENCE:

RESULT:

Thus, above can be executed successfully and verified.

68
EX. NO:13
Mini Project - Merge Sort
DATE:
AIM:
To write a Python Program for Merge Sort
ALGORITHM
Step1:Start the program
Step2:Define the function name
a. create temp arrays
b. Copy data to temp arrays L[] and R[]
c. Merge the temp arrays back into arr[l..r]
d. Copy the remaining elements of L[]
e. Copy the remaining elements of R[]
Step3:Define Merge sort function
Step4:Call the function name
Step5:End the Program

PROGRAM:
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:

69
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if there


# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr, l, r):
if l < r:
# Same as (l+r)//2, but avoids overflow for
# large l and h
m = l+(r-l)//2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Output:

Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

Result:

Thus, the program was executed successfully.

70
71

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy