New Lab Manual Final
New Lab Manual Final
Aim:
This project aims to create a real-time library management system using lists in Python. The system
should allow users to perform various operations such as adding books, removing books, displaying available
books, checking out books, and returning books.
Algorithm:
1. Book Class:
o Create a Book class with attributes for title, author, and availability status.
2. Library Class:
o Create a Library class with methods for adding a book, removing a book, displaying
available books, checking out a book, and returning a book.
3. Main Function:
o Prompt users to choose from various options (add a book, remove a book, display
available books, check out a book, return a book, or exit).
Program
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
self.available = True
def __str__(self):
return f"Title: {self.title}\nAuthor: {self.author}\nAvailable: {'Yes' if self.available else 'No'}"
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
print("Book added successfully.")
def display_books(self):
if not self.books:
print("No books in the library.")
else:
for index, book in enumerate(self.books, start=1):
print(f"Book {index}:")
print(book)
def main():
library = Library()
while True:
print("\nLibrary Management System")
print("1. Add Book")
print("2. Display Books")
print("3. Borrow Book")
print("4. Return Book")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
title = input("Enter book title: ")
author = input("Enter book author: ")
book = Book(title, author)
library.add_book(book)
elif choice == '2':
library.display_books()
elif choice == '3':
title = input("Enter book title to borrow: ")
library.borrow_book(title)
elif choice == '4':
title = input("Enter book title to return: ")
library.return_book(title)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please choose again.")
if __name__ == "__main__":
main()
Output:
Result:
The Python program for Library stock management is executed, and the output is verified.
1b. Implementation of construction material management using list
Aim:
The Python program for construction materials aims to provide a tool for managing information
about various construction materials, including their names, quantities, and prices. This program enables
users to add new materials, update existing materials, and display the list of materials along with their
details.
Algorithm:
1. Start the program.
2. Initialize an empty dictionary or list to store information about construction materials.
3. Define functions/methods to perform the following operations:
4. Add a new material: Prompt the user to enter the name, quantity, and price of the material.
Add this information to the dictionary or list.
5. Update an existing material: Prompt the user to enter the name of the material to be updated.
If the material exists, allow the user to update its quantity and price.
6. Display materials: Iterate through the dictionary or list and print the details of each material.
7. Implement a loop to continuously prompt the user for choices until they choose to exit the
program.
8. Provide options for the user to add new materials, update existing materials, display the list of
materials, or exit the program.
9. End the program.
Program:
# Initialize an empty list to store construction materials
materials = []
def add_material(name, quantity, price_per_unit):
"""Add a new material to the list"""
material = (name, quantity, price_per_unit)
materials.append(material)
print(f"{name} added to the materials list.")
def update_material(name, quantity, price_per_unit):
"""Update an existing material in the list"""
for i, material in enumerate(materials):
if material[0] == name:
materials[i] = (name, quantity, price_per_unit)
print(f"{name} updated in the materials list.")
return
print(f"{name} not found in the materials list.")
def display_materials():
"""Display all materials in the list"""
if not materials:
print("No materials found.")
else:
print("Materials List:")
for material in materials:
print(f"Name: {material[0]}, Quantity: {material[1]}, Price Per Unit: {material[2]}")
if choice == '1':
name = input("Enter material name: ")
quantity = int(input("Enter quantity: "))
price_per_unit = float(input("Enter price per unit: "))
add_material(name, quantity, price_per_unit)
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Output:
Construction Materials Management System
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 1
Enter material name: cement
Enter quantity: 10
Enter price per unit: 100
cement added to the materials list.
Result:
The Python program for construction materials management is executed, and the output is verified.
The aim of the program is to simulate a basic management system for automobiles. It allows management of
a vehicle catalog, inventory, and analysis of customer preferences.
Algorithm:
1. Define a class Automobile with methods to manage the catalog, inventory, and customer preferences.
2. Implement methods to add and remove models from the catalog, add vehicles to the inventory, and
sell vehicles.
3. Implement methods to record and update customer preferences, as well as find common preferences
among customers.
4. In the main() function:
o Create an instance of Automobile.
o Populate initial data including catalog models, vehicles in inventory, and customer
preferences.
o Present a menu to the user with options to manage the catalog, inventory, analyze customer
preferences, or exit.
o Based on the user's choice, perform the corresponding actions using methods from the
Automobile class.
Program:
class Automobile:
def __init__(self):
self.catalog = set()
self.inventory = set()
self.customer_preferences = {}
def add_model_to_catalog(self, model):
self.catalog.add(model)
print(f"Model '{model}' added to the catalog.")
def remove_model_from_catalog(self, model):
if model in self.catalog:
self.catalog.remove(model)
print(f"Model '{model}' removed from the catalog.")
else:
print(f"Model '{model}' not found in the catalog.")
def display_catalog(self):
print("Vehicle Catalog:")
for model in self.catalog:
print("-", model)
def add_vehicle_to_inventory(self, vehicle):
self.inventory.add(vehicle)
print(f"Vehicle '{vehicle}' added to the inventory.")
def sell_vehicle(self, vehicle):
if vehicle in self.inventory:
self.inventory.remove(vehicle)
print(f"Vehicle '{vehicle}' sold.")
else:
print(f"Vehicle '{vehicle}' not found in the inventory.")
def display_inventory(self):
print("Current Inventory:")
for vehicle in self.inventory:
print("-", vehicle)
def add_customer_preference(self, customer, models):
self.customer_preferences[customer] = set(models)
print(f"Customer '{customer}' preferences recorded successfully.")
def update_customer_preference(self, customer, new_models):
if customer in self.customer_preferences:
self.customer_preferences[customer].update(new_models)
print(f"Customer '{customer}' preferences updated successfully.")
else:
print(f"Customer '{customer}' not found in the preferences.")
def common_preferences(self):
common_pref = set.intersection(*self.customer_preferences.values())
print("Common Customer Preferences:")
for model in common_pref:
print("-", model)
def main():
auto = Automobile()
# Populate initial data
auto.add_model_to_catalog("SUV")
auto.add_model_to_catalog("Sedan")
auto.add_model_to_catalog("Hatchback")
auto.add_model_to_catalog("Truck")
auto.add_vehicle_to_inventory("SUV-001")
auto.add_vehicle_to_inventory("Sedan-001")
auto.add_vehicle_to_inventory("Hatchback-001")
auto.add_vehicle_to_inventory("Truck-001")
auto.add_customer_preference("John", ["SUV", "Sedan"])
auto.add_customer_preference("Alice", ["SUV", "Hatchback"])
auto.add_customer_preference("Bob", ["Sedan", "Truck"])
# Main Menu
while True:
print("\nMenu:")
print("1. Vehicle Catalog Management")
print("2. Inventory Management")
print("3. Customer Preference Analysis")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
print("\nVehicle Catalog Management:")
auto.add_model_to_catalog(input("Enter new model to add: "))
auto.remove_model_from_catalog(input("Enter model to remove: "))
auto.display_catalog()
elif choice == '2':
print("\nInventory Management:")
auto.add_vehicle_to_inventory(input("Enter new vehicle to add to inventory: "))
auto.sell_vehicle(input("Enter vehicle sold: "))
auto.display_inventory()
elif choice == '3':
print("\nCustomer Preference Analysis:")
auto.add_customer_preference(input("Enter customer name: "),
input("Enter preferred models (comma-separated): ").split(','))
auto.update_customer_preference(input("Enter customer name to update preferences: "),
input("Enter new preferred models (comma-separated): ").split(','))
auto.common_preferences()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number from 1 to 4.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Vehicle Catalog Management
2. Inventory Management
3. Customer Preference Analysis
4. Exit
Enter your choice: 1
Menu:
1. Vehicle Catalog Management
2. Inventory Management
3. Customer Preference Analysis
4. Exit
Enter your choice:
Result:
Thus, the implementation of Vehicle implementation are implemented and result was obtained
Algorithm:
Program:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i # Fix: Multiply 'result' by 'i', not assign 'i' to 'result'
return result
def main():
try:
num = int(input("Enter a non-negative integer: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
if __name__ == "__main__":
main()
Result:
Thus,the Implementing programs using Functions Factorial and result was obtained
Algorithm:
Program:
def find_largest(numbers):
if not numbers:
return None
max_number = numbers[0]
for num in numbers:
if num > max_number:
max_number = num
return max_number
def main():
try:
numbers = [int(x) for x in input("Enter numbers separated by space: ").split()]
largest = find_largest(numbers)
if largest is not None:
print(f"The largest number in the list is {largest}.")
else:
print("No numbers were provided.")
except ValueError:
print("Invalid input. Please enter numbers separated by space.")
if __name__ == "__main__":
main()
output
Result:
Thus the implementation of the programs using Functions using largest number in a list and result was
obtained
Algorithm:
1. Define functions for calculating the area of different shapes: square_area, rectangle_area, and
circle_area.
2. square_area function:
o Takes the length of a side as input.
o Calculates the area using the formula: area = side * side.
o Returns the calculated area.
3. rectangle_area function:
o Takes the length and width of the rectangle as input.
o Calculates the area using the formula: area = length * width.
o Returns the calculated area.
4. circle_area function:
o Takes the radius of the circle as input.
o Calculates the area using the formula: area = π * radius^2.
o Returns the calculated area.
5. In the main program:
o Prompt the user to choose a shape for which they want to calculate the area.
o Based on the user's choice, prompt for necessary dimensions.
o Call the respective function to calculate the area.
Program:
import math
def circle_area(radius):
return math.pi * radius**2
if choice == '1':
try:
radius = float(input("Enter the radius of the circle: "))
print(f"The area of the circle is {circle_area(radius)}.")
except ValueError:
print("Invalid input. Please enter a numeric value for the radius.")
elif choice == '2':
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
print(f"The area of the rectangle is {rectangle_area(length, width)}.")
except ValueError:
print("Invalid input. Please enter numeric values for length and width.")
elif choice == '3':
try:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
print(f"The area of the triangle is {triangle_area(base, height)}.")
except ValueError:
print("Invalid input. Please enter numeric values for base and height.")
else:
print("Invalid choice. Please enter 1, 2, or 3.")
if __name__ == "__main__":
main()
Output
Result:
Thus the program that allows users to calculate the area of different geometric shapes (circle, rectangle, or
triangle) based on their choices and result was obtained
Algorithm:
1. Implement functions for each operation: reverse a string, check for palindrome, count characters, and
replace characters.
2. For reversing a string, use slicing or iteration.
3. For checking palindrome, compare the string with its reverse.
4. For counting characters, iterate through the string and maintain a count for each character.
5. For replacing characters, iterate through the string and replace the desired characters.
6. Display appropriate outputs for each operation.
Program:
# Function to reverse a string
def reverse_string(string):
return string[::-1]
def main():
while True:
print("\nMenu:")
print("1. Reverse a string")
print("2. Check if a string is palindrome")
print("3. Count characters in a string")
print("4. Replace characters in a string")
print("5. Exit")
if choice == '1':
string = input("Enter a string: ")
print("Reversed string:", reverse_string(string))
elif choice == '2':
string = input("Enter a string: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
elif choice == '3':
string = input("Enter a string: ")
char_count = count_characters(string)
print("Character count:")
for char, count in char_count.items():
print(char, ":", count)
elif choice == '4':
string = input("Enter a string: ")
old_char = input("Enter character to replace: ")
new_char = input("Enter new character: ")
print("Modified string:", replace_characters(string, old_char, new_char))
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 1
Enter a string: hello
Reversed string: olleh
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 2
Enter a string: radar
The string is a palindrome.
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 3
Enter a string: hello
Character count:
h:1
e:1
l:2
o:1
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 4
Enter a string: hello
Enter character to replace: l
Enter new character: z
Modified string: hezzo
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 5
Exiting program.
Result:
Thus the Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters) and result was obtained.
Algorithm:
1. Define functions for each operation: copy content from one file to another, count words, and find the
longest word.
2. For copying content, open the source file in read mode and the destination file in write mode, then
read content from the source file and write it to the destination file.
3. For counting words, read the content from the file and split it into words using whitespace as a
delimiter. Count the number of words obtained.
4. For finding the longest word, split the content into words and iterate through them, keeping track of
the longest word encountered.
5. Display appropriate outputs for each operation.
Program:
def main():
while True:
print("\nMenu:")
print("1. Copy content from one file to another")
print("2. Count words in a file")
print("3. Find the longest word in a file")
print("4. Exit")
if choice == '1':
source_file = input("Enter source file name: ")
destination_file = input("Enter destination file name: ")
copy_file(source_file, destination_file)
elif choice == '2':
file_name = input("Enter file name: ")
print("Number of words in the file:", count_words(file_name))
elif choice == '3':
file_name = input("Enter file name: ")
print("Longest word in the file:", longest_word(file_name))
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 1
Enter source file name: source.txt
Enter destination file name: destination.txt
Content copied successfully.
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 2
Enter file name: destination.txt
Number of words in the file: 9
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 3
Enter file name: destination.txt
Longest word in the file: successfully.
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 4
Exiting program.
Result:
Thus the Implementing real-time/technical applications using File handling. (copy from one file toanother,
word count, longest word) result was obtained
Aim:
Implement real-time/technical applications using exception handling to handle divide by zero errors, validate
voter's age, and validate student mark ranges.
Algorithm:
1. Define functions for each operation: division with error handling, voter's age validation, and student
mark range validation.
2. Use try-except blocks to catch specific exceptions raised during the execution of operations.
3. Implement logic to check if the input satisfies the conditions (e.g., age >= 18 for voting, marks within
a valid range).
4. Raise custom exceptions with meaningful error messages when input does not meet the criteria.
5. Display appropriate outputs or error messages based on the result of exception handling.
Program:
# Function to handle division with error handling
def divide(dividend, divisor):
try:
result = dividend / divisor
return result
except ZeroDivisionError:
raise ZeroDivisionError("Error: Division by zero is not allowed.")
def main():
while True:
print("\nMenu:")
print("1. Divide numbers with error handling")
print("2. Validate voter's age")
print("3. Validate student mark range")
print("4. Exit")
if choice == '1':
try:
dividend = float(input("Enter dividend: "))
divisor = float(input("Enter divisor: "))
print("Result:", divide(dividend, divisor))
except ValueError:
print("Error: Please enter valid numeric values.")
elif choice == '2':
try:
age = int(input("Enter voter's age: "))
validate_voter_age(age)
except ValueError:
print("Error: Please enter a valid age.")
elif choice == '3':
try:
mark = float(input("Enter student mark: "))
validate_mark_range(mark)
except ValueError:
print("Error: Please enter a valid mark.")
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 1
Enter dividend: 10
Enter divisor: 0
Error: Division by zero is not allowed.
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 2
Enter voter's age: 16
Error: Voter must be 18 years or older.
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 3
Enter student mark: 110
Error: Mark should be between 0 and 100.
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 1
Enter dividend: 20
Enter divisor: abc
Error: Please enter valid numeric values.
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 4
Exiting program.
Result:
Thus, the Implementing real-time/technical applications using Exception handling.
Aim:
To Implement real-time/technical applications using exception handling to handle divide by zero errors,
validate voter's age, and validate student mark ranges.
Algorithm:
1. Define functions for each operation: division with error handling, voter's age validation, and student
mark range validation.
2. Use try-except blocks to catch specific exceptions raised during the execution of operations.
3. Implement logic to check if the input satisfies the conditions (e.g., age >= 18 for voting, marks within
a valid range).
4. Raise custom exceptions with meaningful error messages when input does not meet the criteria.
5. Display appropriate outputs or error messages based on the result of exception handling.
Program:
try:
return result
except ZeroDivisionError:
def validate_voter_age(age):
try:
else:
print(ve)
# Function to validate student mark range
def validate_mark_range(mark):
try:
else:
print(ve)
def main():
while True:
print("\nMenu:")
print("4. Exit")
if choice == '1':
try:
except ValueError:
validate_voter_age(age)
except ValueError:
try:
validate_mark_range(mark)
except ValueError:
print("Exiting program.")
break
else:
if __name__ == "__main__":
main()
Output:
Menu:
4. Exit
Enter dividend: 10
Enter divisor: 0
Menu:
4. Exit
Menu:
4. Exit
Menu:
4. Exit
Enter dividend: 20
Enter divisor: abc
Menu:
4. Exit
Exiting program.
Result:
Thus the implementation of voter’s age using Exception Handling and result was obtained.
Program for Exploratory Data Analysis
Aim: Perform exploratory data analysis (EDA) on an email dataset. Export all emails as a dataset, import
them into a pandas DataFrame, visualize them, and extract insights from the data.
Algorithm:
Program:
python
import pandas as pd
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
df['Sender'].value_counts().head(10).plot(kind='bar', color='lightgreen')
plt.title('Top 10 Most Frequent Senders')
plt.xlabel('Sender')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.show()
# Extract insights
print("\nInsights:")
print("Total number of emails:", df.shape[0])
print("Total number of unique senders:", df['Sender'].nunique())
print("Total number of unique recipients:", df['Recipient'].nunique())
print("Average number of emails per sender:", df['Sender'].value_counts().mean())
print("Average number of emails per recipient:", df['Recipient'].value_counts().mean())
# Main function
def main():
email_dataset = "email_dataset.csv" # Replace with the path to your email dataset
perform_eda(email_dataset)
if __name__ == "__main__":
main()
Label
0 Spam
1 Ham
2 Ham
3 Spam
4 Ham
Insights:
Total number of emails: 1000
Total number of unique senders: 20
Total number of unique recipients: 20
Average number of emails per sender: 50.0
Average number of emails per recipient: 50.0
Result:
Thus the implementation to perform the Perform exploratory data analysis (EDA) on with datasets like
email data set and output was obtained
Program for Numpy Array
Aim:
To Perform various operations with NumPy arrays including appending values to the end of an array,
extracting real and imaginary parts of an array of complex numbers, listing the second column elements
from a shape of (3,3) array, and finding the maximum and minimum values from the shape of a (3,3) array.
Algorithm:
Program:
import numpy as np
# Find the maximum and minimum value from the shape of (3,3) array
max_value = np.max(array2)
min_value = np.min(array2)
print("\nMaximum value:", max_value)
print("Minimum value:", min_value)
# Main function
def main():
numpy_operations()
if __name__ == "__main__":
main()
Output:
Appended array: [1 2 3 4 5 6]
Maximum value: 9
Minimum value: 1
Result:
Thus the implementation of Numpy was executed successfully and result was obtained.
Aim:
To Work with Pandas Data Frame to perform operations such as sorting the DataFrame by multiple columns,
selecting rows based on certain conditions, appending a new row to the DataFrame, and then deleting that
newly appended row to return the original DataFrame.
Algorithm:
Program:
import pandas as pd
# Sort the DataFrame by 'name' in descending order, then by 'score' in ascending order
df_sorted = df.sort_values(by=['name', 'score'], ascending=[False, True])
print("DataFrame sorted by 'name' in descending order, then by 'score' in ascending order:")
print(df_sorted)
# Select rows where the number of attempts in the examination is greater than 2
df_attempts_gt_2 = df[df['attempts'] > 2]
print("\nRows where the number of attempts in the examination is greater than 2:")
print(df_attempts_gt_2)
# Delete the newly appended row and return the original DataFrame
df_original = df_with_new_row.drop(index=df_with_new_row[df_with_new_row['name'] ==
'Kate'].index)
print("\nOriginal DataFrame after deleting the newly appended row:")
print(df_original)
# Main function
def main():
pandas_operations()
if __name__ == "__main__":
main()
output:
DataFrame sorted by 'name' in descending order, then by 'score' in ascending order:
name score attempts
0 Emma 95 5
3 David 68 1
2 Charlie 90 4
1 Bob 82 2
4 Alice 75 3
Result:
Thus the program for implementation of working with Pandas Data Frames.
10.1. Write a Python programming to display a horizontal bar chart of the popularity of
programming Languages.
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
AIM:
To write a python program to display a horizontal bar chart using matplotlib.
ALGORITHM :
PROGRAM :
# Create a list of x positions for each bar using the range function
x_pos = range(len(languages))
# Plot the bars using the plt.barh function, passing the x positions, the popularity, and the labels as
arguments
plt.barh(x_pos, popularity, tick_label=languages)
# Add some labels and a title to the chart using the plt.xlabel, plt.ylabel, and plt.title functions
plt.xlabel('Popularity')
plt.ylabel('Languages')
plt.title('Popularity of Programming Languages')
# Show the chart using the plt.show function
plt.show()
OUTPUT:
RESULT:
Thus the program is executed successfully and output is verified.
10.2 Write a Python program to draw a scatter plot comparing two subject marks of
Mathematicsand Science. Use marks of 10 students.
Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
AIM:
To Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and
Science.
ALGORITHM:
Two random variables are taken with random values. The scatter function plots a scatter plot.
The scatter function takes 2 arguments and a label variable gives the label to the plot.
To name the axes X-axis and Y-axis functions are used and to give the title to the plot the title
function is used.
To show the legend the legend function is used and finally to show the plot the show function.
PROGRAM:
RESULT:
Thus the program is executed successfully and output is verified.
10.2 .Write a Python programming to create a pie chart of gold medal achievements of five
mostsuccessful countries in 2016 Summer Olympics. Read the data from a csv file.
Sample data:
medal.csv
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17
AIM:
To Write a Python programming to create a pie chart of gold medal achievements of five most successful
countries in 2016 Summer Olympics.
ALGORITHM:
1. Create a CSV file (let’s call it medal.csv) with the following structure:
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17
2. The first column represents the country names, and the second column represents the
number of gold medals each country won.
3.We use pandas to read the data from the CSV file.
4.The plt.pie() function creates the pie chart, and we customize it with colors, explode effect,
and other parameters.