Practical Programming Exercises in Python
Practical Programming Exercises in Python
SARASWATHI
Associate Professor
ENGINEERING COLLEGE
ERUMAPATTY PO, NAMAKKAL DT, TAMILNADU, PIN-637013
NAME: …………………………………………………………………..……………..
SEMESTER: ……………………………………………………………………………
Submitted for the practical examination held at Annai Mathammal Sheela Engineering
College on ………………….
Part Details
Problem Add two numbers and display the result.
Input Two numbers, num1 and num2.
Output Display the sum of num1 and num2.
Processing Add num1 and num2 to get the sum.
Formula sum = num1 + num2
Part Details
Problem Find the area of a rectangle.
Input Length and width of the rectangle.
Output Area of the rectangle (Length × Width).
Processing Multiply length and width.
Formula area = length * width
Part Details
Problem Determine if a given number is even or odd.
Input A number n.
Output Print Even if the number is divisible by 2, else print Odd.
Processing Use modulo operation n % 2 to check divisibility by 2.
Formula If n % 2 == 0, print Even; else print Odd.
[Link].:2
DATE: Flowchart and Pseudocode
Flowchart
Pseudocode
Start
Read num1
Read num2
result = num1 + num2
Print result
End
2. Problem Calculate Area of a Rectangle
Flowchart
Pseudocode
Start
Read length
Read width
area = length * width
Print area
End
3. Problem Check if a Number is Even or Odd
Flowchart
Pseudocode
Start
Read n
If n % 2 == 0
Print "Even"
Else
Print "Odd"
End
[Link].:3
DATE: Usage of conditional logics in programs
1. Decision Making
AIM:
ALGORITHM:
PROGRAM:
age = 16
else:
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
2. Input Validation
AIM:
ALGORITHM:
Step 1: Prompt the user to enter a number and convert the input to an integer using int().
Step 2: Use conditional statements to check the value of the number:
If the number is greater than 0, print "Positive number".
Else if the number is equal to 0, print "Zero".
Otherwise, print "Negative number".
PROGRAM:
OUTPUT:
Enter a number -6
Negative number
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Loops with Conditions
AIM:
To print all even numbers from 0 to 4 using a loop and conditional check.
ALGORITHM:
Step 1: Use a for loop to iterate through numbers from 0 to 4 using range(5).
Step 2: For each number i, check if i % 2 == 0.
If true, print i followed by "is even".
PROGRAM:
for i in range(5):
if i % 2 == 0:
OUTPUT:
0 is even
2 is even
4 is even
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:4
DATE: Usage of functions in programs
AIM:
ALGORITHM:
PROGRAM:
def greet():
print("Hello, World!")
greet()
OUTPUT:
Hello, World!
Hello, World!
RESULT:
Thus the given program is executed successfully and the result has verified.
2. Functions with Parameters and Return Values
AIM:
To define a function that adds two numbers and displays their sum.
ALGORITHM:
PROGRAM:
return a + b
result = add(5,7)
print("Sum", result)
OUTPUT:
Sum 12
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Modularizing Complex Tasks
AIM:
ALGORITHM:
Step 1: Define a function calculate_area(length, width) that returns the product of length and
width.
Step 2: Define another function print_area(length, width) that calls calculate_area, stores the
result in area, and prints "Area of rectangle" followed by the value of area.
Step 3: Call print_area(4, 7) to execute the process with given dimensions.
PROGRAM:
print_area(4,7)
OUTPUT:
Area of rectangle 28
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:5
DATE: String manipulations
AIM:
To concatenate two strings with a space in between and display the result.
ALGORITHM:
PROGRAM:
str1 = "Hello"
str2 = "World"
print(result)
OUTPUT:
Hello World
RESULT:
Thus the given program is executed successfully and the result has verified.
2. Slicing (Extracting Substrings)
AIM:
To extract and print the first four characters of a string using slicing.
ALGORITHM:
PROGRAM:
text = "Python"
OUTPUT:
Pyth
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Case Conversion
AIM:
ALGORITHM:
PROGRAM:
word = "hello"
print([Link]())
print([Link]())
OUTPUT:
HELLO
Hello
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:6
DATE:
Operations on lists
1. Appending Elements
AIM:
To demonstrate how to add an item to a list using the append() method in Python.
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
2. Removing Elements
AIM:
To remove a specific item from a list using the remove() method in Python.
ALGORITHM:
Step 1: Create a list named fruits containing "apple", "banana", and "cherry".
Step 2: Use [Link]("banana") to delete "banana" from the list.
Step 3: Print the updated list using print(fruits).
PROGRAM:
[Link]("banana")
print(fruits)
OUTPUT:
['apple', 'cherry']
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Sorting Lists
AIM:
ALGORITHM:
Step 1: Create a list named numbers with the elements [3, 1, 4, 2].
Step 2: Use [Link]() to sort the list in ascending order.
Step 3: Print the sorted list using print(numbers).
PROGRAM:
numbers = [3, 1, 4, 2]
[Link]()
print(numbers)
OUTPUT:
[1, 2, 3, 4]
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:7
DATE: Operations on tuples
AIM:
ALGORITHM:
Step 1: Create a tuple my_tuple with elements (10, 20, 30, 40, 50).
Step 2: Use my_tuple[0] to access and print the first element.
Step 3: Use my_tuple[-1] to access and print the last element.
Step 4: Use slicing my_tuple[1:4] to extract elements from index 1 to 3 and print them.
PROGRAM:
# Indexing
# Slicing
10
50
RESULT:
Thus the given program is executed successfully and the result has verified.
AIM:
ALGORITHM:
PROGRAM:
t1 = (1, 2)
t2 = (3, 4)
# Concatenation
t3 = t1 + t2
print(t3)
# Repetition
t4 = t1 * 3
print(t4)
OUTPUT:
(1, 2, 3, 4)
(1, 2, 1, 2, 1, 2)
RESULT:
Thus the given program is executed successfully and the result has verified.
AIM:
To demonstrate tuple operations such as finding length, counting occurrences, and locating the index of
a value.
ALGORITHM:
PROGRAM:
numbers = (1, 2, 3, 2, 4, 2)
# Length of tuple
print(len(numbers))
print([Link](2))
print([Link](3))
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:8
DATE: Operations on sets
1. Union
AIM:
To demonstrate set union operation in Python by combining elements from two sets.
ALGORITHM:
Step 1: Create two sets: set1 = {1, 2, 3} and set2 = {3, 4, 5}.
Step 2: Use [Link](set2) or set1 | set2 to combine all unique elements from both sets.
Step 3: Print the resulting set.
PROGRAM:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = [Link](set2)
print(result)
OUTPUT:
{1, 2, 3, 4, 5}
RESULT:
Thus the given program is executed successfully and the result has verified.
2. Intersection
AIM:
To find the common elements between two sets using the intersection operation in Python.
ALGORITHM:
Step 1: Create two sets: set1 = {1, 2, 3} and set2 = {2, 3, 4}.
Step 2: Use [Link](set2) or set1 & set2 to find elements present in both sets.
Step 3: Print the resulting set.
PROGRAM:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = [Link](set2)
print(result)
OUTPUT:
{2, 3}
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Difference
AIM:
ALGORITHM:
Step 1: Create two sets: set1 = {1, 2, 3} and set2 = {2, 3, 4}.
Step 2: Use [Link](set2) or set1 - set2 to get elements that are in set1 but not in set2.
Step 3: Print the resulting set.
PROGRAM:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = [Link](set2)
print(result)
OUTPUT:
{1}
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:9
DATE: Operations on dictionaries
1. Accessing Values
AIM:
To demonstrate dictionary access using keys and the get() method in Python.
ALGORITHM:
Step 1: Create a dictionary person with keys "name", "age", and "city".
Step 2: Use person["name"] to access the value directly by key.
Step 3: Use [Link]("city") to safely retrieve the value for "city".
Step 4: Use [Link]("country", "Not Found") to attempt retrieving a non-existent key with a
default fallback.
PROGRAM:
# Using key
print(person["name"])
print([Link]("city"))
Alice
New York
Not Found
RESULT:
Thus the given program is executed successfully and the result has verified.
AIM:
To demonstrate how to add a new key-value pair and update an existing value in a Python dictionary.
ALGORITHM:
Step 1: Create a dictionary person with initial keys "name", "age", and "city".
Step 2: Add a new key "country" with value "USA" and update the value of "age" to 26.
Step 3: Print the updated dictionary using print(person).
PROGRAM:
print(person)
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Removing Entries
AIM:
To demonstrate how to delete dictionary items using del, pop(), and popitem() methods in Python.
ALGORITHM:
Step 1: Create a dictionary person with keys "name", "age", and "city".
Step 2: Use del person["city"] to remove the "city" key.
Step 3: Use [Link]("age") to remove the "age" key and store its value in age.
Step 4: Use [Link]() to remove the last inserted key-value pair and store it in item.
Step 5: Print the values of age, item, and the final state of the dictionary.
PROGRAM:
del person["city"]
age = [Link]("age")
item = [Link]()
print(age)
print(item)
print(person)
OUTPUT:
25
('name', 'Alice')
{}
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:10
DATE: Opening, closing, reading and writing in formatted file format and
sort data
AIM:
To demonstrate reading, writing, and sorting data in both CSV and JSON formats using Python.
ALGORITHM:
Step 1: Create a list of employee records and write it to a CSV file using [Link]().
Step 2: Read the CSV file using [Link]() and convert its content into a list.
Step 3: Sort the CSV data by the "Age" column and write the sorted data to a new CSV file.
Step 4: Create a dictionary of employee records and write it to a JSON file using [Link]().
Step 5: Read the JSON file using [Link]() and sort the employee data by the "age" key.
Step 6: Write the sorted JSON data to a new file.
PROGRAM:
import csv
import json
csv_data = [
writer = [Link](f)
[Link](csv_data)
reader = [Link](f)
csv_content = list(reader)
sorted_csv.insert(0, csv_content[0])
[Link](sorted_csv)
json_data = {
"employees": [
[Link](json_data, f, indent=4)
data = [Link](f)
# Sort JSON data by Age
data['employees'] = sorted_json
[Link](data, f, indent=4)
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
AIM:
To create, process, and enhance employee data in both CSV and JSON formats by calculating and
appending the average salary.
ALGORITHM:
Step 1: Define a list of employee records containing name, age, and salary.
Step 2: Write the employee data to a CSV file using [Link]().
Step 3: Calculate the average salary from the CSV data by summing the salary values and
dividing by the number of employees.
Step 4: Append a new row with the average salary to the CSV data and write it to a new CSV
file.
Step 5: Create a JSON object with the same employee data structured under the "employees"
key.
Step 6: Write the JSON data to a file using [Link]().
Step 7: Calculate the average salary from the JSON data and add it as a new key
"average_salary" in the JSON object.
Step 8: Write the updated JSON data to a new file.
PROGRAM:
import csv
import json
# Original Data
csv_data = [
writer = [Link](f)
[Link](csv_data)
writer = [Link](f)
[Link](csv_data)
# JSON Data
json_data = {
"employees": [
[Link](json_data, f, indent=4)
json_data['average_salary'] = average_salary_json
with open('data_with_avg.json', 'w') as f:
[Link](json_data, f, indent=4)
OUTPUT:
CSV Output
JSON Output
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Remove Employees Below a Certain Age and Write Updated Data to CSV/JSON
AIM:
To filter employee records by age from both CSV and JSON formats, retaining only those aged 30 and
above.
ALGORITHM:
Step 1: Create a list of employee records and write it to a CSV file using [Link]().
Step 2: Filter the CSV data to exclude employees below age 30 and write the result to a new
CSV file.
Step 3: Create a JSON object with employee records and write it to a JSON file using
[Link]().
Step 4: Filter the JSON data to exclude employees below age 30 and write the result to a new
JSON file.
PROGRAM:
import csv
import json
# Original Data
csv_data = [
writer = [Link](f)
[Link](csv_data)
# Remove Employees Below Age 30
writer = [Link](f)
[Link](filtered_csv)
# JSON Data
json_data = {
"employees": [
[Link](json_data, f, indent=4)
# Remove Employees Below Age 30 in JSON
filtered_json = {
[Link](filtered_json, f, indent=4)
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:11
DATE: Usage of modules and packages to solve problems
AIM:
To read sales data from a CSV file, calculate total revenue per month, and visualize it using a bar chart.
ALGORITHM:
Step 1: Import the required libraries (pandas and [Link]) and load the CSV file into a
DataFrame.
Step 2: Group the data by the "Month" column and calculate the sum of "Revenue" for each
month.
Step 3: Plot the grouped revenue data as a bar chart with appropriate labels and title.
PROGRAM:
import pandas as pd
data = pd.read_csv('sales_data.csv')
monthly_revenue = [Link]('Month')['Revenue'].sum()
# Plot the revenue
[Link]('Month')
[Link]('Revenue')
[Link]()
sales_data.csv
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
AIM:
To calculate the standard deviation of a dataset and find the square root of its first element using NumPy
and the math module.
ALGORITHM:
PROGRAM:
import numpy as np
import math
std_dev = [Link](data)
sqrt_val = [Link](data[0])
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
3. Building a Simple Machine Learning Model Using scikit-learn
AIM:
To build and evaluate a Decision Tree classifier using the Iris dataset to predict flower species.
ALGORITHM:
Step 1: Load the Iris dataset and separate it into features (X) and target labels (y).
Step 2: Split the dataset into training and testing sets using train_test_split() with 30% for
testing.
Step 3: Create a DecisionTreeClassifier model and train it using the training data.
Step 4: Use the trained model to predict labels for the test set.
Step 5: Evaluate the model's performance using accuracy_score() and print the result.
PROGRAM:
# Load dataset
iris = load_iris()
X = [Link]
y = [Link]
# Split dataset
# Train model
model = DecisionTreeClassifier()
[Link](X_train, y_train)
y_pred = [Link](X_test)
OUTPUT:
Accuracy 0.9333333333333333
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:12
DATE: Personal Expense Tracker
AIM:
To record daily expenses and visualize the distribution of spending across categories using a pie chart.
ALGORITHM:
Step 1: Define a function add_expense() that appends a new expense entry with the current date,
category, and amount to a CSV file.
Step 2: Load the expense data from the CSV file into a pandas DataFrame with columns: Date,
Category, and Amount.
Step 3: Group the data by Category and calculate the total amount spent in each category.
Step 4: Plot the grouped data as a pie chart to show the percentage distribution of expenses.
PROGRAM:
import pandas as pd
# Add an expense
date = [Link]().strftime('%Y-%m-%d')
monthly = [Link]('Category')['Amount'].sum()
[Link]()
[Link]
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.
[Link].:13
DATE: Guess the Number Game in Python
AIM:
To create a number guessing game in Python where the user tries to guess a randomly selected number
between 1 and 15.
ALGORITHM:
Step 1: Import the random module and generate a random number between 1 and 15.
Step 2: Initialize the attempt counter and prompt the user to guess the number.
Step 3: Use a loop to compare the user's guess with the target number.
If the guess is too low, display a hint.
If the guess is too high, display a hint.
If the guess is correct, congratulate the user and show the number of attempts.
Step 4: Handle invalid inputs using a try-except block to ensure the user enters a valid number.
PROGRAM:
import random
def guess_the_number():
attempts = 0
try:
attempts += 1
else:
break
except ValueError:
guess_the_number()
OUTPUT:
RESULT:
Thus the given program is executed successfully and the result has verified.