0% found this document useful (0 votes)
7 views56 pages

Practical Programming Exercises in Python

The document is a practical examination report for students at Annai Mathammal Sheela Engineering College, detailing various programming exercises. It includes problems and solutions related to basic operations, conditional logic, functions, string manipulations, lists, tuples, and sets in Python. Each exercise is accompanied by algorithms, programs, and expected outputs, demonstrating the execution and verification of the results.

Uploaded by

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

Practical Programming Exercises in Python

The document is a practical examination report for students at Annai Mathammal Sheela Engineering College, detailing various programming exercises. It includes problems and solutions related to basic operations, conditional logic, functions, string manipulations, lists, tuples, and sets in Python. Each exercise is accompanied by algorithms, programs, and expected outputs, demonstrating the execution and verification of the results.

Uploaded by

Dr.K.SARASWATHI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr.K.

SARASWATHI

Associate Professor

Department of General Engineering

Annai Mathammal Sheela Engineering College

Erumapatty, Tamil Nadu, India


ANNAI MATHAMMAL SHEELA

ENGINEERING COLLEGE
ERUMAPATTY PO, NAMAKKAL DT, TAMILNADU, PIN-637013

DEPARTMENT OF ROBOTICS AND AUTOMATION

This is to certify that the following student

NAME: …………………………………………………………………..……………..

REGISTER NO: ……………………………………….……………………….……...

DEGREE & BRANCH: ……………………………………………………….……….

SUBJECT CODE & NAME: …………………………………………………..……..

SEMESTER: ……………………………………………………………………………

STAFF INCHARGE HEAD OF THE DEPARTMENT

Submitted for the practical examination held at Annai Mathammal Sheela Engineering

College on ………………….

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

[Link] Date Name of Experiment Page Remarks


No
[Link].:1
DATE: Problem Analysis Chart

1. Problem Add Two Numbers

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

2. Problem Calculate Area of a Rectangle

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

3. Problem Check if a Number is Even or Odd

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

1. Problem Add Two Numbers

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:

To determine whether a person is an adult or a minor based on their age.

ALGORITHM:

 Step 1: Assign the value 18 to the variable age.


 Step 2: Check if age is greater than or equal to 18.
 If true, print "You are an adult."
 If false, print "You are a minor."

PROGRAM:

age = 16

if age >= 18:

print("You are an adult")

else:

print("You are a minor")

OUTPUT:

You are a minor

RESULT:

Thus the given program is executed successfully and the result has verified.
2. Input Validation

AIM:

To classify a user-input number as positive, negative, or zero.

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:

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


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

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:

print(i, "is even")

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

1. Reusing Code with Functions

AIM:

To define and call a function that prints a greeting message.

ALGORITHM:

 Step 1: Define a function named greet() that prints "Hello, World!".


 Step 2: Call the greet() function twice to execute the print statement each time.

PROGRAM:

def greet():

print("Hello, World!")

greet() # Calling the function multiple times

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:

 Step 1: Define a function add(a, b) that returns the sum of a and b.


 Step 2: Call the function with arguments 5 and 7, store the result in result, and print "Sum"
followed by the result.

PROGRAM:

def add(a, b):

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:

To calculate and display the area of a rectangle using functions.

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:

def calculate_area(length, width):

return length * width

def print_area(length, width):

area = calculate_area(length, width)

print(f"Area of rectangle {area}")

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

1. Concatenation (Joining Strings)

AIM:

To concatenate two strings with a space in between and display the result.

ALGORITHM:

 Step 1: Assign "Hello" to str1 and "World" to str2.


 Step 2: Concatenate str1, a space " ", and str2 into a new variable result.
 Step 3: Print the value of result.

PROGRAM:

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

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:

 Step 1: Assign the string "Python" to the variable text.


 Step 2: Use slicing text[0:4] to extract characters from index 0 to 3.
 Step 3: Print the sliced substring.

PROGRAM:

text = "Python"

print(text[0:4]) # from index 0 to 3

OUTPUT:

Pyth

RESULT:

Thus the given program is executed successfully and the result has verified.
3. Case Conversion

AIM:

To demonstrate string case conversion using built-in string methods in Python.

ALGORITHM:

 Step 1: Assign the string "hello" to the variable word.


 Step 2: Use [Link]() to convert all characters to uppercase and print the result.
 Step 3: Use [Link]() to capitalize the first letter of the string and print the result.

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:

 Step 1: Create a list named fruits containing "apple" and "banana".


 Step 2: Use [Link]("cherry") to add "cherry" to the end of the list.
 Step 3: Print the updated list using print(fruits).

PROGRAM:

fruits = ["apple", "banana"]


[Link]("cherry")
print(fruits)

OUTPUT:

['apple', 'banana', 'cherry']

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:

fruits = ["apple", "banana", "cherry"]

[Link]("banana")

print(fruits)

OUTPUT:

['apple', 'cherry']

RESULT:

Thus the given program is executed successfully and the result has verified.
3. Sorting Lists

AIM:

To sort a list of numbers in ascending order using the sort() method.

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

1. Indexing and Slicing

AIM:

To demonstrate tuple indexing and slicing in Python.

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:

my_tuple = (10, 20, 30, 40, 50)

# Indexing

print(my_tuple[0]) # First element

print(my_tuple[-1]) # Last element

# Slicing

print(my_tuple[1:4]) # Elements from index 1 to 3


OUTPUT:

10

50

(20, 30, 40)

RESULT:

Thus the given program is executed successfully and the result has verified.

2. Concatenation and Repetition

AIM:

To demonstrate tuple concatenation and repetition using Python operators.

ALGORITHM:

 Step 1: Create two tuples t1 = (1, 2) and t2 = (3, 4).


 Step 2: Concatenate t1 and t2 using the + operator and store the result in t3.
 Step 3: Repeat the tuple t1 three times using the * operator and store the result in t4.
 Step 4: Print both t3 and t4.

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.

3. Tuple Methods and Built-in Functions

AIM:

To demonstrate tuple operations such as finding length, counting occurrences, and locating the index of
a value.

ALGORITHM:

 Step 1: Create a tuple numbers = (1, 2, 3, 2, 4, 2).


 Step 2: Use len(numbers) to get the total number of elements in the tuple.
 Step 3: Use [Link](2) to count how many times the value 2 appears.
 Step 4: Use [Link](3) to find the first index where the value 3 occurs.

PROGRAM:

numbers = (1, 2, 3, 2, 4, 2)

# Length of tuple

print(len(numbers))

# Count occurrences of a value

print([Link](2))

# Find index of a value

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)

# OR result = set1 | 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)

# OR result = set1 & set2

print(result)

OUTPUT:

{2, 3}

RESULT:

Thus the given program is executed successfully and the result has verified.
3. Difference

AIM:

To demonstrate how to find the difference between two sets 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 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)

# OR result = set1 - 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:

person = {"name":"Alice", "age": 25, "city":"New York"}

# Using key

print(person["name"])

# Using get() (won’t throw error if key doesn’t exist)

print([Link]("city"))

print([Link]("country", "Not Found"))


OUTPUT:

Alice

New York

Not Found

RESULT:

Thus the given program is executed successfully and the result has verified.

2. Adding or Updating Entries

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:

person = {"name": "Alice", "age": 25, "city": "New York"}

person["country"] = "USA" # Add new key

person["age"] = 26 # Update existing key

print(person)
OUTPUT:

{'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}

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:

person = {"name": "Alice", "age": 25, "city": "New York"}

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

1. CSV and JSON Data Handling with Sorting by Age in Python

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

# Write CSV file

csv_data = [

['Name', 'Age', 'Salary'],

['John', 30, 50000],


['Jane', 25, 60000],

['Doe', 35, 55000]

with open('[Link]', 'w', newline='') as f:

writer = [Link](f)

[Link](csv_data)

# Read CSV file

with open('[Link]', 'r') as f:

reader = [Link](f)

csv_content = list(reader)

# Sort CSV by Age (index 1)

sorted_csv = sorted(csv_content[1:], key=lambda x: int(x[1]))

sorted_csv.insert(0, csv_content[0])

# Write sorted CSV back to file

with open('sorted_data.csv', 'w', newline='') as f:


writer = [Link](f)

[Link](sorted_csv)

# Write JSON file

json_data = {

"employees": [

{"name": "John", "age": 30, "salary": 50000},

{"name": "Jane", "age": 25, "salary": 60000},

{"name": "Doe", "age": 35, "salary": 55000}

with open('[Link]', 'w') as f:

[Link](json_data, f, indent=4)

# Read JSON file

with open('[Link]', 'r') as f:

data = [Link](f)
# Sort JSON data by Age

sorted_json = sorted(data['employees'], key=lambda x: x['age'])

data['employees'] = sorted_json

# Write sorted JSON back to file

with open('sorted_data.json', 'w') as f:

[Link](data, f, indent=4)

OUTPUT:

Sorted CSV Output


Sorted JSON Output

RESULT:

Thus the given program is executed successfully and the result has verified.

2. Calculate and Add Average Salary to CSV and JSON

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 = [

['Name', 'Age', 'Salary'],

['John', 30, 50000],

['Jane', 25, 60000],

['Doe', 35, 55000],

['Alice', 40, 70000],

['Bob', 28, 65000] ]


# Write CSV file

with open('[Link]', 'w', newline='') as f:

writer = [Link](f)

[Link](csv_data)

# Calculate Average Salary

total_salary = sum(row[2] for row in csv_data[1:])

average_salary = total_salary / (len(csv_data) - 1)

# Add Average Salary to CSV

csv_data.append(['Average', '', average_salary])

with open('data_with_avg.csv', 'w', newline='') as f:

writer = [Link](f)

[Link](csv_data)

# JSON Data

json_data = {

"employees": [

{"name": "John", "age": 30, "salary": 50000},


{"name": "Jane", "age": 25, "salary": 60000},

{"name": "Doe", "age": 35, "salary": 55000},

{"name": "Alice", "age": 40, "salary": 70000},

{"name": "Bob", "age": 28, "salary": 65000}

# Write JSON File

with open('[Link]', 'w') as f:

[Link](json_data, f, indent=4)

# Calculate Average Salary in JSON

average_salary_json = sum(emp['salary'] for emp in json_data['employees']) /


len(json_data['employees'])

# Add Average Salary to JSON

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 = [

['Name', 'Age', 'Salary'],

['John', 30, 50000],

['Jane', 25, 60000],

['Doe', 35, 55000],

['Alice', 40, 70000],

['Bob', 28, 65000]

# Write CSV file

with open('[Link]', 'w', newline='') as f:

writer = [Link](f)

[Link](csv_data)
# Remove Employees Below Age 30

filtered_csv = [csv_data[0]] + [row for row in csv_data[1:] if row[1] >= 30]

with open('filtered_data.csv', 'w', newline='') as f:

writer = [Link](f)

[Link](filtered_csv)

# JSON Data

json_data = {

"employees": [

{"name": "John", "age": 30, "salary": 50000},

{"name": "Jane", "age": 25, "salary": 60000},

{"name": "Doe", "age": 35, "salary": 55000},

{"name": "Alice", "age": 40, "salary": 70000},

{"name": "Bob", "age": 28, "salary": 65000}

# Write JSON File

with open('[Link]', 'w') as f:

[Link](json_data, f, indent=4)
# Remove Employees Below Age 30 in JSON

filtered_json = {

"employees": [emp for emp in json_data['employees'] if emp['age'] >= 30]

with open('filtered_data.json', 'w') as f:

[Link](filtered_json, f, indent=4)

OUTPUT:

Filtered CSV Output


Filtered JSON 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

1. Data Analysis Using pandas and matplotlib

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

import [Link] as plt

# Load CSV data

data = pd.read_csv('sales_data.csv')

# Group by month and sum revenue

monthly_revenue = [Link]('Month')['Revenue'].sum()
# Plot the revenue

monthly_revenue.plot(kind='bar', title='Monthly Revenue')

[Link]('Month')

[Link]('Revenue')

[Link]()

sales_data.csv
OUTPUT:

RESULT:

Thus the given program is executed successfully and the result has verified.

2. Scientific Calculations Using numpy and math

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:

 Step 1: Define a list data containing numerical values.


 Step 2: Use [Link]() to compute the standard deviation of the list.
 Step 3: Use [Link]() to calculate the square root of the first element in the list.
 Step 4: Print both the standard deviation and the square root result.

PROGRAM:

import numpy as np

import math

data = [12, 15, 20, 22, 24]

# Calculate standard deviation

std_dev = [Link](data)

# Square root of the first value

sqrt_val = [Link](data[0])

print("Standard Deviation", std_dev)

print("Square Root of First Element", sqrt_val)

OUTPUT:

Standard Deviation 4.454211490264017


Square Root of First Element 3.4641016151377544

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:

from [Link] import load_iris

from [Link] import DecisionTreeClassifier

from [Link] import accuracy_score

from sklearn.model_selection import train_test_split

# Load dataset

iris = load_iris()

X = [Link]

y = [Link]
# Split dataset

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# Train model

model = DecisionTreeClassifier()

[Link](X_train, y_train)

# Predict and evaluate

y_pred = [Link](X_test)

print("Accuracy", accuracy_score(y_test, y_pred))

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

import [Link] as plt

from datetime import datetime

# Add an expense

def add_expense(amount, category):

date = [Link]().strftime('%Y-%m-%d')

with open('[Link]', 'a') as f:


[Link](f"{date},{category},{amount}\n")

# Load and analyze expenses

df = pd.read_csv('[Link]', names=['Date', 'Category', 'Amount'])

monthly = [Link]('Category')['Amount'].sum()

[Link](kind='pie', autopct='%1.1f%%', title='Monthly Expense Distribution')

[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():

number_to_guess = [Link](1, 15)

attempts = 0

print("Welcome to 'Guess the Number'!")

print("I'm thinking of a number between 1 and 15.")


while True:

try:

guess = int(input("Take a guess: "))

attempts += 1

if guess < number_to_guess:

print("Too low! Try again.")

elif guess > number_to_guess:

print("Too high! Try again.")

else:

print(f"Congratulations! You guessed it in {attempts} attempts.")

break

except ValueError:

print("Please enter a valid number.")

guess_the_number()
OUTPUT:

Welcome to 'Guess the Number'!


I'm thinking of a number between 1 and 15.
Take a guess: 9
Too high! Try again.
Take a guess: 7
Too high! Try again.
Take a guess: 4
Too high! Try again.
Take a guess: 2
Too low! Try again.
Take a guess: 3
Congratulations! You guessed it in 5 attempts.

RESULT:

Thus the given program is executed successfully and the result has verified.

You might also like