0% found this document useful (0 votes)
15 views65 pages

Ge3171 PSPP Lab Manual Updated 12-8-24

Uploaded by

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

Ge3171 PSPP Lab Manual Updated 12-8-24

Uploaded by

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

SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY

(An Autonomous Institution)


(Approved by AICTE, New Delhi / Accredited by NAAC)
Dindigul- Palani Highway, Dindigul – 624 002.
Tamilnadu, India. 0451 - 2448800 – 2448899

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

LAB CODE GE3171

LAB NAME PROBLEM SOLVING AND


PYTHON
PROGRAMMING
LABORATORY
SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
(An Autonomous Institution)
(Approved by AICTE, New Delhi / Accredited by NAAC)
Dindigul- Palani Highway, Dindigul – 624 002.
Tamilnadu, India. 0451 - 2448800 – 2448899

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


VISION

To grow as an eminent department with international standards of excellence in computing


and research by integrating computer and information technology to develop products and services
for the benefit of the society with ethical values.

MISSION

To instill the students with the finest quality education


To impart good attitude and thereby casting them with creativity and research orientation
To initiate interest and equip students to design and develop intelligent products.
To inculcate the desire to serve the society with ethical values.

PROGRAM EDUCATIONAL
OBJECTIVES
PEO1: Technical Proficiency
Advance professionally to roles of greater computer engineering responsibilities in government
and private organizations, through providing solutions to challenging problems in their profession
by applying computer engineering theory and principles.

PEO2: Continuous educational growth

Engage in life-long learning through successful completion of post graduate programs in


engineering and interdisciplinary areas to emerge as researchers, experts, and educators.

PEO3: Managerial Skills

Develop and refine their knowledge to provide exposure to emerging cutting edge technologies,
adequate training and opportunities to work as teams on multidisciplinary projects with effective
communication skills and leadership qualities.

PEO4: Service to the society

Establish a commitment to the society by applying technical skills and knowledge to support
various service activities.

PROGRAMME SPECIFIC OUTCOMES

PSO 1: Understand the principles of basic engineering and acquire the hardware and software
aspects of computer science and engineering.

PSO 2: Design and develop applications or products using various programming language.
SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
(An Autonomous Institution)
(Approved by AICTE, New Delhi / Accredited by NAAC)
Dindigul – Palani Highway, Dindigul – 624 002

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Dos and Don’ts
Laboratory Rules & Regulation:

Students are instructed to maintain silence inside the Lab.


Students have to sign the log-book, while entering and leaving the Lab and also they have to
mention the time in and time out.
Students have to enter and leave the Lab in their scheduled time otherwise they will be marked
absent.
Students should come with proper Lab uniform and with shoes.
The students should properly shut down the Computer Systems before they leave the Lab.
Students are not allowed to use CD’s & DVD’s, USB DRIVE etc. lf required prior permission of
Laboratory in-charge is needed.
All students will be responsible for keeping the Lab clean.
Students should refrain from dislocating, shifting and damaging with any parts of the computer
or any other device in the Lab.
The students should not load or delete any software from the computer.
The students should not use computers in the Lab for any personal work.
Browsing of Internet will not be allowed in the lab beyond the stipulated hour as per time table.
The Instructor/Lecturer will be the sole authority to judge the disciplinary behavior inside
the laboratory. For violation of any of the above rules, the department reserves the right to
take
appropriate disciplinary action.
Browsing of non-academic Internet sites will not be allowed in the Lab.
Before downloading any materials please consult your instructor and save the downloaded files
as per instruction given by the laboratory in-charge.
Because of security problems, downloading software and music etc. from the Internet is strictly
prohibited. Any such file found in the hard disk will be deleted without warning.
Students should arrange the chairs properly while leaving the LAB hours.
Students should not allow to work inside the LAB other than LAB hours. If required prior
permission of Laboratory in-charge and Department in charge is needed.
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

OBJECTIVES:

To understand the problem solving approaches.


To learn the basic programming constructs in Python.
To practice various computing strategies for Python-based solutions to real world problems.
To use Python data structures - lists, tuples, dictionaries.
To do input/output with files in Python.

EXPERIMENTS:

Note: The examples suggested in each experiment are only indicative. The lab instructor is expected
to design other problems on similar lines. The Examination shall not be restricted to the sample
experiments listed here.

1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motorbike,
Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns, Pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of list &
tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (Reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas,
numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (Copy from one file to
another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (Divide by zero error,
Voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.

TOTAL: 60 PERIODS
OUTCOMES:

On completion of the course, students will be able to:


CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.

TEXT BOOKS:
1. Allen B. Downey, “Think Python : How to Think like a Computer Scientist”, 2nd Edition,
O’Reilly Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.

REFERENCES:

1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition,
2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers
and Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, "Introduction to Computation and Programming Using Python: With
Applications to Computational Modeling and Understanding Data‘‘, Third Edition,
MIT Press, 2021
4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to
Programming”, 2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
INSTALL AND CONFIGURE PYTHON IDE
I. Practical Significance

Python is a high-level, general-purpose, interpreted, interactive, object-oriented


Dynamic programming language. Student will able to select and install appropriate installer
for Python in windows and package manager for Linux in order to setup Python
environment for running programs.

II. Relevant Program Outcomes (POs)

Basic knowledge: Apply knowledge of basic mathematics, sciences and basic engineering
to solve the broad-based Computer engineering problem.
Discipline knowledge: Apply Computer engineering discipline - specific knowledge
to solve core computer engineering related problems.
Engineering tools: Apply relevant Computer technologies and tools with an
understanding of the limitations.
Communication: Communicate effectively in oral and written form.
Life-long learning: Engage in independent and life-long learning activities in the context
of technological changes in the Computer engineering field and allied industry.

III. Competency and Practical Skills


Develop general purpose programming using Python to solve problem

The practical is expected to develop the following skills:


Selecting and installing Python in Windows using appropriate installer.
Setting up Python environment for execution of Python programs

IV. Relevant Course Outcome(s)


Display message on screen using Python script on IDE.

V. Practical Outcomes (PrOs)


Setup a Python programming development environment

VI. Relevant Affective Domain related Outcome(s)


1. Follow safety practices
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices

VII. Minimum Theoretical Background

Python was created by Guido van Rossum during 1985- 1990. Like Perl, Python
Source code is also available under the GNU General Public License (GPL). Python is named
after a TV Show called ‘Monty Python’s Flying Circus’ and not after Python- the snake.

Installing Python in Windows:

Open any internet browser. Type http:///www.Python.org/downloads/ in address bar


and Enter.
Home page of Python will have displayed as shown in Fig. 1
Fig. 1: Home Page
Click on download the latest version for windows, which shows latest version as
shown in Fig. 2

Fig.2: Python release versions

Open the Python 3.7.1 version pack and double click on it to start installation and
installation windows will be open as shown in Fig. 3.

Fig. 3: Installation Type


Click on next install now for installation and then Setup progress windows will be
opened as shown in Fig. 4.

Fig. 4: Setup Progress


After complete the installation, Click on close button in the windows as shown in
Fig. 5.

Fig. 5: Setup Completion

Starting Python in different modes:


1) Starting Python (Command Line)
Press start button
Click on all programs and then click on Python 3.7 (32 bit). You will see the
Python interactive prompt in Python command line.

Python command prompt contains an opening message >>> called command prompt.
The cursor at command prompt waits for to enter Python command. A complete
command is called a statement. For example check first command to print message.
To exit from the command line of Python, press Ctrl+z followed by Enter or Enter
exit () or quit () and Enter.

2) Starting Python IDLE


Press start button and click on IDLE (Python 3.7 32 bit) options.

You will see the Python interactive prompt i.e. interactive shell.

Python interactive shell prompt contains opening message >>>, called shell
prompt. A cursor is waiting for the command. A complete command is called a
statement. When you write a command and press enter, the Python interpreter will
immediately display the result.
SAMPLE PROGRAMMES

# Python program to print "Hello World"

print("Hello World")

Output: Hello World

message = "Hello, World!"

print(message)

Output: Hello World!

print("Hello, World!")

Output: Hello, World!

# Python program to Adding two numbers

num1 = 15
num2 = 12

# Adding two numbers


sum = num1 + num2

# printing values
print("Sum of", num1, "and", num2 , "is", sum)

number1 = input("First number: ")


number2 = input("\n Second number: ")

# adding two numbers

# User might also enter float numbers

sum = float(number1) + float(number2)

# Display the sum


# will print value in float

print("The sum of {0} and {1} is {2}" .format(number1,number2, sum))


# Python program to find the maximum of two numbers

a=2
b=4
maximum = max(a, b)

print(maximum)

def maximum(a, b):

if a >= b:
return a
else:
return b

# Driver code
a=2
b=4

print(maximum(a, b))
Ex .No: 1a ELECTRICITY BILLING

AIM:
To draw a flowchart to calculate the electricity amount for the following scenario using
MS Word.

UNITS USED CHARGE PER UNIT

< = 150 Units Rs 5.50

151 – 300 Units Rs 6

300 – 500 Units Rs 6.50

>500 Units Rs 7

ALGORITHM:

STEP 1: Start the Program.


STEP 2: Read the number of Units ‘n’ from user.
STEP 3: If (n<=150) amount = n* 5.5
else if (n>150 && n<= 300) amount = n*6
else if (n>300&& n<= 500) amount = n*6.50
else if (n>500) amount = n* 7
STEP 4: Print the electricity charges ‘amount ‘.
STEP 5: Stop the Program.
FLOWCHART:

START

Read the no of Units ‘n’


True

If
Amount = n * 55
False
n>= True
150

False

True
if (n>150
&& Amount = n * 6
n<=False
300)

True

False
if 00
(n>3
&& n<= Amount = n * 6.5
500)

Amount = n * 7
if
(n>500)

Print Amount

Stop
RESULT:

Thus the flowchart to calculate electricity charges has been drawn successfully using
MS Word.
Ex No: 1b RETAIL SHOP BILLING

AIM:
To draw a flowchart to calculate the Bill amount of a Retail shop using MS Word.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Read the item name, item Quality, Item price for ‘n ‘products.

STEP 3: Calculate the following


Amount = Qty * Price
Tot amount = Total amount + Amount

STEP 4: Repeat the step 2 and step 3 for ‘n’ products

STEP 5: Print the tot amount.

STEP 6: Stop the program.


FLOWCHART:

Start

Set i=1, totamt=0

Read no of items ‘n’

Calculate amt = Qty *price,


totamt = totamt+amount

True

If i<=n Read item name, Quality, Price

False

Print Total Amount

Stop

RESULT:

Thus the flowchart to calculate the bill amount of a retail shop has been drawn
successfully using MS Word.
Ex No: 1c SINE SERIES

AIM:
To draw the flowchart in find the Sine Series using MS Word.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the value of ‘x’in radians and ‘n’.
STEP 3: Find the Sine Series using the formula

Sin(x) = x – x3 / 3! + x5 / 5! – x7 / 7! + x9 / 9!

STEP 4: Print the result


STEP 5: Stop the program

FLOWCHART:

Start

Read x in radians, read n

Set i=1
t=x
Sum=x

False

If i<=n Print Sum

Calculate
T=(t*(-1)*x*x)/2*i*(2*i+1)
Sum = Sum + t , i = i+ 1

Stop
RESULT:

Thus the flowchart for finding the Sine Series has been drawn successfully using MS
Word.
Ex No: 1d WEIGHT OF A MOTOR BIKE

AIM:

To draw a flowchart to print the weight of bike based on type of bike using MS Word.

ALGORITHM:

STEP 1: Start the program

STEP 2: Read the bike type from user.

STEP 3: Display the weight of bike based on following


categories Moped -> 73 – 82 kg
Scooler -> 91 -136 kg
Café racer -> 181 – 227 kg
Cruiser -> 181 – 318 kg”
Sportsbike -> 136 – 227 kg

STEP 4: Stop the program


FLOWCHART:

Start

Read bike type S

If type is Print “Weight is 73


MopedFalse
– 82 kg”
True

False
If type is True
Print “Weight is 91
Scooler -136 kg”
False
True

If type Print “Weight is


181 – 227 kg”
Fisalse True
Caperacer

False
False

If type is Print “Weight is


Cruiser 181 – 318 kg”

If type is Print “Weight is 136


Sportsbike
– 227 kg”

Stop

RESULT:
Thus the flowchart to print the weight of a motorbike has been drawn successfully
using MS Word.
Ex No: 1e WEIGHT OF A STEEL BAR

AIM:
To draw the flowchart in find the Sine Series using MS Word.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the diameter ‘D’ & length of steel ‘L’.
STEP 3: Calculate the weight in kg/m
W = D2 * L / 162.198
STEP 4: Print the Weight
STEP 5: Stop the program

FLOWCHART:

Start

Read D, L

Calculate W = D2*L / 162.198

Print the Weight


‘W‘

Stop

RESULT:

Thus the flowchart to find the weight of a steel bar has been drawn successfully using
MS Word.
Ex No: 1f ELECTRICITY CURRENT IN 3 PHASE AC CIRCUIT

AIM:

To draw the flowchart to find the electricity current in 3 phase AC circuit using
MS Word.

ALGORITHM:

STEP 1: Start the program


STEP 2: Read the power in KW and Power Factor (PF) from 3 phase AC circuit
STEP 3: Calculate the electricity circuit
KVA = Power in KW / PF
Current I = KVA * 1000 / 230

STEP 4: Print the Current (I)


STEP 5: Stop the program

FLOWCHART:

Start

Read power in KV and


power factor (pf)

Calculate KVA = Power in KW /


PF

Calculate Current (I) =


KVA * 1000 / 230

Print the Current (I)

Stop
RESULT:

Thus the flowchart to find the electricity current from 3 phase AC circuit has
been drawn successfully using MS Word.
EX NO: 2A SWAPPING OF TWO VARIABLES

AIM:

To write a program to swap two variables

ALGORITHM:
1. Start the program
2. Get two integer variables a, b from the user
3. Print a and b
4. Swap the variables
5. Print a and b.
6. Get two strings x and y from the user
7. Print the strings x and y.
8. Swap the strings using the temporary variable‘t’.
9. Print x and y.
10. Stop the program

PROGRAM:

#INTEGER SWAPPING

a= int (input ("Enter a"))


b = int (input ("Enter b"))
print ("Value of a:", a)
print ("Value of b:", b)
a, b = b, a
print ("values after swap")
print ("Value of a:", a)
print ("Value of b:", b)

#STRING SWAPPING

x= input ("Enter X")


y = input ("Enter Y")
print ("Value of x:", x)
print ("Value of y:", y)
t=x;
x=y;
y=t;
print("values after swap")
print ("Value of x:", x)
print ("Value of y:", y)
OUTPUT:

Enter a 12
Enter b 13
Value of a: 12
Value of b: 13
Values after swap
Value of a: 13
Value of b: 12
Enter X hello
Enter Y hi
Value of x: hello
Value of y: hi
Values after swap
Value of x: hi
Value of y: hello

RESULT:

The program to swap two variables is executed successfully.


EX 2.B CIRCULATING THE VALUES OF N VARIABLES

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

ALGORITHM

1. Start the program


2. Define the List with numbers
3. Print the initial list
4. Define the value for number of circulations (n) to be done
5. Use the list: operator to circulate.
6. Print the list after circulation
7. Stop the program

PROGRAM

list=[10,20,30,40,50]
print("Initial list is:", list)
n=2 #<<2 left shift by two bit position list=list[2:]+list[:2]
print ("list after circulation is:”, list)

OUTPUT

Initial list is: [10, 20, 30, 40, 50]


List after circulation is: [30, 40, 50, 10, 20]

RESULT

The python program to circulate the values of n variables successfully.


EX: 2C DISTANCE BETWEEN TWO POINTS

AIM

To write a python program to find the distance between two points

ALGORITHM

1. Start the program


2. Get the two points x1,x2 and y1,y2 from user
3. Calculate distance= sqrt((x2-x1)2 +(y2-y1)2)
4. Print the distance
5. Stop the program

PROGRAM

import math x1=int(input("Enter


x1")) y1=int(input("Enter y1"))
x2=int(input("Enter x2"))
y2=int(input("Enter y2"))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2) )
print(“ The distance between is”, distance)

OUTPUT
Enter x1 2
2
Enter y1 3
3
Enter x2 4
4
Enter y2 5
5
The distance between is 2.8284271247461903

RESULT:

The python program to find the distance between two points is executed successfully.
EX 3.A NUMBER SERIES

AIM:

To write a python program to print the sum of n numbers

ALGORITHM:

1. Start the program


2. Get the value of n from user
3. Initialize 1=1, sum=0
4. While (i<=n)
4.1 Read num
4.2 sum=sum+n
4.3 i=i+1
Go to step 4.
5. Print sum
6. Stop the program

PROGRAM:

n = int(input("Enter N: "))
sum = 0
for value in range(1, n+ 1): num=int(input("Enter the
number")) sum=int(sum)+num
print("The sum of n numbers is", sum)

OUTPUT:

Enter N: 5
Enter the
number12 Enter the
number15 Enter the
number35 Enter the
number60 Enter the
number82
The sum of n numbers is 204

RESULT:
The python program to find sum of number series is executed successfully.
EX 3.B PRINTING NUMBER PATTERNS

AIM:

To write a program to print number patterns.

ALGORITHM:

1. Start the program


2. Initialize the depth to print the numbers in right angle triangle
3. Use outer and inner loops to print the pattern
4. Stop the program

PROGRAM:

depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print("")

OUTPUT:

1
22
333
4444
55555

RESULT:

The program to print numbers in pattern is executed successfully.


EX: 3C PYRAMID PATTERN

AIM:

To write a program to print PYRAMID PATTERN of numbers

ALGORITHM:

1. Start the program


2. Initialize the depth to print the numbers PYRAMID PATTERN
3. Use outer and inner loops to print the pattern
4. Stop the program

PROGRAM

row=6
a=0
print("Full Pyramid Pattern of Stars (*):
") for i in range(row):
for s in range(1, row-i):
print(" ", end="")
for j in range(2*i-1):
print(a, end="")
a=a+1
print()
OUTPUT:

1
222
33333
4444444
555555555

RESULT:

The program to print numbers in pyramid pattern is executed successfully.


EX 4.a LIST OPERATIONS

AIM:
To write a python program to implement List operations for library.

ALGORITHM:

1. Start the program


2. Declare the list of strings with its values
3. Add elements to the list, slice the list, append and remove elements from the list using the built in
list functions
4. Display the changes in list after each operation
5. Stop the program.

PROGRAM:

# Python code for various list operation

# declaring a list of strings


iList = ['wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank', 'seat',
'number_plate']

# List slicing operations


# printing the complete list
print('iList: ',iList)
# Printing first element
print('first element: ',iList[0])
# printing fourth element
print('fourth element: ',iList[3])
# printing list elements from 0th index to 4th index
print('iList elements from 0 to 4 index:',iList[0: 5])
# printing list -7th or 3rd element from the list
print('3rd or -7th element:',iList[-7])

# appending an element to the list


iList.append('wheel_cover')
print('iList after append():',iList)

# finding index of a specified element


print('index of door: ',iList.index('door'))

# sorting the elements of iLIst


iList.sort()
print('after sorting: ', iList);
# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);

# removing specified element


iList.remove('engine')
print('after removing \engine: ',iList)

# inserting an element at specified index


# inserting car_key at 2nd index iList.insert(2,
'car_key') print('after insert: ', iList)

# counting occurances of a specified element


print('number of occurences of seat: ', iList.count('seat'))

# extending elements i.e. inserting a list to the list


iList.extend(['front_mirror','rear_mirror' ]) print('after extending:', iList)

#reversing the list


iList.reverse()
print('after reversing:', iList)

OUTPUT:

('wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank', 'seat', 'number_plate')
2
5
('wheel', 'door', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank', 'seat', 'number_plate',
'front_mirror', 'real_mirror')
door
wheel
['door', 'engine', 'front_mirror', 'fuel_tank', 'head_lamp', 'number_plate', 'real_mirror', 'seat', 'seat',
'steering_wheel', 'tail_lamp', 'wheel']
('real_mirror', 'front_mirror', 'number_plate', 'seat', 'fuel_tank', 'steering_wheel', 'seat', 'engine', 'tail_lamp',
'head_lamp', 'door', 'wheel')
wheel
('door', 'head_lamp', 'tail_lamp')
Yes item exists
('wheel', 'car_key', 'head_lamp', 'tail_lamp', 'engine', 'seat', 'steering_wheel', 'fuel_tank', 'seat',
'number_plate', 'front_mirror', 'real_mirror')
('wheel', 'car_key', 'head_lamp', 'tail_lamp', 'seat', 'steering_wheel', 'fuel_tank', 'seat', 'number_plate',
'front_mirror', 'real_mirror')

RESULT:

The python program to implement list operations for car is implemented successfully.
EX 4.b TUPLE OPERATIONS

AIM:

To write a python program to implement Tuple operations for books in library

ALGORITHM:

1. Start the program


2. Declare the Tuple book with its values
3. Add elements to the list, slice the list, concatenate, count and do type conversion from of
the tuple using the built in list functions
4. Display the changes in Tuple book after each operation
5. Stop the program

PROGRAM:

book=("HARRY POTTER", 'ENGINEERING GRAPHICS',"PYTHON PROGRAMMING",


"FUNDAMENTALS OF PROGRAMMING", "MASTER MINDS") book_2=("THREE LITTLE
PIGS", "MURDER IN ORIENTAL EXPRESS") print ("The data type of book element is ",
type(book)) print("The elements in book are", book)
print("The first element of the book is", book[0])
#SLICING OPERATION
print("Printing elements of book from 1 to 3 is", book[:4])
#CONCATENATION
print("The joined elements of the book and book_2 is", book+book_2)
#LENGTH OF THE TUPLE
print("The length of the element book is ",len(book))
#MEMBERSHIP OPREATION
print("HARRY POTTER" in book)
#COUNT AND INDEX IN TUPLE BOOK
print("The number of programming books is",
book.count("PROGRAMMING"))
print("The index of the element ENGINEERING GRAPHICS IN BOOK TUPLE
IS",book.index("ENGINEERING GRAPHICS"))
#CONVERTING TUPLE TO LIST TO REMOVE ELEMENTS
ilist=list(book) ilist.remove("HARRY
POTTER") book=tuple(ilist)
print("The elements of the book after removing harry potter is", book)
OUTPUT:

The data type of book element is <class 'tuple'>


The elements in book are ('HARRY POTTER', 'ENGINEERING GRAPHICS', 'PYTHON
PROGRAMMING', 'FUNDAMENTALS OF PROGRAMMING', 'MASTER MINDS')
The first element of the book is HARRY POTTER
Printing elements of book from 0 to 3 is ('HARRY POTTER', 'ENGINEERING GRAPHICS',
'PYTHON PROGRAMMING', 'FUNDAMENTALS OF PROGRAMMING')
The joined elements of the book and book_2 is ('HARRY POTTER', 'ENGINEERING GRAPHICS',
'PYTHON PROGRAMMING', 'FUNDAMENTALS OF PROGRAMMING', 'MASTER MINDS',
'THREE LITTLE PIGS', 'MURDER IN ORIENTAL EXPRESS')
The length of the element book is 5
True
The number of python programming in books is 1
The index of the element ENGINEERING GRAPHICS IN BOOK TUPLE IS 1
The elements of the book after removing harry potter is ('ENGINEERING GRAPHICS',
'PYTHON PROGRAMMING', 'FUNDAMENTALS OF PROGRAMMING',
'MASTER MINDS')

RESULT:

The python program to implement tuple operations for books in a library is


implemented successfully.
EX.5A IMPLEMENTING THE ELEMENTS OF CIVIL STRUCTURE USING PYTHON

SETS. AIM:

To write a python program to implement set operations for elements for civil structure.

ALGORITHM:
1. Start the program
2. Initialize set values in python
3. Use add() function to add values to the set
4. Use update () function to find the union of sets
5. Use |, ^,-, & operators to do union, unique elements , difference and intersection in sets
6. Use remove() function to remove an element from the set
7. Use pop(() function to remove last element of the set.
8. Stop the program.

PROGRAM

set1={'cement','bricks''tiles','doors','steel rods','pipes','roofs','lifts'}
set2={'roofs','rain shade','staircase','lifts','gate'}
for x in set1,set2: #DISPLAYING SETS
print(x)
print('roofs' in set2) #SEARCHING IN SET
set1.add('pillar')
print(set1) #AFTER ADDING PILLAR TO THE SET print(set1|
set2)#ADDING TWO SETS USING OPERATORS print(set1&set2)#
INTERSECTION OF SETS USING OPERATORS print(set1-
set2)#DIFFERENCE BETWEEN SETS
print(set1^set2)# UNIQUE ELEMENTS COMBINING BOTH THE LIST
set2.intersection_update(set1)#INTERSECTION OPERATION
print(set2)
set1.update(set2) #UNION OF SETS
print(set1)
set1.remove('pillar') #REMOVING AN ELEMENT FROM THE SET
print(set1)
set1.pop() #REMOVING LAST ELEMENT
print(set1)
OUTPUT

{'roofs', 'brickstiles', 'pipes', 'steel rods', 'cement', 'doors', 'lifts'}


{'gate', 'roofs', 'staircase', 'rain shade', 'lifts'} True
{'roofs', 'brickstiles', 'pipes', 'pillar', 'steel rods', 'cement', 'doors', 'lifts'}
{'roofs', 'brickstiles', 'pipes', 'gate', 'pillar', 'steel rods', 'cement', 'doors',
'staircase', 'rain shade', 'lifts'}
{'roofs', 'lifts'}
{'brickstiles', 'pillar', 'steel rods', 'pipes', 'doors', 'cement'}
{'cement', 'pipes', 'staircase', 'brickstiles', 'gate', 'pillar', 'steel rods',
'doors', 'rain shade'}
{'roofs', 'lifts'}
{'roofs', 'brickstiles', 'pipes', 'pillar', 'steel rods', 'cement', 'doors', 'lifts'}
{'roofs', 'brickstiles', 'pipes', 'steel rods', 'cement', 'doors', 'lifts'}
{'brickstiles', 'pipes', 'steel rods', 'cement', 'doors', 'lifts'}

RESULT

A python program to implement set operations for civil structure is implemented successfully
EX.5B IMPLEMENTING THE COMPONENTS OF AUTOMOBILE USING PYTHON DICTIONARY

AIM:

To write a python program to implement dictionary operations for components of automobile


structure.

ALGORITHM:

1. Start the program


2. Initialize the dictionary values
3. Use get()function to retrieve the values of the specified key
4. Use keys() function to print the key of the dictionary
5. Use values()function to print the values of the dictionary
6. Use len([dictionary name]) function to print the length of the dictionary
7. Use items() function to display the key value pairs of the dictionary
8. Use ‘in’operator to check if the key is present in dictionary or not
9. Use pop() function to remove the element with the specified key
10. Use popitem() function to remove the last element
11. Use del([key])function to delete element with the specified key
12. Use clear() function to delete all the key value pairs of the dictionary
13. Use iteritems()function to iterate over the dictionary elements
14. Use sorted(dict.keys()) function is used to sort the key values of the dictionary.
15. Stop the program.

PROGRAM

dict1={"brand": "MARUTHI","model": "SWIFT","year": 2009}


print(dict1)
x=dict1.get('brand') #accessing the values based on key print(x)
print(dict1['model']) # another way to access the values based on key print(dict1.keys()) #display
all the keys print(dict1.values())#Displays all the values in dictionary print(dict1.items())
#display key value pairs
print("The length of dictionary is :",len(dict1))
dict1['color']='Black grey' #adding elements in dictionary print(dict1)
if 'color' in dict1:
print('yes color is one of the key in dictionary') dict1['year']='2020' #
change the value of the year print(dict1)
print("REMOVING THE LAST ITEM")
dict1.popitem() #remove the last item print(dict1)
print("REMOVING THE ITEM AT THE SPECIFIED KEY
'model")
dict1.pop('model') #remove the specified item print(dict1)
print("COPYING DICT2 TO DICT1")
dict2=dict1.copy() #copy dict1 to dict2 print(dict2)
print("JOINING DICTIONARIES CHILD 1 AND CHILD 2")
child1 = {"brand" : "Ford","year" : 2012}
child2 = {"color" : "Meroon", "capacity" :"four-seated"}
print(child1.update(child2))
print("NESTED DICTIONARY")
dict3 = {"child1" : child1, "child2" : child2} #nested dictionary print(dict3)
del dict1['year']
print(dict1)
dict1.clear()
print(dict1)
dict1={3:”Charles”,2:”J.K.Rowling”,1:”Agatha christe”}
print(sorted(dict1.keys())

OUTPUT

{'brand': 'MARUTHI', 'model': 'SWIFT', 'year': 2009} MARUTHI


SWIFT
dict_keys(['brand', 'model', 'year'])
dict_values(['MARUTHI', 'SWIFT', 2009])
dict_items([('brand', 'MARUTHI'), ('model', 'SWIFT'), ('year', 2009)]) The length of dictionary
is : 3
{'brand': 'MARUTHI', 'model': 'SWIFT', 'year': 2009, 'color': 'Black grey'}
yes color is one of the key in dictionary
{'brand': 'MARUTHI', 'model': 'SWIFT', 'year': '2020', 'color': 'Black grey'} REMOVING THE LAST
ITEM
{'brand': 'MARUTHI', 'model': 'SWIFT', 'year': '2020'}
REMOVING THE ITEM AT THE SPECIFIED KEY 'model
{'brand': 'MARUTHI', 'year': '2020'} COPYING
DICT2 TO DICT1
{'brand': 'MARUTHI', 'year': '2020'} JOINING
DICTIONARIES CHILD 1 AND CHILD 2
None
NESTED DICTIONARY
{'child1': {'brand': 'Ford', 'year': 2012, 'color': 'Meroon', 'capacity':
'four-seated'}, 'child2': {'color': 'Meroon', 'capacity': 'four-seated'}}
{'brand': 'MARUTHI'}
{}
[1, 2, 3]

RESULT

A python program to implement dictionary operations for components of automobile


structure is executed successfully.
EX.6 PYTHON PROGRAMS USING FUNCTIONS

AIM:

To write a Python program to implement Factorial, Swapping two values, Largest of 3 numbers
in a list, Area of mathematical shapes using functions.

ALGORITHM:

1. Start the program


2. Define the function using def keyword
3. For factorial function “fact(n)”, pass the number for which the factorial has to be found (n) as
the parameter
3.1 Define the function, def fact(n)
3.2 Initialize i=1
3.3 While(i<n)
3.3.1 If n==1, return 1
3.3.2 Else return(n*n-1).go to step 3.1
4. For swapping two values function” swap(a,b)”,
4.1 Define the function swap()
4.1.1 Swap the variables of different data types using a,b=b,a statement.
4.1.2 Swap using temporary variable
4.1.3 Print the values of a and b after swapping.
5. For finding largest of two numbers using list function large”(list_1)”
5.1 Define the function large(list_1)
5.1.1 Initialize max=Iist_1[0], i=0
5.1.2 For (i<len(list_1)
5.1.2.1 If(list1[index]>max)
5.1.2.1.1 Swap(max, list_1[index])
5.1.2.1.2 i=i+1
5.1.3 Print the maximum element is max
6. For finding the area of shapes, def separate functions to find area of square ,rectangle, triangle,
circle.
6.1 Define function area_square(side)
6.1.1 Compute area=side*side
6.1.2 Print the value of area
6.2 Define function area_triangle(base,height)
6.2.1 Compute area=base*height
6.2.2 Print the value of area
6.3 Define function area_circle(radius)
6.3.1 Compute area=3.14*r*r
6.3.2 Print the value of area
6.4 Define function area_rectangle(length, breadth)
6.4.1 Compute area=length*breadth
6.4.2 Print the value of area
7. Get the input values n, a,b , list, radius, side,length,breadth,base ,height.
8. Call the functions in order with function names.
9. Stop the program.

PROGRAM:

max_element=0
a=0
b=0
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def max_list(list_1):
maxi=list_1[0]
for i in range(0,len(list_1),1):
if(list_1[i]>maxi): t=maxi
maxi=list_1[i]
list_1[i]=t
return(maxi)
def swap(a,b):
t=a
a=b
b=t
return(a,b)
# the area of a shapes def
calculate_area(name):

# converting all characters


# into lower cases
name = name.lower()
# check for the conditions if name ==
"rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth:
"))
# calculate area of rectangle rect_area = l *
b
print("The area of rectangle is",rect_area)
elif name == "square":
s = int(input("Enter square's side length: "))
# calculate area of square sqt_area = s
*s
print("The area of square is",sqt_area)
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length:
"))
# calculate area of triangle tri_area = 0.5 * b *
h
print(f"The area of triangle is",tri_area)
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
# calculate area of circle circ_area = pi * r * r
print(f"The area of circle is",circ_area)
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length:
"))
# calculate area of parallelogram para_area = b * h
print(f"The area of parallelogram is ",para_area)
else:
print("Sorry! This shape is not available") n=int(input("Input a number to
compute the factorial : ")) print("The factorial value of n is",factorial(n))
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
# function calling
calculate_area(shape_name) a=input("enter
the a value:") b=input("enter the b value:")
print("The values of a and b: Before Swapping:",a,b)
a,b=swap(a,b)
print("The values of a and b: After Swapping:",a,b)
list_1=[10,65,32,78,90,121]
print("the length of the list is",len(list_1))
print("maximum element in list using max function is", max(list_1))
max_element=max_list(list_1)
print("The maximum element in the list without using max function is",max_element)
#list_1.remove(max_element)
max_element=max_list(list_1)
print("The second maximum element in the list without using max function is ",max_element)
OUTPUT:

Input a number to compute the factorial : 5


The factorial value of n is 120
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 enter the a
value:23
enter the b value:45
The values of a and b: Before Swapping: 23 45
The values of a and b: After Swapping: 45 23 the length of the list
is 6
maximum element in list using max function is 121
The maximum element in the list without using max function is 121
The second maximum element in the list without using max function is
90
>

RESULT:

Python program to implement Factorial, Swapping two values, Largest of 3 numbers in a list,
Area of mathematical shapes using functions.
EX 7.A STRING BUILT IN FUNCTIONS

AIM:

To write a python program to implement the string built in functions.

ALGORITHM:

1. Start the program


2. Define the string and use string built-in functions for performing string reverse(), string
count(), string replace()methods.
3. Display the results
4. Stop the program.

PROGRAM:

txt = "PYTHON PROGRAMMING"


print("Reverse of the string txt is", txt[::-1])
s = "malayalam" if
s==s[::-1]:
print("The given string",s,"is palindrome")
else:
print("The given string",s,"is not palindrome")
str1 = "problem solving and python programming"
str_count1 = str1.count('p') # counting the character “o” in the
givenstring
print("The count of 'p' is", str_count1)
str_count2 = str1.count('p', 0,len(str1))
print("The count of 'p' using start/end is", str_count2) string = "Dhoni Sachin Kohli
Sachin Sachin" print(string.replace("Sachin", "Dhoni"))
print(string.replace("Sachin", "Dhoni", 2))

OUTPUT:
Reverse of the string txt is GNIMMARGORP NOHTYP The given
string malayalam is palindrome
The count of 'p' is 3
The count of 'p' using start/end is 3
Dhoni Dhoni Kohli Dhoni Dhoni
Dhoni Dhoni Kohli Dhoni Sachin

RESULT:

The python program to execute the string built-in functions is executed successfully.
EX 7.B STRING USER-

DEFINEDFUNCTIONS AIM:

To write a python program to implement the string built in functions.

ALGORITHM:

1. Start the program


2. Define the string function reverse ():
2.1 Get the string from the user
2.2 Use string reverse with slicing operator
3. Get the strings to check for palindrome
4. Find the reverse of the first string using strrev() and store it in strrev variable
5. Compare the strings strrev and string1 and print palindrome or not.
6. Use strcount() function to count the specific character in the string using for loops
7. Use strreplace(string, substring to be replaced, replacing string) to replace the substrings
in the particular string
8. Stop the program

PROGRAM:

def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]

s = "Hello world"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using recursion) is : ",end="")
print (reverse(s))
string1=input("palindrome check: Enter the string")
strrev=reverse(string1)
if(string1==strrev):
print("palindrome")
def strcount(s):
count=0
print("the string received is",s)
char=input("Enter the character to be counted in the string")
for i in s:
if(i==char):
count=count+1
print("the count of",char,"is: ",count)
strcount("hello world")
def replace(strng, substr, rplstr):
if substr not in strng:
return strng
low_index = strng.find(substr) # get lowest index of substring
high_index = low_index + len(substr) # evaluate the highest index of substring

return replace(strng[:low_index]+ rplstr + strng[high_index:], substr, rplstr)

print("String replace")
string1=input("Enter string to be
replaced")
string2=input("Enter the substring to replace") string3=input("Enter
the replacing substring") print(replace(string1,string2,string3))

OUTPUT:
The original string is : Hello world
The reversed string(using recursion) is : dlrow olleH
palindrome check: Enter the string malayalam
palindrome the string received is hello world Enter the character to be
counted in the string o
the count of o is: 2
String replace Enter string to be replaced hello
Enter the substring to replace ello
Enter the replacing substring
@@@@
h@@@@

RESULT:

The python program to execute the string user defined functions is executed successfully.
EX 8A PROGRAMS USING PYTHON STANDARD LIBRARY

NUMPY AIM:

To write python programs using standard library Numpy

ALGORITHM:

1. Create a two dimensional array using numpy object np


2. Perform indexing operation on the arrays using[] operator
3. Use built in functions add, sum and T,sort to find addition, sum of elements in
an array,Transponse and sorting.
4. Display the results
5. Stop.

PROGRAM
import numpy as np

# Defining Array 1
a = np.array([[1, 2], [3, 4]])

# Defining Array 2
b = np.array([[4, 3], [2, 1]])
# Indexing the elements in array
print("Printing row 1 elements of b array")
print(b[0])
# Adding 1 to every element
print ("Adding 1 to every element:", a + 1)

# Subtracting 2 from each element


print ("\nSubtracting 2 from each element:", b - 2)

# sum of array elements


# Performing Unary operations
print ("\nSum of all array " "elements:",a.sum())

# Adding two arrays


# Performing Binary operations
print ("\nArray sum:\n", a + b)
print("Array sum using built in function",np.add(a,b))
# Square root of Array
Sqrt = np.sqrt(a)
print("\nSquare root of Array'a' elements: ")
print(Sqrt)
# Transpose of Array
# using In-built function 'T'
Trans_arr = a.T print("\
nTranspose of Array: ")
print(Trans_arr)
print("Sorting b array")
print(np.sort(b))

OUTPUT

Printing row 1 elements of b array


[4 3]
Adding 1 to every element: [[2 3] [4 5]]

Subtracting 2 from each element: [[ 2 1] [ 0 -1]]

Sum of all array elements: 10

Array sum:
[[5 5][5 5]]
Array sum using built in function
[[5 5][5 5]]

Square root of Array'a' elements:


[[1.1.41421356]
[1.73205081 2.]]

Transpose of Array:
[[1 3][2 4]]
Sorting b array
[[3 4][1 2]]

** Process exited - Return Code: 0 ** Press Enter


to exit terminal

RESULT:

Python programs using standard library Numpy is executed successfully.


EX 8B PROGRAM USING PYTHON STANDARD LIBRARY PANDAS

AIM:

To write python programs using standard library PANDAS

ALGORITHM:

1. Start the program


2. Create a 1d array using list data.
3. Make it as a series using panda object.series(data, index) function.
4. Display the series.
5. Create a 2d array using dictionary.
6. Create dict1 and dict2.
7. Make it as a data frame using panda object.dataframe(key:dict1,key:dict2)
8. Display the data frame.
9. Create two 2d arrays.
10. Make it as a dataframe using pandaobject.dataframe(key:array1,key:array2)
11. Display the dataframe
12. Stop

PROGRAM

import pandas as pd
Data =[1, 3, 4, 5, 6, 2, 9]
# Creating series with default index values
s = pd.Series(Data)

# predefined index values


Index =['a', 'b', 'c', 'd', 'e', 'f',
'g']

# Creating series with predefined index values


si = pd.Series(Data, Index)
print(" ")
print("printing 1d daa using series ")
print("
")
print(si)

# Program to Create Data Frame with two dictionaries

# Define Dictionary 1
dict1 ={'a':1, 'b':2, 'c':3, 'd':4}

# Define Dictionary 2
dict2 ={'a':5, 'b':6, 'c':7, 'd':8, 'e':9}

# Define Data with dict1 and dict2


Data = {'first':dict1, 'second':dict2}

# Create DataFrame
df = pd.DataFrame(Data)
print(" ")
print("Dictionary data frames")
print(" ")
print(df)
# Define 2d array 1
d1 = [[2, 3, 4], [5, 6, 7]]

# Define 2d array 2
d2 = [[2,4, 8], [1, 3, 9]]
# Define Data Data = {'first': d1, 'second': d2}
# Create DataFrame
df2d = pd.DataFrame(Data)
print(" ")
print("2d array series using dataframes")
print(" ")
print(df2d)

OUTPUT
printing 1d data using series
a 1
b 3
c 4
d 5
e 6
f 2
g 9

dtype: int64

Dictionary data frame

first second
a 1.0 5
b 2.0 6
c 3.0 7
d 4.0 8
e NaN 9

2d array series using dataframes


first second

0 [2, 3, 4] [2, 4, 8]
1 [5, 6, 7] [1, 3, 9]
RESULT

Python program using standard library pandas is executed successfully.


EX 8C PROGRAM USING PYTHON STANDARD LIBRARY

SCIPY AIM:

To write python programs using standard library Scipy

ALGORITHM:

1. Import constants from scipy libarary using import keyword


2. Declare the points p1, p2
3. Print the constant values using constants.constant name as syntax
4. Calculate the Euclidean distance between p1 and p2 using Euclidean function inside
scipy library.
5. Display the result
6. Stop

PROGRAM

from scipy import constants


from scipy.spatial.distance import Euclidean
print(constants.pi) #display the value of pi
print(constants.kibi) #return the unit in bytes that is
kilobytes p1 = (1, 0)
p2 = (10, 2)
res = euclidean(p1, p2) #euclidean distance between two
points print(res)

OUTPUT

3.141592653589793

1024

9.219544457292887

RESULT:

Python programs using standard library Scipy is written and executed successfully.
EX 8D PROGRAM USING PYTHON STANDARD LIBRARY

MATLIB AIM:

To write python programs using standard library Matlib

ALGORITHM:

1. Import the matlab library file pyplot to draw bar graph


2. Create two arrays using numpy object np
3. Draw the bar graph using plt.bar () function taking x,y arrays as parameters.
4. Display the results
5. Stop.

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 = "hotpink",width=0.5)
plt.show()

OUTPUT

RESULT:

Python programs using standard library Matlib is written and executed successfully.
EX 9 PYTHON FILE HANDLING

AIM:

To implement python file handling operations

ALGORITHM

1. Start the program


2. Open the respective file using fileptr=open()function in read mode.
3. Display the contents using the file pointer read() and print function.
4. Open the file using fileptr in write mode”w” and write contents to the file in case of
appending, open it in
“a” mode.
5. For over writing the files , open the file in write mode and refresh new contents to it.
6. For finding the number of words in a file, use fileptr.count() function with fileptr being in “w”
mode.
7. For finding the longest word in the file,
Compute split()function to find the words of the file
Compute len() function to find the lengths of the word in the file
Compute max() to find the maximum length word in the file.
8. For finding the occurrences of a particular word in a file, use count () function to count
the repetition of the
word in the file.
9. Display the output
10. Stop the program

PROGRAM

file1 = open("myfile.txt", "w")


L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()

file1 = open("myfile.txt","r")
print(" ")
print("Initial file contents")
print(" ")
print(file1.read())
print()
file1.close()

file1 = open("myfile.txt", "a") # append


mode file1.write("Today \n")
file1.close()
file1 = open("myfile.txt", "r")
print(" ")
print("Output of Readlines after
appending") print(" ")
print(file1.read())
print()
file1.close()
print(" ")
print(" OVER WRITING THE CONTENTS OF THE FILE")
print(" ")
print()
file1=open("myfile.txt","w")
file1.write(" HI HELLO..WELCOME TO PYTHON PROGRAMMING..PYTHON IS A OPEN SOURCE
FREE PROGRAMMING LANGUAGE")
file1.close()
file1 = open("myfile.txt","r")
data=file1.read()
words=data.split()
print("PRINTING THE WORDS IN THE FILE")
print()
print(words)
print()
print("THE TOTAL NUMBER OF WORDS IN THE FILE",file1,"IS ",len(words))
file1.close()
print(" ")
print("FINDING THE NUMBER OF OCCURENCES OF A WORD")
print(" ")
file1 = open("myfile.txt", "r")
data=file1.read()
occurences= data.count("PYTHON")
print("THE NUMBER OF OCCURENCES OF THE WORD PYTHON IN THE
FILE",file1,"is",occurences)

print(" ")
print("FINDING THE LONGEST WORD IN THE FILE")
print(" ")
print()
print("THE WORDS IN THE FILE ARE",words)
max_len = len(max(words, key=len))
print("THE LONGEST WORD LENGTH IS",max_len)
for i in words:
if(len(i)==max_len):
print(" THE LONGEST WORD IS",i)
file1.close()
print("Write-Overwrites")
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt", "r")
print(" ")
print("Output of Readlines after
writing") print(" ")
print(file1.read())
print()
file1.close()

OUTPUT

Initial file contents

This is Delhi
This is Paris
This is
London

Output of Readlines after appending

This is Delhi
This is Paris
This is LondonToday

OVER WRITING THE CONTENTS OF THE FILE PRINTING THE WORDS IN THE FILE

['HI', 'HELLO..WELCOME', 'TO', 'PYTHON', 'PROGRAMMING..PYTHON', 'IS', 'A', 'OPEN',


'SOURCE', 'FREE',
'PROGRAMMING', 'LANGUAGE']

THE TOTAL NUMBER OF WORDS IN THE FILE <_io.TextIOWrapper name='myfile.txt'


mode='r' encoding='cp1252'> IS 12
FINDING THE NUMBER OF OCCURENCES OF A WORD

THE NUMBER OF OCCURENCES OF THE WORD PYTHON IN THE FILE


<_io.TextIOWrapper name='myfile.txt' mode='r' encoding='cp1252'> is 2
FINDING THE LONGEST WORD IN THE FILE

THE WORDS IN THE FILE ARE ['HI', 'HELLO..WELCOME', 'TO',


'PYTHON', 'PROGRAMMING..PYTHON',
'IS', 'A', 'OPEN', 'SOURCE', 'FREE', 'PROGRAMMING',
'LANGUAGE'] THE LONGEST WORD LENGTH IS 19
THE LONGEST WORD IS PROGRAMMING..PYTHON

RESULT
The python file handling operations is executed successfully.
EX 10a PYTHON EXCEPTION HANDLING IN REAL TIME APPLICATIONS

AIM:

To implement python exception handling in real time applications

ALGORITHM

1. Start the program


2. Use try block to catch the exception. Inside the try
block Get the inputs a,b from the user
Divide
c=a/b
In case of b being 0, the except block catches the exception using Exception class
object e. Print the exception
3. If no exception occurs, the else statement runs.
4. Stop the program

PROGRAM

try:
a = int(input("Enter a:")) b =
int(input("Enter b:")) c = a/b
print("a/b =",c)
# Using exception object with the except statement except
Exception as e:
print("user defined exception statemt: can't divide by zero")
print("SYSTEM CATCHING EXCEPTION",e)
else:
print("Hi I am else block")

OUTPUT

Enter a:12
Enter b:0
user defined exception statemt: can't divide by
zero SYSTEM CATCHING EXCEPTION
division by zero

RESULT
Python program to handle Divide by zero error is executed successful.
EX 10b PYTHON EXCEPTION HANDLING VOTER’S AGE ELIGIBILITY EXCEPTION

AIM:

To implement a python exception handling program for voter’s age eligibility in voting.

ALGORITHM

1. Start the program


2. Get the year of birth from user and calculate the age by current year-year of birth inside the
try block.
3. Use If-else block to display voting eligibility or not.
4. Catch system defined exception in except value error in case of entering random or
unwanted values.
5. Print the exception and if no exception print the else block.
6. Stop the program.

PROGRAM

def main():
#single try statement can have multiple except statements. try:
from datetime import date current_year =
date.today().year
year_of_birth = int(input('Enter Year of Birth: '))
age = current_year - year_of_birth print("You
are",age, "years old") if age >=18:
print('You can Vote!')
else:
print('You cant Vote.')
except ValueError:
print("age must be a valid number")
except Exception as e:
print(e)
else:
print("Thank you, you have successfully checked the voting eligibility")
main()
OUTPUT
Enter Year of Birth:
lfjslfjsalfjs
age must be a valid number

RESULT
Python exception handling program for voter’s age eligibility in voting is executed
successfully.
EX 10C PYTHON EXCEPTION HANDLING FOR STUDENT MARK VALIDATION

AIM:

To implement a python exception handling program for student mark validation system

ALGORITHM

1. Start the program


2. Get the marks from student in a arrat inside the try block.
3. Find the average of the marks to find the percentage
4. If the percentage is >90, print grade as ‘A’
5. Elif, if the percentage is >80, print grade as ‘B’
6. Elif, if the percentage is >70, print grade as ‘C’
7. Elif, if the percentage is >60, print grade as ‘D’
8. Else , the grade is ‘F’.
9. Use catch block to catch the exception in case of null values or unwanted symbols entered
as mark value.
10. Display the result.
11. Stop.

PROGRAM

def marks_Validation ():

# Store marks of all the subjects


# in an array
marks = []
print("Enter marks for 5 subjects")
try:
for i in range(5):
m=int(input("enter mark"))
marks.append(m)
except:
print("Enter integer number alone...do check")
# Max marks will be 100 * number
# of subjects
max_marks = len(marks)* 100

# Initialize student's total


# marks to 0
total = 0
# Initialize student's grade
# marks to F
grade = 'F'
# Traverse though the marks array
# to find the sum.
for i in range(len(marks)):
total += marks[i]
# Calculate the percentage.
# Since all the marks are integer, percentage =
((total) /max_marks) * 100
# Nested if else
if (percentage >= 90):
grade = 'A'
else
: if (percentage >= 80 and
percentage <= 89) : grade
= 'B'

else :
if (percentage >= 60 and
percentage <= 79) : grade
= 'C'
else :
if (percentage >= 33 and
percentage <= 59) : grade
= 'D'

else:
grade = 'F'

print("The Student Grade is:",grade)


marks_Validation()

OUTPUT:
Enter marks for 5 subjects enter
mark
@
Enter integer number alone...do check
Traceback (most recent call last):
File "Untitled2.py", line 56, in <module>
marks_Validation()
File "Untitled2.py", line 31, in marks_Validation percentage =
((total) /max_marks) * 100
ZeroDivisionError: division by zero

** Process exited - Return Code: 1 ** Press Enter


to exit terminal

RESULT
Python exception handling program for student mark validation system is executed
successfully.
EX.NO.11 BOUNCING BALL USING PYGAME

AIM:

To develop a bouncing ball game in python using pygame module.

ALGORITHM:

1. Set screen size, background color using pygame.display.set_mode() function.


2. Change the caption of window using pygame.display.set_caption() function.
3. Load the moving object using pygame.image.load() method
4. Set the ball rectangle area boundary using get_rect()
5. Set speed of the moving object using move() method.
6. Create an infinite loop to make the ball move continuously and reverse the direction
of ball if it hits the edges.
7. Fill the background color using fill() method and blit the screen using blit() method
8. Make image visible using flip() method

PROGRAM

import sys, pygame


pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball3.jpg")
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]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT

RESULT

Thus a python to implement bouncing ball game using pygame module has been
executed successfully.
EX.NO.12 CAR RACING GAME USING PYGAME

AIM:
To develop a car racing game in python using pygame module.

ALGORITHM
1. Import the pygame module and call init() method to initialize it.
2. Set the logo image and change the title of the window
3. Set the background image and other car images.
4. Implement key operations for the player1
5. Set the movements of opponent cars
6. Set the boundary of player1
7. Blit the screen
8. Display the updated score

PROGRAM:
import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
screen = pygame.display.set_mode((798,600))
#changing title of the game window
pygame.display.set_caption('Racing Beast')
#changing the logo
logo = pygame.image.load('logo1.jpg')
pygame.display.set_icon(logo)
#defining our gameloop function
def gameloop():
#setting background image
bg = pygame.image.load('bg1.jpg')
# setting our player
maincar = pygame.image.load('player1.png')
maincarX = 350
maincarY = 495
maincarX_change = 0
maincarY_change = 0
#other cars
car1 = pygame.image.load('car1.jpg')
car1X = random.randint(178,490)
car1Y = 100
car2 = pygame.image.load('car2.jpg')
car2X = random.randint(178,490)
car2Y = 100
car3 = pygame.image.load('car3.jpg')
car3X = random.randint(178,490)
car3Y = 100
run = True

while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#checking if any key has been pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
maincarX_change += 5
if event.key == pygame.K_LEFT:
maincarX_change -= 5
if event.key == pygame.K_UP:
maincarY_change -= 5
if event.key == pygame.K_DOWN:
maincarY_change += 5
#checking if key has been lifted up
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
maincarX_change = 0
if event.key == pygame.K_LEFT:
maincarX_change = 0
if event.key == pygame.K_UP:
maincarY_change = 0
if event.key == pygame.K_DOWN:
maincarY_change = 0
#setting boundary for our main car
if maincarX < 178:
maincarX = 178
if maincarX > 490:
maincarX = 490
if maincarY < 0:
maincarY = 0
if maincarY > 495:
maincarY = 495
#CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE
screen.fill((0,0,0))
#displaying the background image
screen.blit(bg,(0,0))
#displaying our main car screen.blit(maincar,
(maincarX,maincarY)) #displaing other cars
screen.blit(car1,(car1X,car1Y))
screen.blit(car2,(car2X,car2Y))
screen.blit(car3,(car3X,car3Y))
#updating the values
maincarX += maincarX_change
maincarY +=maincarY_change
#movement of the enemies
car1Y += 10
car2Y += 10
car3Y += 10
#moving enemies infinitely
if car1Y > 670:
car1Y = -100
if car2Y > 670:
car2Y = -150
if car3Y > 670:
car3Y = -200
pygame.display.update()
gameloop()

OUTPUT:

RESULT

Thus a car racing game in python implement using pygame module has been executed
successfully.

You might also like