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

HS 1st Semester Problem Solving and Python Programming Laboratory - GE3171 - Lab Manual 2

Uploaded by

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

HS 1st Semester Problem Solving and Python Programming Laboratory - GE3171 - Lab Manual 2

Uploaded by

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

All 1st semester Subjects

Professional English - I - HS3152 – Click Here


Matrices and Calculus - MA3151 – Click Here
Engineering Physics - PH3151 – Click Here
Engineering Chemistry - CY3151 – Click Here
Problem Solving and Python Programming - GE3151 – Click Here
Problem Solving and Python Programming Laboratory - GE3171 – Click Here
Physics and Chemistry Laboratory - BS3171 – Click Here
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BE- Computer Science and Engineering

Anna University Regulation: 2021

GE3171- Problem Solving And Python Programming

Laboratory

I Year/I Semester

Lab Manual

Prepared By,

Mrs. S. Porkodi, AP/CSE

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY L T P C 0 0 4 2


COURSE 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
COURSE 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.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

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.)
Ex.No: 1a Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for Electricity Billing

Aim:

To calculate the electricity bill based on the difference between the current and previous readings.

Algorithm:

Start:Begin the flowchart.


Input:Receive the user inputs for Previous Reading, Current Reading, and Rate per Unit.
Calculate Units Consumed:Subtract the Previous Reading from the Current Reading to get the Units
Consumed.
Check for Negative Consumption:Use a decision box to check if Units Consumed is less than 0.
Yes: Display an error message ("Invalid Reading") and end the process.
No: Continue to the next step.
Calculate Bill Amount:Multiply the Units Consumed by the Rate per Unit to get the Bill Amount.
Display Bill Details:Output the Bill Amount.
End:End the flowchart.

Procedure:

Start the Process:Begin the electricity billing process.


Input Data:Take the user inputs for Previous Reading, Current Reading, and Rate per Unit.
Calculate Units Consumed:Subtract Previous Reading from Current Reading to find the Units Consumed.
Check for Errors:Verify if the Units Consumed is non-negative.
If negative, display an error message.
If non-negative, proceed to the next step.
Calculate Bill Amount:Multiply Units Consumed by Rate per Unit to calculate the Bill Amount.
Display Results:Output the calculated Bill Amount.
End the Process:Terminate the electricity billing process.

FlowChart:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Result:
Thus the above flowchart was developed and output was verified successfully.

Ex.No: 1b Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for Retail shop billing

Aim: To Compute the total cost of items based on the unit price and quantity for retail shop billing.

Procedure:
Start:Begin the retail shop billing process.
Input Data:Obtain the item price and quantity for each product.
Calculate Total Cost for Each Item:Multiply the item price by the quantity to calculate the total cost for each
item.
Accumulate Total Costs:Sum up the total costs of all items to find the overall cost.
Display Result:Output the total cost of items.
End:Terminate the retail shop billing process.

Algorithm:
Start:Begin the retail shop billing algorithm.
Input Data:Obtain the item price and quantity for each product.
Initialize Total Cost:Set the total cost variable to zero.
For Each Item:For every item, perform the following steps:
a. Input Item Price
b. Input Quantity
c. Calculate Total Cost for the Item: Total Cost = Item Price * Quantity
d. Accumulate Total Cost: Total Cost = Total Cost + (Item Price * Quantity)
Display Result:Output the accumulated total cost.
End:Terminate the retail shop billing algorithm.

Flowchart:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Result:

Thus the above flowchart was developed and output was verified successfully.

Ex.No: 1c Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for Sin series

Aim:

To Generate a sine series up to a specified number of terms.

Algorithm:

Start:Begin the sine series algorithm.


Input Data:Obtain the number of terms (n) for the sine series.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Initialize Variables:Set variables x (angle in radians), term, sum, and i to zero.


For Each Term:For every term from 0 to n-1, perform the following steps:
a. Calculate the value of term: term = x^i / i!
b. Accumulate term to sum: sum = sum + term
c. Increment i by 2.
Display Result:Output the final sum as the result of the sine series.
End:Terminate the sine series algorithm.

Flowchart:

Result:

Thus the above flowchart was developed and output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 1d Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for weight of a motorbike

Aim:

To Calculate the total weight of a motorbike, including the weight of the frame, engine, and other
components.

Algorithm:

Start:Begin the algorithm to calculate the weight of a motorbike.


Input Data:Obtain the weights of the frame, engine, and other components.
Calculate Total Weight:Add up the weights of the frame, engine, and other components to get the total
weight of the motorbike.
Display Result:Output the calculated total weight of the motorbike.
End:Terminate the algorithm.

Flowchart:

Result:

Thus the above flowchart was developed and output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 1e Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for weight of a steel bar

Aim:

To Calculate the weight of a steel bar based on its dimensions and density.

Algorithm:

Start:Begin the algorithm to calculate the weight of a steel bar.


Input Data:Obtain the length, width, height (or diameter), and density of the steel bar.
Calculate Volume:

For a rectangular bar: Volume = Length * Width * Height


For a cylindrical bar: Volume = π * (Diameter/2)^2 * Height
Calculate Weight:

Weight = Volume * Density


Display Result:Output the calculated weight of the steel bar.
End:Terminate the algorithm.

Flowchart: Start

Stop

Result:

Thus the above flowchart was developed and output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 1f Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for compute Electrical Current in Three Phase AC Circuit

Aim:

To Calculate the electrical current in a three-phase AC circuit using the given parameters.

Algorithm:

Start:Begin the algorithm to compute electrical current in a three-phase AC circuit.


Input Data:Obtain the line voltage (V), power factor (PF), and power (P).
Calculate Apparent Power (S):
S = P / PF
Calculate Current (I):
I = S / (√3 * V)
Display Result:Output the calculated electrical current (I).
End:Terminate the algorithm.

Flowchart:

Result:

Thus the above flowchart was developed and output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).

Ex.No: 2a Python programming using simple statements and expressions to exchange the
values of two variables

Aim:

Exchange the values of two variables using a Python program.


Algorithm:

Start:Begin the algorithm to exchange the values of two variables.


Input Data:Obtain the values of two variables, let's say variable1 and variable2.
Exchange Values:Use a temporary variable to store the value of variable1.
Assign the value of variable2 to variable1.
Assign the value stored in the temporary variable to variable2.
Display Result:Output the values of the variables after the exchange.
End:Terminate the algorithm.
Program:

# Input: Obtain the values of two variables


variable1 = int(input("Enter the value of Variable 1: "))
variable2 = int(input("Enter the value of Variable 2: "))

# Display the original values


print("\nOriginal values:")
print("Variable 1:", variable1)
print("Variable 2:", variable2)

# Exchange the values using a temporary variable


temp = variable1
variable1 = variable2
variable2 = temp

# Display the values after the exchange


print("\nValues after exchange:")
print("Variable 1:", variable1)
print("Variable 2:", variable2)
Output:
>>>
Original values:
Variable 1: 2
Variable 2: 3

Values after exchange:


Variable 1: 3
Variable 2: 2
>>>
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 2b Python programming using simple statements and expressions to circulate the values
of n variables

Aim:
To Circulate the values of n variables in a circular manner using a Python program.
Algorithm:
Start:Begin the algorithm to circulate the values of n variables.
Input Data:Obtain the values of n variables (e.g., variable1, variable2, ..., variablen).
Circulate Values:Use a circular shifting approach to move the values to the next variable in a circular order.
Display Result:Output the values of variables after the circulation.
End:Terminate the algorithm.
Program:

# Input: Obtain the values of n variables


n = int(input("Enter the number of variables: "))
variables = [int(input(f"Enter the value of Variable {i + 1}: ")) for i in range(n)]

# Display the original values


print("\nOriginal values:")
for i in range(n):
print(f"Variable {i + 1}: {variables[i]}")

# Circulate the values in a circular manner


temp = variables[-1]
for i in range(n - 1, 0, -1):
variables[i] = variables[i - 1]
variables[0] = temp

# Display the values after circulation


print("\nValues after circulation:")
for i in range(n):
print(f"Variable {i + 1}: {variables[i]}")

Output:

Enter the number of variables: 3


Enter the value of Variable 1: 2
Enter the value of Variable 2: 3
Enter the value of Variable 3: 4
Original values:
Variable 1: 2
Variable 2: 3
Variable 3: 4

Values after circulation:


Variable 1: 4
Variable 2: 2
Variable 3: 3
>>>
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 2c Python programming using simple statements and expressions to distance between
two points

Aim:

To Calculate the distance between two points (x1, y1) and (x2, y2) in a two-dimensional space.

Algorithm:

Start:Begin the algorithm to calculate the distance between two points.


Input Data:
Obtain the coordinates (x1, y1) and (x2, y2) for the two points.
Calculate Distance:

Use the distance formula: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)


Display Result:Output the calculated distance.
End:Terminate the algorithm.

Program:

import math

# Input: Obtain the coordinates of two points


x1, y1 = map(float, input("Enter the coordinates of Point 1 (x1 y1): ").split())
x2, y2 = map(float, input("Enter the coordinates of Point 2 (x2 y2): ").split())

# Calculate the distance using the distance formula


distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

# Display the result


print(f"\nDistance between Point 1 and Point 2: {distance}")

Output:

Enter the coordinates of Point 1 (x1 y1): 1 3


Enter the coordinates of Point 2 (x2 y2): 4 5
Distance between Point 1 and Point 2: 3.605551275463989
>>>

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
Ex.No: 3a Scientific problems using Conditionals and Iterative loops for Number series

Aim:
To Generate a number series and use conditionals and iterative loops to perform certain operations on the
elements of the series.

Algorithm:
Start:Begin the algorithm to work with a number series.
Input Data:
Obtain the length of the series and generate the series.
Iterate Over the Series:

Use a loop to iterate over the elements of the series.


Conditionals and Operations:
For each element in the series, apply conditionals (e.g., check if the number is even or odd) and perform
operations accordingly.
Display Result:Output the processed series.
End:Terminate the algorithm.
Program:
# Input: Obtain the length of the series
n = int(input("Enter the length of the series: "))

# Generate the number series


number_series = list(range(1, n + 1))

# Display the original series


print("\nOriginal Number Series:", number_series)

# Iterate over the series and perform operations


for num in number_series:
# Check if the number is even or odd
if num % 2 == 0:
print(f"Square of {num}: {num**2}")
else:
print(f"Cube of {num}: {num**3}")

# End of the program


print("\nEnd of the program.")
Output:
Enter the length of the series: 4
Original Number Series: [1, 2, 3, 4]
Cube of 1: 1
Square of 2: 4
Cube of 3: 27
Square of 4: 16
End of the program.
>>>
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 3b Scientific problems using Conditionals and Iterative loops for Number Patterns

Aim:
To Generate a number pattern using conditionals and iterative loops.

Algorithm:
Start:

Begin the algorithm to generate a number pattern.


Input Data:Obtain the number of rows for the pattern.
Iterate Over Rows:Use a loop to iterate over each row.
Iterate Within Each Row:Within each row, use another loop to iterate over the columns.
Conditionals and Display:Apply conditionals to determine the numbers to be displayed based on the row and
column indices.
Display Result:Output the generated number pattern.
End:Terminate the algorithm.
Program:

# Input: Obtain the number of rows for the pattern


rows = int(input("Enter the number of rows for the pattern: "))

# Generate and display the number pattern


for i in range(1, rows + 1):
for j in range(1, i + 1):
# Apply conditionals to determine the numbers
if (i + j) % 2 == 0:
print("1", end=" ")
else:
print("0", end=" ")
print() # Move to the next line for the next row

# End of the program


print("\nEnd of the program.")

Output:

Enter the number of rows for the pattern: 6


1
01
101
0101
10101
010101

End of the program.


>>>
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 3c Scientific problems using Conditionals and Iterative loops for pyramid pattern

Aim:
To Generate a pyramid pattern using conditionals and iterative loops.
Algorithm:
Start:Begin the algorithm to generate a pyramid pattern.
Input Data:Obtain the number of rows for the pyramid.
Iterate Over Rows:Use a loop to iterate over each row.
Iterate Within Each Row:Within each row, use another loop to iterate over the columns.
Conditionals and Display:Apply conditionals to determine the characters to be displayed based on the row
and column indices.
Display Result:Output the generated pyramid pattern.
End:Terminate the algorithm.

Program:
# Input: Obtain the number of rows for the pyramid
rows = int(input("Enter the number of rows for the pyramid: "))

# Generate and display the pyramid pattern


for i in range(1, rows + 1):
# Print spaces before the numbers
for j in range(rows - i):
print(" ", end=" ")

# Print ascending numbers


for k in range(1, i + 1):
print(k, end=" ")

# Print descending numbers


for l in range(i - 1, 0, -1):
print(l, end=" ")

# Move to the next line for the next row


print()

# End of the program


print("\nEnd of the program.")

Output:
Enter the number of rows for the pyramid: 6
1
121
12321
1234321
123454321
12345654321
End of the program.
>>>
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

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)

Ex.No: 4a Implementing real-time/technical applications using Lists, Tuples. (Items present in


a library)

Aim:

To Implement a library application using Lists and Tuples to manage information about books.

Algorithm:

Start:Begin the algorithm for the library application.


Initialize Library:Create an empty list to represent the library.
Menu:Display a menu with options for users to Add a book, View all books, or Exit.
Add a Book:Accept user input for book details (Title, Author, Year), create a tuple, and append it to the
library list.
View all Books:Iterate over the library list and display information about each book.
Exit:Terminate the program.
End:End the algorithm.

Program:

def add_book(library):
title = input("Enter the title of the book: ")
author = input("Enter the author of the book: ")
year = int(input("Enter the publication year of the book: "))

book = (title, author, year)


library.append(book)
print(f"Book '{title}' added successfully!\n")

def view_books(library):
if not library:
print("Library is empty. No books to display.\n")
return

print("\nLibrary Books:")
for index, book in enumerate(library, start=1):
print(f"{index}. Title: {book[0]}, Author: {book[1]}, Year: {book[2]}")
print()

def main():
library = []

while True:
print("Library Management System")
print("1. Add a Book")

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print("2. View all Books")


print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
add_book(library)
elif choice == '2':
view_books(library)
elif choice == '3':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.\n")

if __name__ == "__main__":
main()

Output:

Library Management System


1. Add a Book
2. View all Books
3. Exit
Enter your choice (1/2/3): 1
Enter the title of the book: python
Enter the author of the book: porkodi
Enter the publication year of the book: 2023
Book 'python' added successfully!

Library Management System


1. Add a Book
2. View all Books
3. Exit
Enter your choice (1/2/3): 2
Library Books:
1. Title: python, Author: porkodi, Year: 2023

Library Management System


1. Add a Book
2. View all Books
3. Exit
Enter your choice (1/2/3): 3
Exiting the program. Goodbye!
>>>

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 4b Implementing real-time/technical applications using Lists, Tuples. (Materials


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

Aim:

To Implement a car component management application using Lists and Tuples to store information about
various components of a car.

Algorithm:
Start:Begin the algorithm for the car component management application.
Initialize Components:Create a list to represent the components of a car.
Menu:Display a menu with options for users to Add a component, View all components, or Exit.
Add a Component:Accept user input for component details (Name, Manufacturer, Price), create a tuple, and
append it to the components list.
View all Components:Iterate over the components list and display information about each component.
Exit:Terminate the program.
End:End the algorithm.

Program:

def add_component(components):
name = input(“Enter the name of the component: “)
manufacturer = input(“Enter the manufacturer of the component: “)
price = float(input(“Enter the price of the component: “))

component = (name, manufacturer, price)


components.append(component)
print(f”Component ‘{name}’ added successfully!\n”)

def view_components(components):
if not components:
print(“No components to display.\n”)
return

print(“\nCar Components:”)
for index, component in enumerate(components, start=1):
print(f”{index}. Name: {component[0]}, Manufacturer: {component[1]}, Price: ${component[2]:.2f}”)
print()

def main():
components = []

while True:
print(“Car Component Management System”)
print(“1. Add a Component”)
print(“2. View all Components”)
print(“3. Exit”)

choice = input(“Enter your choice (1/2/3): “)

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

if choice == ‘1’:
add_component(components)
elif choice == ‘2’:
view_components(components)
elif choice == ‘3’:
print(“Exiting the program. Goodbye!”)
break
else:
print(“Invalid choice. Please enter 1, 2, or 3.\n”)

if __name__ == “__main__”:
main()

OUTPUT:

Car Component Management System


1. Add a Component
2. View all Components
3. Exit
Enter your choice (1/2/3): 2
No components to display.

Car Component Management System


1. Add a Component
2. View all Components
3. Exit
Enter your choice (1/2/3): 1
Enter the name of the component: battery
Enter the manufacturer of the component: dulux
Enter the price of the component: 1340
Component ‘battery’ added successfully!

Car Component Management System


1. Add a Component
2. View all Components
3. Exit
Enter your choice (1/2/3): 2
Car Components:
3. Name: battery, Manufacturer: dulux, Price: $1340.00

Car Component Management System


1. Add a Component
2. View all Components
3. Exit
Enter your choice (1/2/3):

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 4c Implementing real-time/technical applications using Lists, Tuples. (Items present in


a Components of a car)

Aim:

To Implement a construction materials management application using Lists and Tuples to store information
about various materials.

Algorithm:

Start:Begin the algorithm for the construction materials management application.


Initialize Materials:Create a list to represent the materials required for building construction.
Menu:Display a menu with options for users to Add a material, View all materials, or Exit.
Add a Material:Accept user input for material details (Name, Quantity, Unit), create a tuple, and append it to
the materials list.
View all Materials:Iterate over the materials list and display information about each material.
Exit:Terminate the program.
End:End the algorithm.

Program:

def add_material(materials):
name = input("Enter the name of the material: ")
quantity = float(input("Enter the quantity of the material: "))
unit = input("Enter the unit of the material: ")

material = (name, quantity, unit)


materials.append(material)
print(f"Material '{name}' added successfully!\n")

def view_materials(materials):
if not materials:
print("No materials to display.\n")
return

print("\nConstruction Materials:")
for index, material in enumerate(materials, start=1):
print(f"{index}. Name: {material[0]}, Quantity: {material[1]} {material[2]}")
print()

def main():
materials = []

while True:
print("Construction Materials Management System")
print("1. Add a Material")
print("2. View all Materials")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

if choice == '1':
add_material(materials)
elif choice == '2':
view_materials(materials)
elif choice == '3':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.\n")

if __name__ == "__main__":
main()

Output:
Construction Materials Management System
1. Add a Material
2. View all Materials
3. Exit
Enter your choice (1/2/3): 1
Enter the name of the material: Brick
Enter the quantity of the material: 2000
Enter the unit of the material: 20
Material 'Brick' added successfully!

Construction Materials Management System


1. Add a Material
2. View all Materials
3. Exit
Enter your choice (1/2/3): 1
Enter the name of the material: Sand
Enter the quantity of the material: 25
Enter the unit of the material: 23
Material 'Sand' added successfully!

Construction Materials Management System


1. Add a Material
2. View all Materials
3. Exit
Enter your choice (1/2/3): 3
Exiting the program. Goodbye!
>>>

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

5. Implementing real-time/technical applications using Sets, Dictionaries. (Language, components of


an automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries)

Ex.No: 5a Implementing real-time/technical applications using Sets, Dictionaries. (Language)

Aim:

To Implement a programming language management application using Sets and Dictionaries to store
information about various languages.

Algorithm:

Start:Begin the algorithm for the programming language management application.


Initialize Languages:Create a set to represent the programming languages.
Initialize Language Information:Create a dictionary to store additional information about each programming
language, such as the year of creation and the creator.
Menu:Display a menu with options for users to Add a language, View all languages, Search for a language,
or Exit.
Add a Language:Accept user input for language details (Name, Year of Creation, Creator), add the language
to the set, and update the dictionary with additional information.
View all Languages:Iterate over the set of languages and display information about each language using the
dictionary.
Search for a Language:Accept user input for a language name and display information about that language if
it exists in the set.
Exit:Terminate the program.
End:End the algorithm.

Program:

def add_language(languages, language_info):


name = input("Enter the name of the language: ")
year = int(input("Enter the year of creation: "))
creator = input("Enter the creator of the language: ")

languages.add(name)
language_info[name] = {'Year': year, 'Creator': creator}
print(f"Language '{name}' added successfully!\n")

def view_languages(languages, language_info):


if not languages:
print("No languages to display.\n")
return

print("\nProgramming Languages:")
for index, language in enumerate(languages, start=1):
print(f"{index}. Name: {language}, Year: {language_info[language]['Year']}, Creator:
{language_info[language]['Creator']}")
print()

def search_language(languages, language_info):


if not languages:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print("No languages to search. Add languages first.\n")


return

search_name = input("Enter the name of the language to search: ")


if search_name in languages:
print(f"\nLanguage Found:")
print(f"Name: {search_name}, Year: {language_info[search_name]['Year']}, Creator:
{language_info[search_name]['Creator']}")
else:
print(f"\nLanguage '{search_name}' not found.\n")

def main():
languages = set()
language_info = {}

while True:
print("Programming Language Management System")
print("1. Add a Language")
print("2. View all Languages")
print("3. Search for a Language")
print("4. Exit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
add_language(languages, language_info)
elif choice == '2':
view_languages(languages, language_info)
elif choice == '3':
search_language(languages, language_info)
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, or 4.\n")

if __name__ == "__main__":
main()

Output:

Programming Language Management System


1. Add a Language
2. View all Languages
3. Search for a Language
4. Exit

Enter your choice (1/2/3/4): 1


Enter the name of the language: Python
Enter the year of creation: 1991
Enter the creator of the language: Guido van Rossum

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Language 'Python' added successfully!

Programming Language Management System


1. Add a Language
2. View all Languages
3. Search for a Language
4. Exit

Enter your choice (1/2/3/4): 2

Programming Languages:
1. Name: Python, Year: 1991, Creator: Guido van Rossum

Programming Language Management System


1. Add a Language
2. View all Languages
3. Search for a Language
4. Exit

Enter your choice (1/2/3/4): 3


Enter the name of the language to search: Java

Language 'Java' not found.

Programming Language Management System


1. Add a Language
2. View all Languages
3. Search for a Language
4. Exit

Enter your choice (1/2/3/4): 4


Exiting the program. Goodbye!

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 5b Implementing real-time/technical applications using Sets, Dictionaries. (components


of an automobile)

Aim:

To Implement an automobile component management application using Sets and Dictionaries to store
information about various components.

Algorithm:

Start:Begin the algorithm for the automobile component management application.


Initialize Components:Create a set to represent the components of an automobile.
Initialize Component Information:Create a dictionary to store additional information about each component,
such as the manufacturer and price.
Menu:Display a menu with options for users to Add a component, View all components, Search for a
component, or Exit.
Add a Component:
Accept user input for component details (Name, Manufacturer, Price), add the component to the set, and
update the dictionary with additional information.
View all Components:
Iterate over the set of components and display information about each component using the dictionary.
Search for a Component:

Accept user input for a component name and display information about that component if it exists in the set.
Exit:Terminate the program.
End:End the algorithm.

Program:

def add_component(components, component_info):


name = input("Enter the name of the component: ")
manufacturer = input("Enter the manufacturer of the component: ")
price = float(input("Enter the price of the component: "))

components.add(name)
component_info[name] = {'Manufacturer': manufacturer, 'Price': price}
print(f"Component '{name}' added successfully!\n")

def view_components(components, component_info):


if not components:
print("No components to display.\n")
return

print("\nAutomobile Components:")
for index, component in enumerate(components, start=1):
print(f"{index}. Name: {component}, Manufacturer: {component_info[component]['Manufacturer']},
Price: ${component_info[component]['Price']:.2f}")
print()

def search_component(components, component_info):


if not components:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print("No components to search. Add components first.\n")


return

search_name = input("Enter the name of the component to search: ")


if search_name in components:
print(f"\nComponent Found:")
print(f"Name: {search_name}, Manufacturer: {component_info[search_name]['Manufacturer']}, Price:
${component_info[search_name]['Price']:.2f}")
else:
print(f"\nComponent '{search_name}' not found.\n")

def main():
components = set()
component_info = {}

while True:
print("Automobile Component Management System")
print("1. Add a Component")
print("2. View all Components")
print("3. Search for a Component")
print("4. Exit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
add_component(components, component_info)
elif choice == '2':
view_components(components, component_info)
elif choice == '3':
search_component(components, component_info)
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, or 4.\n")

if __name__ == "__main__":
main()

Output:

Automobile Component Management System


1. Add a Component
2. View all Components
3. Search for a Component
4. Exit

Enter your choice (1/2/3/4): 1


Enter the name of the component: Engine
Enter the manufacturer of the component: ABC Motors
Enter the price of the component: 2500.00

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Component 'Engine' added successfully!

Automobile Component Management System


1. Add a Component
2. View all Components
3. Search for a Component
4. Exit

Enter your choice (1/2/3/4): 2

Automobile Components:
1. Name: Engine, Manufacturer: ABC Motors, Price: $2500.00

Automobile Component Management System


1. Add a Component
2. View all Components
3. Search for a Component
4. Exit

Enter your choice (1/2/3/4): 3


Enter the name of the component to search: Transmission

Component 'Transmission' not found.

Automobile Component Management System


1. Add a Component
2. View all Components
3. Search for a Component
4. Exit

Enter your choice (1/2/3/4): 4


Exiting the program. Goodbye!

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 5c Implementing real-time/technical applications using Sets, Dictionaries. (Elements of


a civil structure)

Aim:

Implement a civil structure element management application using Sets and Dictionaries to store information
about various elements.

Algorithm:

Start:Begin the algorithm for the civil structure element management application.
Initialize Elements:Create a set to represent the elements of a civil structure.
Initialize Element Information:

Create a dictionary to store additional information about each element, such as the material and height.
Menu:
Display a menu with options for users to Add an element, View all elements, Search for an element, or Exit.
Add an Element:

Accept user input for element details (Name, Material, Height), add the element to the set, and update the
dictionary with additional information.
View all Elements:
Iterate over the set of elements and display information about each element using the dictionary.
Search for an Element:

Accept user input for an element name and display information about that element if it exists in the set.
Exit:

Terminate the program.


End:End the algorithm.

Program:

def add_element(elements, element_info):


name = input("Enter the name of the element: ")
material = input("Enter the material of the element: ")
height = float(input("Enter the height of the element (in meters): "))

elements.add(name)
element_info[name] = {'Material': material, 'Height': height}
print(f"Element '{name}' added successfully!\n")

def view_elements(elements, element_info):


if not elements:
print("No elements to display.\n")
return

print("\nCivil Structure Elements:")


for index, element in enumerate(elements, start=1):
print(f"{index}. Name: {element}, Material: {element_info[element]['Material']}, Height:
{element_info[element]['Height']} meters")

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print()

def search_element(elements, element_info):


if not elements:
print("No elements to search. Add elements first.\n")
return

search_name = input("Enter the name of the element to search: ")


if search_name in elements:
print(f"\nElement Found:")
print(f"Name: {search_name}, Material: {element_info[search_name]['Material']}, Height:
{element_info[search_name]['Height']} meters")
else:
print(f"\nElement '{search_name}' not found.\n")

def main():
elements = set()
element_info = {}

while True:
print("Civil Structure Element Management System")
print("1. Add an Element")
print("2. View all Elements")
print("3. Search for an Element")
print("4. Exit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
add_element(elements, element_info)
elif choice == '2':
view_elements(elements, element_info)
elif choice == '3':
search_element(elements, element_info)
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, or 4.\n")

if __name__ == "__main__":
main()

Output:

Civil Structure Element Management System


1. Add an Element
2. View all Elements
3. Search for an Element
4. Exit

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Enter your choice (1/2/3/4): 1


Enter the name of the element: Column
Enter the material of the element: Concrete
Enter the height of the element (in meters): 3.5
Element 'Column' added successfully!

Civil Structure Element Management System


1. Add an Element
2. View all Elements
3. Search for an Element
4. Exit

Enter your choice (1/2/3/4): 2

Civil Structure Elements:


1. Name: Column, Material: Concrete, Height: 3.5 meters

Civil Structure Element Management System


1. Add an Element
2. View all Elements
3. Search for an Element
4. Exit

Enter your choice (1/2/3/4): 3


Enter the name of the element to search: Beam

Element 'Beam' not found.

Civil Structure Element Management System


1. Add an Element
2. View all Elements
3. Search for an Element
4. Exit

Enter your choice (1/2/3/4): 4


Exiting the program. Goodbye!

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)

Ex.No: 6a Implementing programs using Functions. (Factorial)

Aim:
To Implement a Python program using functions to calculate the factorial of a given number.

Algorithm:
Start:Begin the algorithm for the factorial calculation program.
Input:
Accept user input for the number for which the factorial needs to be calculated.
Function Definition - factorial:
Define a function called factorial that takes a parameter n.
Initialize Result:

Initialize a variable result to store the factorial result and set it to 1.


Calculate Factorial:

Use a loop to calculate the factorial by multiplying the result with each number from 1 to n.
Output Result:

Display the calculated factorial.


End:End the algorithm.
Program:

def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

def main():
# Input: Accept user input for the number
number = int(input("Enter a non-negative integer to calculate its factorial: "))

# Calculate factorial using the factorial function


result = factorial(number)

# Output Result
print(f"The factorial of {number} is: {result}")

if __name__ == "__main__":
main()
Output:
Enter a non-negative integer to calculate its factorial: 5
The factorial of 5 is: 120

Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 6b Implementing programs using Functions. (largest number in a list)

Aim:
To Implement a Python program using functions to find the largest number in a given list.
Algorithm:
Start:
Begin the algorithm for the program to find the largest number in a list.
Input:
Accept user input or define a list of numbers.
Function Definition - find_largest:
Define a function called find_largest that takes a list as a parameter.
Initialize Largest:
Initialize a variable largest to store the largest number and set it to the first element of the list.
Find Largest:
Use a loop to iterate through the list and update the largest variable if a larger number is found.
Output Result:Display the largest number.
End:End the algorithm.

PROGRAM:
def find_largest(numbers):
if not numbers:
return None # Return None if the list is empty

largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest

def main():
# Input: Accept user input or define a list of numbers
num_list = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]

# Find the largest number using the find_largest function


result = find_largest(num_list)

# Output Result
if result is not None:
print(f"The largest number in the list is: {result}")
else:
print("The list is empty.")

if __name__ == "__main__":
main()

OUTPUT:

Enter a list of numbers separated by spaces: 12 45 8 23 67 34


The largest number in the list is: 67
Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 6c Implementing programs using Functions. (area of shape)

Aim:

To Implement a Python program using functions to calculate the area of different shapes (rectangle, circle,
triangle).

Algorithm:

Start:Begin the algorithm for the program to find the area of different shapes.
Function Definitions:
Define functions for calculating the area of a rectangle, circle, and triangle.
Input:Accept user input or define values for the dimensions of each shape.
Calculate Area Functions:
Implement the area calculation logic inside each function.
Output Result:
Display the calculated area for each shape.
End:End the algorithm.

PROGRAM:

import math

def area_rectangle(length, width):


return length * width

def area_circle(radius):
return math.pi * radius**2

def area_triangle(base, height):


return 0.5 * base * height

def main():
# Input: Accept user input or define values for dimensions
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

radius = float(input("Enter the radius of the circle: "))

base = float(input("Enter the base of the triangle: "))


height = float(input("Enter the height of the triangle: "))

# Calculate area using functions


area_rect = area_rectangle(length, width)
area_circ = area_circle(radius)
area_tri = area_triangle(base, height)

# Output Result
print(f"\nThe area of the rectangle is: {area_rect}")
print(f"The area of the circle is: {area_circ}")
print(f"The area of the triangle is: {area_tri}")

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

if __name__ == "__main__":
main()

OUTPUT:

Enter the length of the rectangle: 5


Enter the width of the rectangle: 8
Enter the radius of the circle: 4
Enter the base of the triangle: 6
Enter the height of the triangle: 10

The area of the rectangle is: 40.0


The area of the circle is: 50.26548245743669
The area of the triangle is: 30.0

Result:

Thus the above Python program was executed and the output was verified successfully.

7. Implementing programs using Strings. (reverse, palindrome, character count, replacing characters)

Ex.No: 7a Implementing programs using Strings. (reverse)

Aim:
Implement a Python program using strings to reverse a given string.

Algorithm:

Start:

Begin the algorithm for the program to reverse a string.


Input:

Accept user input for the string to be reversed.


Function Definition - reverse_string:

Define a function called reverse_string that takes a string as a parameter.


Initialize Reversed String:

Initialize a variable reversed_str to store the reversed string and set it to an empty string.
Reverse String:

Use string slicing to reverse the given string.


Output Result:

Display the reversed string.


End:

End the algorithm.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

PROGRAM:

def reverse_string(input_str):
return input_str[::-1]

def main():
# Input: Accept user input for the string
user_input = input("Enter a string to reverse: ")

# Reverse the string using the reverse_string function


reversed_str = reverse_string(user_input)

# Output Result
print(f"The reversed string is: {reversed_str}")

if __name__ == "__main__":
main()

OUTPUT:

Enter a string to reverse: Hello World!


The reversed string is: !dlroW olleH

Result:

Thus the above Python program was executed and the output was verified successfully.

Ex.No: 7b Implementing programs using Strings. (palindrome)

Aim:
To Implement a Python program using strings to check whether a given string is a palindrome.

Algorithm:

Start:

Begin the algorithm for the program to check whether a string is a palindrome.
Input:

Accept user input for the string to be checked.


Function Definition - is_palindrome:

Define a function called is_palindrome that takes a string as a parameter.


Remove Spaces and Convert to Lowercase:

Remove spaces from the input string and convert it to lowercase.


Compare Original and Reversed Strings:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Use string slicing to reverse the string, and then compare it with the original string.
Output Result:

Display whether the input string is a palindrome or not.


End:

End the algorithm.

PROGRAM:

def is_palindrome(input_str):
# Remove spaces and convert to lowercase
processed_str = input_str.replace(" ", "").lower()

# Compare original and reversed strings


return processed_str == processed_str[::-1]

def main():
# Input: Accept user input for the string
user_input = input("Enter a string to check if it's a palindrome: ")

# Check if the string is a palindrome using the is_palindrome function


result = is_palindrome(user_input)

# Output Result
if result:
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")

if __name__ == "__main__":
main()

OUTPUT:

Enter a string to check if it's a palindrome: A man a plan a canal Panama


The entered string is a palindrome.

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 7c Implementing programs using Strings. (character count)

Aim:

To Implement a Python program using strings to count the occurrences of each character in a given string.

Algorithm:

Start:

Begin the algorithm for the program to count character occurrences in a string.
Input:

Accept user input for the string.


Function Definition - count_characters:

Define a function called count_characters that takes a string as a parameter.


Initialize Counter Dictionary:

Initialize an empty dictionary to store character occurrences.


Count Characters:

Iterate through the string and update the counter dictionary.


Output Result:

Display the character count.


End:End the algorithm.

PROGRAM:

def count_characters(input_str):
# Initialize counter dictionary
char_count = {}

# Count characters
for char in input_str:
if char.isalpha(): # Consider only alphabetic characters
char_count[char] = char_count.get(char, 0) + 1

return char_count

def main():
# Input: Accept user input for the string
user_input = input("Enter a string to count character occurrences: ")

# Count character occurrences using the count_characters function


result = count_characters(user_input)

# Output Result
print("\nCharacter Occurrences:")
for char, count in result.items():

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print(f"{char}: {count}")

if __name__ == "__main__":
main()

OUTPUT:

Enter a string to count character occurrences: Hello, World!


Character Occurrences:
H: 1
e: 1
l: 3
o: 2
W: 1
r: 1
d: 1

Result:

Thus the above Python program was executed and the output was verified successfully.

Ex.No: 7d Implementing programs using Strings. (replacing characters)

Aim:
To Implement a Python program using strings to replace specific characters in a given string.

Algorithm:
Start:Begin the algorithm for the program to replace specific characters in a string.
Input:Accept user input for the string and the characters to be replaced.
Function Definition - replace_characters:Define a function called replace_characters that takes a string, old
character, and new character as parameters.
Replace Characters:Use the replace method to replace occurrences of the old character with the new
character in the string.
Output Result:Display the modified string.
End:End the algorithm.

PROGRAM:

def replace_characters(input_str, old_char, new_char):


# Replace characters in the string
modified_str = input_str.replace(old_char, new_char)
return modified_str

def main():
# Input: Accept user input for the string, old character, and new character
user_input = input("Enter a string: ")
old_character = input("Enter the character to be replaced: ")
new_character = input("Enter the replacement character: ")

# Replace characters using the replace_characters function


result = replace_characters(user_input, old_character, new_character)

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

# Output Result
print("\nModified String:")
print(result)

if __name__ == "__main__":
main()

OUTPUT

Enter a string: Hello, World!


Enter the character to be replaced: o
Enter the replacement character: @

Modified String:
Hell@, W@rld!

Result:

Thus the above Python program was executed and the output was verified successfully.

8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)

Ex.No: 8 Implementing programs using written modules and Python Standard Libraries (pandas,
numpy. Matplotlib, scipy)

Aim:
To Implement a Python program using pandas, numpy, matplotlib, and scipy to analyze and visualize sample
data.

Example Scenario:
Let's consider a scenario where we have a dataset containing information about sales data for different
products over a period of time. We'll use pandas for data manipulation, numpy for numerical operations,
matplotlib for data visualization, and scipy for statistical analysis.

Algorithm:
Start:Begin the algorithm for the program to analyze and visualize sample data.
Import Libraries:
Import the required libraries (pandas, numpy, matplotlib, scipy).
Load Sample Data:
Load a sample dataset into a pandas DataFrame.
Data Analysis:
Perform basic data analysis tasks, such as calculating summary statistics using numpy and pandas.
Data Visualization:
Create visualizations using matplotlib to understand the sales trends.
Statistical Analysis:
Use scipy for statistical analysis, such as hypothesis testing.
End:End the algorithm.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

PROGRAM:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind

def main():
# Load sample data into a pandas DataFrame
data = {
'Product': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
'Sales': [50, 30, 45, 25, 60, 35, 55, 28]
}
df = pd.DataFrame(data)

# Display the DataFrame


print("\nSample Data:")
print(df)

# Data Analysis
print("\nSummary Statistics:")
summary_stats = df.groupby('Product')['Sales'].describe()
print(summary_stats)

# Data Visualization
plt.figure(figsize=(8, 5))
plt.bar(df['Product'], df['Sales'], color=['blue', 'orange'])
plt.title('Product Sales Comparison')
plt.xlabel('Product')
plt.ylabel('Sales')
plt.show()

# Statistical Analysis
product_A_sales = df[df['Product'] == 'A']['Sales']
product_B_sales = df[df['Product'] == 'B']['Sales']

t_stat, p_value = ttest_ind(product_A_sales, product_B_sales)


print(f"\nStatistical Analysis (t-test):")
print(f"T-statistic: {t_stat}")
print(f"P-value: {p_value}")

if p_value < 0.05:


print("\nThe difference in sales between Product A and Product B is statistically significant.")
else:
print("\nNo significant difference in sales between Product A and Product B.")

if __name__ == "__main__":
main()

OUTPUT:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Sample Data:
Product Sales
0 A 50
1 B 30
2 A 45
3 B 25
4 A 60
5 B 35
6 A 55
7 B 28

Summary Statistics:
count mean std min 25% 50% 75% max
Product
A 4.0 52.50 6.454972 45.0 48.75 52.5 56.25 60.0
B 4.0 29.50 4.272002 25.0 27.25 29.0 31.25 35.0

Statistical Analysis (t-test):


T-statistic: 6.29514780968878
P-value: 0.00036289056972202045

The difference in sales between Product A and Product B is statistically significant.

Result:

Thus the above Python program was executed and the output was verified successfully.

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

Ex.No: 9 Implementing real-time/technical applications using File handling. (copy from one
file to another, word count, longest word)

Aim:

To Implement a Python program that performs file handling operations, including copying content from one
file to another, counting words in a file, and finding the longest word in a file.

Algorithm:

Start:Begin the algorithm for the file handling program.


Copy File:
Define a function copy_file that takes the source file and destination file paths as parameters.
Open the source file for reading and the destination file for writing.
Copy the content from the source file to the destination file.
Close both files.
Word Count:
Define a function word_count that takes the file path as a parameter.
Open the file for reading.
Read the content of the file and split it into words.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Count the number of words.


Close the file and return the word count.
Longest Word:

Define a function longest_word that takes the file path as a parameter.


Open the file for reading.
Read the content of the file and split it into words.
Find and return the longest word.
Close the file.
Main Function:

Define a main function.


Specify the source file and destination file paths.
Call the copy_file function to copy content from the source file to the destination file.
Call the word_count function to count words in the destination file.
Call the longest_word function to find the longest word in the destination file.
Print the word count and the longest word.
End:

End the algorithm.

PROGRAM:

def copy_file(source_file, destination_file):


try:
with open(source_file, 'r') as source:
with open(destination_file, 'w') as destination:
destination.write(source.read())
print(f"Content copied from {source_file} to {destination_file} successfully.")
except FileNotFoundError:
print("Error: One or both files not found.")

def word_count(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
words = content.split()
num_words = len(words)
return num_words
except FileNotFoundError:
print("Error: File not found.")
return 0

def longest_word(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
words = content.split()
longest = max(words, key=len)
return longest
except FileNotFoundError:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print("Error: File not found.")


return None

def main():
source_file = 'source.txt'
destination_file = 'destination.txt'

# Copy content from one file to another


copy_file(source_file, destination_file)

# Count words in a file


word_count_result = word_count(destination_file)
print(f"\nWord Count in {destination_file}: {word_count_result} words")

# Find the longest word in a file


longest_word_result = longest_word(destination_file)
if longest_word_result:
print(f"Longest Word in {destination_file}: {longest_word_result}")

if __name__ == "__main__":
main()

PROCEDURE:

When you run this program, it will copy the content from source.txt to destination.txt, count the words in
destination.txt, and find the longest word in destination.txt. Ensure you have source.txt with some content in
the same directory as the script.

OUTPUT:

Content copied from source.txt to destination.txt successfully.

Word Count in destination.txt: 20 words


Longest Word in destination.txt: successfully.

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)

Ex.No: 10a Implementing real-time/technical applications using Exception handling. (divide by


zero error)

Aim:

Implement a Python program that performs division and handles a potential divide by zero error using
exception handling.

Algorithm:
Start:

Begin the algorithm for the program with exception handling.


User Input:

Prompt the user to enter two numbers (numerator and denominator).


Exception Handling:

Use a try-except block to handle the potential divide by zero error.


Inside the try block, perform the division operation.
If a ZeroDivisionError occurs, catch the exception in the except block and handle it gracefully.
Output:

Print the result of the division if successful.


If a divide by zero error occurs, print an error message.
End:

End the algorithm.

PROGRAM:

def divide_numbers(numerator, denominator):


try:
result = numerator / denominator
return result
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
return None

def main():
# User Input
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))

# Division with Exception Handling


division_result = divide_numbers(numerator, denominator)

# Output
if division_result is not None:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

print(f"\nResult of {numerator} / {denominator} is: {division_result}")

if __name__ == "__main__":
main()

OUTPUT:

1.Normal division:
Enter the numerator: 10
Enter the denominator: 2

Result of 10.0 / 2.0 is: 5.0

2. Divide by zero error:


Enter the numerator: 8
Enter the denominator: 0

Error: Division by zero is not allowed.

Result:

Thus the above Python program was executed and the output was verified successfully.

Ex.No: 10b Implementing real-time/technical applications using Exception handling. (voter’s age
validity)

Aim:

To Implement a Python program that checks the validity of a voter's age, handling potential exceptions for
invalid input or age below the voting age.

Algorithm:

Start:Begin the algorithm for the program with exception handling.


User Input:

Prompt the user to enter their age.


Exception Handling:

Use a try-except block to handle potential exceptions.


Inside the try block, convert the user input to an integer and check the age validity.
If the age is below the voting age (e.g., 18), raise a custom exception.
If there is any other invalid input (e.g., non-numeric input), catch the exception in the except block and
handle it gracefully.
Output:

Print a message indicating whether the user is eligible to vote or not.


End:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

End the algorithm.

PROGRAM:

class InvalidAgeError(Exception):
pass

def check_voter_eligibility(age):
voting_age = 18

try:
age = int(age)
if age < voting_age:
raise InvalidAgeError("Error: You must be at least 18 years old to vote.")
else:
print("You are eligible to vote.")
except ValueError:
print("Error: Please enter a valid numeric age.")
except InvalidAgeError as e:
print(e)

def main():
# User Input
age_input = input("Enter your age: ")

# Check Voter Eligibility with Exception Handling


check_voter_eligibility(age_input)

if __name__ == "__main__":
main()

OUTPUT:

1.Valid Age

Enter your age: 25


You are eligible to vote.

2.Invalid Age(Below voting age)


Enter your age: 16
Error: You must be at least 18 years old to vote.

3.Invalid input
Enter your age: abc
Error: Please enter a valid numeric age.

Result:

Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Ex.No: 10c Implementing real-time/technical applications using Exception handling. (student


mark range validation)

Aim:

To Implement a Python program that checks the validity of student marks, handling potential exceptions for
invalid input or marks outside the valid range.

Algorithm:

Start:Begin the algorithm for the program with exception handling.


User Input:

Prompt the user to enter the student's marks.


Exception Handling:

Use a try-except block to handle potential exceptions.


Inside the try block, convert the user input to an integer and check the marks' validity.
If the marks are outside the valid range (e.g., below 0 or above 100), raise a custom exception.
If there is any other invalid input (e.g., non-numeric input), catch the exception in the except block and
handle it gracefully.
Output:

Print a message indicating whether the student's marks are valid or not.
End:

End the algorithm.

PROGRAM:

class InvalidMarksError(Exception):
pass

def validate_student_marks(marks):
valid_range = (0, 100)

try:
marks = int(marks)
if marks < valid_range[0] or marks > valid_range[1]:
raise InvalidMarksError("Error: Marks should be between 0 and 100.")
else:
print("Student marks are valid.")
except ValueError:
print("Error: Please enter valid numeric marks.")
except InvalidMarksError as e:
print(e)

def main():
# User Input
marks_input = input("Enter student marks: ")

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

# Validate Student Marks with Exception Handling


validate_student_marks(marks_input)

if __name__ == "__main__":
main()

OUTPUT:

Enter student marks: 85


Student marks are valid.

Enter student marks: 120


Error: Marks should be between 0 and 100.

Enter student marks: abc


Error: Please enter valid numeric marks.

Result:

Thus the above Python program was executed and the output was verified successfully.

Ex.No: 11 Exploring Pygame tool.

Aim:

To Explore Pygame and create a simple program that displays a window with a moving rectangle.

Algorithm:

Start:
Begin the algorithm for exploring Pygame.
Import Pygame:

Import the pygame module.


Initialize Pygame:

Initialize Pygame with pygame.init().


Create a Window:

Create a Pygame window using pygame.display.set_mode().


Set up Colors and Rectangles:

Define colors and create a rectangle using pygame.Rect().


Game Loop:

Implement a game loop that continuously updates the screen and handles events.
Inside the loop, move the rectangle based on user input or a predefined pattern.
Update Display:

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

Update the display using pygame.display.flip().


Event Handling:

Handle events, such as closing the window or user input, using pygame.event.get().
End:

End the algorithm.

PROGRAM:

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# Create a window
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame Exploration")

# Set up a rectangle
rect_width, rect_height = 50, 30
rect = pygame.Rect((width - rect_width) // 2, (height - rect_height) // 2, rect_width, rect_height)
rect_speed = 5

# Game Loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

# Move the rectangle based on arrow key input


keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
rect.x -= rect_speed
if keys[pygame.K_RIGHT]:
rect.x += rect_speed
if keys[pygame.K_UP]:
rect.y -= rect_speed
if keys[pygame.K_DOWN]:
rect.y += rect_speed

# Fill the screen with white


screen.fill(WHITE)

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

# Draw the rectangle


pygame.draw.rect(screen, BLACK, rect)

# Update the display


pygame.display.flip()

# Control the frame rate


pygame.time.Clock().tick(30)

Result:

Thus the above Python program was executed and the output was verified successfully.

12. Developing a game activity using Pygame like bouncing ball, car race etc.
Ex.No: 12 Developing a game activity using Pygame like bouncing ball, car race etc.

Aim:

The aim of the game is to control a paddle using keyboard input and bounce a ball off the paddle to prevent
it from falling off the screen. The player scores points by keeping the ball in play.

Algorithms:

Ball Movement:

Initialize the ball's position and velocity.


Update the ball's position based on its velocity.
Bounce the ball off the walls and the paddle.
Paddle Movement:

Initialize the paddle's position.


Listen for keyboard input to move the paddle left or right.
Update the paddle's position based on input.
Collision Detection:

Check for collisions between the ball and the walls, as well as the paddle.
If the ball hits the paddle, bounce it upward. If it falls off the screen, end the game.
Scoring:

Keep track of the score based on the time the ball is kept in play.

PROGRAM:

import pygame
import sys

# Initialize Pygame

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

pygame.init()

# Constants
WIDTH, HEIGHT = 800, 600
BALL_RADIUS = 20
PADDLE_WIDTH, PADDLE_HEIGHT = 100, 20
FPS = 60

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# Set up the display


screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Ball Game")

# Set up the clock


clock = pygame.time.Clock()

# Ball properties
ball_x = WIDTH // 2
ball_y = HEIGHT // 2
ball_speed_x = 5
ball_speed_y = 5

# Paddle properties
paddle_x = (WIDTH - PADDLE_WIDTH) // 2
paddle_y = HEIGHT - PADDLE_HEIGHT - 10
paddle_speed = 10

# Game variables
score = 0

# Main game loop


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

# Ball movement
ball_x += ball_speed_x
ball_y += ball_speed_y

# Bounce off the walls


if ball_x - BALL_RADIUS < 0 or ball_x + BALL_RADIUS > WIDTH:
ball_speed_x = -ball_speed_x

if ball_y - BALL_RADIUS < 0:


ball_speed_y = -ball_speed_y

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi

# Bounce off the paddle


if (
paddle_x < ball_x < paddle_x + PADDLE_WIDTH
and paddle_y < ball_y < paddle_y + PADDLE_HEIGHT
):
ball_speed_y = -ball_speed_y

# Check if the ball falls off the screen


if ball_y + BALL_RADIUS > HEIGHT:
pygame.quit()
sys.exit()

# Paddle movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and paddle_x > 0:
paddle_x -= paddle_speed
if keys[pygame.K_RIGHT] and paddle_x < WIDTH - PADDLE_WIDTH:
paddle_x += paddle_speed

# Draw background
screen.fill(WHITE)

# Draw the ball


pygame.draw.circle(screen, RED, (int(ball_x), int(ball_y)), BALL_RADIUS)

# Draw the paddle


pygame.draw.rect(screen, RED, (paddle_x, paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT))

# Update the display


pygame.display.flip()

# Cap the frame rate


clock.tick(FPS)

OUTPUT:

Result:
Thus the above Python program was executed and the output was verified successfully.

GE3171_PSPP

https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
All 1st semester Subjects
Professional English - I - HS3152 – Click Here
Matrices and Calculus - MA3151 – Click Here
Engineering Physics - PH3151 – Click Here
Engineering Chemistry - CY3151 – Click Here
Problem Solving and Python Programming - GE3151 – Click Here
Problem Solving and Python Programming Laboratory - GE3171 – Click Here
Physics and Chemistry Laboratory - BS3171 – Click Here

You might also like