HS 1st Semester Problem Solving and Python Programming Laboratory - GE3171 - Lab Manual 2
HS 1st Semester Problem Solving and Python Programming Laboratory - GE3171 - Lab Manual 2
Laboratory
I Year/I Semester
Lab Manual
Prepared By,
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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:
Procedure:
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:
Algorithm:
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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:
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:
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:
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:
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:
Output:
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:
Program:
import math
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
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:
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:
Output:
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: "))
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
Aim:
To Implement a library application using Lists and Tuples to manage information about books.
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: "))
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
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:
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
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: “))
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”)
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:
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
Aim:
To Implement a construction materials management application using Lists and Tuples to store information
about various materials.
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: ")
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")
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!
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
Aim:
To Implement a programming language management application using Sets and Dictionaries to store
information about various languages.
Algorithm:
Program:
languages.add(name)
language_info[name] = {'Year': year, 'Creator': creator}
print(f"Language '{name}' added successfully!\n")
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()
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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")
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:
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
Programming Languages:
1. Name: Python, Year: 1991, Creator: Guido van Rossum
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
Aim:
To Implement an automobile component management application using Sets and Dictionaries to store
information about various components.
Algorithm:
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:
components.add(name)
component_info[name] = {'Manufacturer': manufacturer, 'Price': price}
print(f"Component '{name}' added successfully!\n")
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()
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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")
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:
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
Automobile Components:
1. Name: Engine, Manufacturer: ABC Motors, Price: $2500.00
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
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:
Program:
elements.add(name)
element_info[name] = {'Material': material, 'Height': height}
print(f"Element '{name}' added successfully!\n")
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 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")
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:
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 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)
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:
Use a loop to calculate the factorial by multiplying the result with each number from 1 to n.
Output Result:
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: "))
# 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
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()]
# 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:
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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_circle(radius):
return math.pi * radius**2
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: "))
# 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:
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)
Aim:
Implement a Python program using strings to reverse a given string.
Algorithm:
Start:
Initialize a variable reversed_str to store the reversed string and set it to an empty string.
Reverse String:
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: ")
# Output Result
print(f"The reversed string is: {reversed_str}")
if __name__ == "__main__":
main()
OUTPUT:
Result:
Thus the above Python program was executed and the output was verified successfully.
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:
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:
PROGRAM:
def is_palindrome(input_str):
# Remove spaces and convert to lowercase
processed_str = input_str.replace(" ", "").lower()
def main():
# Input: Accept user input for the string
user_input = input("Enter a string to check if it's a palindrome: ")
# 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:
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
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:
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: ")
# 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:
Result:
Thus the above Python program was executed and the output was verified successfully.
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 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: ")
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
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)
# 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']
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
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:
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 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
def main():
source_file = 'source.txt'
destination_file = 'destination.txt'
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:
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)
Aim:
Implement a Python program that performs division and handles a potential divide by zero error using
exception handling.
Algorithm:
Start:
PROGRAM:
def main():
# User Input
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the 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
if __name__ == "__main__":
main()
OUTPUT:
1.Normal division:
Enter the numerator: 10
Enter the denominator: 2
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:
GE3171_PSPP
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
www.BrainKart.com
4931_Grace College of Engineering,Thoothukudi
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: ")
if __name__ == "__main__":
main()
OUTPUT:
1.Valid Age
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
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:
Print a message indicating whether the student's marks are valid or not.
End:
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
if __name__ == "__main__":
main()
OUTPUT:
Result:
Thus the above Python program was executed and the output was verified successfully.
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:
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
Handle events, such as closing the window or user input, using pygame.event.get().
End:
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()
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 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:
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)
# 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
# Ball movement
ball_x += ball_speed_x
ball_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
# 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)
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