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

Write a python program to implement the arithmetic operations for the following

This document is a lab record for a Python Programming Lab (CAD 7127) submitted by Dejasvini G for the Semester End Practical Examinations. It includes a bonafide certificate, an index of various programming exercises, and detailed procedures and source code for each exercise covering topics such as arithmetic operations, conditional statements, crowd computing, game development, and list functionalities. The document serves as a comprehensive record of the practical work completed during the semester.

Uploaded by

g.dejasvini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Write a python program to implement the arithmetic operations for the following

This document is a lab record for a Python Programming Lab (CAD 7127) submitted by Dejasvini G for the Semester End Practical Examinations. It includes a bonafide certificate, an index of various programming exercises, and detailed procedures and source code for each exercise covering topics such as arithmetic operations, conditional statements, crowd computing, game development, and list functionalities. The document serves as a comprehensive record of the practical work completed during the semester.

Uploaded by

g.dejasvini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

CENTRE FOR DISTANCE AND ONLINE EDUCATION

LAB RECORD

NAME : ______Dejasvini G______

RRN : _____22211016_____

LAB : _____CAD 7127______


CENTRE FOR DISTANCE AND ONLINE EDUCATION

DEPARTMENT OF COMPUTER APPLICATIONS

CAD 7127–Python Programming Lab


( III SEMESTER)
CENTRE FOR DISTANCE AND ONLINE EDUCATION
BONAFIDE CERTIFICATE

This is a Certified Record Book of ________Dejasvini G_______RRN:

______22211016_______ submitted for the Semester End Practical

Examinations held on ___15-03-2024___, for the CAD 7127–Python Lab

during 2023-2024.

---------------------------------------
Signature of LAB In-Charge
INDEX

Page
Ex.No Date Program Title Sign
No.

Write a python program to implement the arithmetic operations


for the following:
1 20.10.23  Addition  Subtraction  Multiplication  Modulus  Floor
6
Division
Write a python program to implement the conditional statement
for the following:
 Fibonacci number series.
2 01.11.23 8
 Incorporate FIZZ for any number divisible by 3 and Buzz for
any number divisible for 5 and FIZZBUZZ for any number
divisible by 3 and 5 as well
Write a python program to implement the crowd computing
using the array concept for the following scenario.
 To collect approximate cost for a material or object and store
3 15.11.23 the same in the array. Remove first and last 10 % of the listed 10
cost from the array and compute the mean value of the array
items

Write a python program to implement looping concept,


4 27.11.23 conditional statement and function to build a game called 12
jumbled word.
Write a python program to implement random module to
randomly generate 50 birth dates and find how many of them
5 17.12.23 14
have same day of the year.

List Programs(Python Lists & its Functionality)


 Display of List with elements.
 Finding the range of the Lists.
6 27.12.23  Indexing in the Lists (Including Negative Indexing). 16
 Use of Loop in the Lists.
 Adding, removing and Joining two Lists

Tuple Programs(Python Tuple & its Functionality)


 Creation of Tuple with values.
 Finding the range of the Tuple.
7 05.01.24  Indexing in the Tuple (Including Negative Indexing). 19
 Use of Loop in the Tuple.
 Adding, removing and Joining two Tuple

.Dictionary Programs(Python Dictionary& its Functionality)


 Display of unordered elements.
 Accessing the elements in the dictionary.
8 11.01.24 22
 Use of Loop in the Dictionary.
 Adding, removing and Joining two Dictionary
Write a python program to convert speech to text.
9 18.01.24 25

Write a python program to create a game “MONTE HALL _ 3 -


DOORS AND A TWIST”. This comprises of three doors. In
10 30.01.24 which two doors contain GOAT and one door contain BMW. 27
User has to pick his/her choice of door. If the choice of door
contains BMW then user WINS otherwise LOST
Write a python program to implement visualization concept to
11 19.02.24 plot the values in a chart with x-axis and y-axis. 29

Write a python program using pandas library to perform the


following operation.
 Create DataFrame
12 29.02.24  Manipulate the values in DataFrame 31
 Barcharts
 Pie Charts
 Scatter Plots
1.Write a python program to implement the arithmetic operations for the following:
 Addition  Subtraction  Multiplication  Modulus  Floor Division

Aim:
Write a python program to implement the arithmetic operations for the following:
 Addition  Subtraction  Multiplication  Modulus  Floor Division

Procedure:
Addition:
 Accept two numbers, num1 and num2.
 Calculate the sum by adding num1 and num2.
 Return the result.
Subtraction:
 Accept two numbers, num1 and num2.
 Calculate the difference by subtracting num2 from num1.
 Return the result.
Multiplication:
 Accept two numbers, num1 and num2.
 Calculate the product by multiplying num1 and num2.
 Return the result.
Modulus:
 Accept two numbers, num1 and num2.
 Calculate the remainder when num1 is divided by num2.
 Return the result.
Floor Division:
 Accept two numbers, num1 and num2.
 Calculate the integer division of num1 by num2.
 Return the result.

Source code:
def addition(x, y):
return x + y

def subtraction(x, y):


return x - y

def multiplication(x, y):


return x * y

def modulus(x, y):


return x % y

def floor_division(x, y):


return x // y

# Example usage:
num1 = 10
num2 = 3

print("Addition:", addition(num1, num2))


print("Subtraction:", subtraction(num1, num2))
print("Multiplication:", multiplication(num1, num2))
print("Modulus:", modulus(num1, num2))
print("Floor Division:", floor_division(num1, num2))

Output:
2.Write a python program to implement the conditional statement for the following:
 Fibonacci number series.
 Incorporate FIZZ for any number divisible by 3 and Buzz for any number divisible for 5 and
FIZZBUZZ for any number divisible by 3 and 5 as well.

Aim:
Write a python program to implement the conditional statement for the following:
 Fibonacci number series.
 Incorporate FIZZ for any number divisible by 3 and Buzz for any number divisible for 5 and
FIZZBUZZ for any number divisible by 3 and 5 as well.

Procedure:
Fibonacci number series:
 Accept an integer n as input, specifying the number of terms in the Fibonacci series.
 Initialize variables a and b with values 0 and 1, respectively, to represent the first two
terms of the Fibonacci series.
Iterate n times:
 Calculate the next term in the Fibonacci series by adding a and b.
 Update a and b with the last two terms.
 Print or store the current term as part of the Fibonacci series.
FIZZBUZZ problem:
 Accept an integer n as input, specifying the range of numbers to check.
Iterate from 1 to n:
 Check if the current number is divisible by both 3 and 5.
 If it is divisible by both, print "FIZZBUZZ".
 If it is divisible by only 3, print "FIZZ".
 If it is divisible by only 5, print "BUZZ".
Otherwise, print the current number itself.

Source:
def fibonacci(n):
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series

def fizz_buzz_fizzbuzz(n):
result = []
for num in range(1, n+1):
if num % 3 == 0 and num % 5 == 0:
result.append("FIZZBUZZ")
elif num % 3 == 0:
result.append("FIZZ")
elif num % 5 == 0:
result.append("BUZZ")
else:
result.append(num)
return result

# Example usage:
n = 15
fib_series = fibonacci(n)
print("Fibonacci series:", fib_series)

fizz_buzz_fizzbuzz_result = fizz_buzz_fizzbuzz(n)
print("FIZZ, BUZZ, FIZZBUZZ series:", fizz_buzz_fizzbuzz_result)

Output:
3.Write a python program to implement the crowd computing using the array concept for the
following scenario.
 To collect approximate cost for a material or object and store the same in the array.
Remove first and last 10 % of the listed cost from the array and compute the mean value of
the array items

Aim:
Write a python program to implement the crowd computing using the array concept for the
following scenario.
 To collect approximate cost for a material or object and store the same in the array.
Remove first and last 10 % of the listed cost from the array and compute the mean value of
the array items

Procedure:
Collect approximate costs for materials or objects:
 Accept a list of costs as input.
 Store the costs in an array or list.
Remove the first and last 10% of the listed costs:
 Calculate the number of items to remove by taking 10% of the length of the list.
 Remove the first and last num_items_to_remove elements from the list.
Compute the mean value of the array items:
 Sum all the remaining values in the list.
 Divide the sum by the number of remaining items in the list to calculate the mean
value.
 Return the mean value as the result.

Source code:
def compute_mean_cost(cost_list):
# Calculate the number of items to remove (10% from both ends)
num_items_to_remove = int(len(cost_list) * 0.1)

# Remove the first and last 10% of the listed costs


trimmed_list = cost_list[num_items_to_remove:-num_items_to_remove]

# Compute the mean value of the remaining array items


mean_cost = sum(trimmed_list) / len(trimmed_list)

return mean_cost

# Example usage:
cost_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
mean_cost = compute_mean_cost(cost_list)
print("Mean cost after removing first and last 10%:", mean_cost)
Output:
4.Write a python program to implement looping concept, conditional statement and function
to build a game called jumbled word.

Aim:
Write a python program to implement looping concept, conditional statement and function to
build a game called jumbled word.

Procedure:
Choose a word for the game:
 Prepare a list of words to choose from.
 Randomly select a word from the list.
Jumble the selected word:
 Shuffle the characters of the selected word to create a jumbled word.
Display instructions and jumbled word to the player:
 Print instructions for the game.
 Display the jumbled word to the player.
Accept user input:
 Prompt the player to guess the original word based on the jumbled word.
Check the player's guess:
 Compare the player's guess with the original word.
 If the guess is correct, congratulate the player.
 If the guess is incorrect, inform the player and provide the option to try again.
Allow the player to play again:
 Ask the player if they want to play another round.
 If yes, repeat the process from step 1.
 If no, end the game with a farewell message.

Source code:
import random
def choose_word():
words = ['python', 'programming', 'computer', 'algorithm', 'variable']
return random.choice(words)

def jumble_word(word):
jumbled = list(word)
random.shuffle(jumbled)
return ''.join(jumbled)

def play_game():
word = choose_word()
jumbled = jumble_word(word)

print("Welcome to the Jumbled Word Game!")


print("Unscramble the word:", jumbled)

guess = input("Your guess: ")

if guess == word:
print("Congratulations! You guessed the word correctly.")
else:
print("Sorry, the correct word was:", word)
# Main loop to allow playing multiple games
while True:
play_game()
play_again = input("Do you want to play again? (yes/no): ")
if play_again.lower() != 'yes':
break

print("Thanks for playing!")

Output:
5.Write a python program to implement random module to randomly generate 50 birth dates
and find how many of them have same day of the year.

Aim:
Write a python program to implement random module to randomly generate 50 birth dates
and find how many of them have same day of the year.

Procedure:
Generate 50 random birth dates:
 Initialize an empty list to store the birth dates.
Iterate 50 times:
 Generate a random day of the year (1 to 365).
 Append the generated day to the list of birth dates.
Count the occurrences of each day of the year:
 Initialize a dictionary to store the count of each day of the year.
Iterate through the list of birth dates:
 Check if the day is already in the dictionary.
 If it is, increment the count for that day.
 If it is not, add the day to the dictionary with a count of 1.
Find the number of birth dates with the same day of the year:
 Iterate through the dictionary of day counts.
 Count the number of days with a count greater than 1.

Source code:
import random
from collections import Counter

def generate_birth_dates(num_dates):
birth_dates = []
for _ in range(num_dates):
month = random.randint(1, 12)
if month in [1, 3, 5, 7, 8, 10, 12]:
day = random.randint(1, 31)
elif month in [4, 6, 9, 11]:
day = random.randint(1, 30)
else:
day = random.randint(1, 28) # Assuming February has 28 days
birth_dates.append((month, day))
return birth_dates

def count_same_day(birth_dates):
day_of_year = [(date[0], date[1]) for date in birth_dates]
counts = Counter(day_of_year)
same_day_count = sum(1 for count in counts.values() if count > 1)
return same_day_count

# Generate 50 birth dates


birth_dates = generate_birth_dates(50)

# Count how many of them have the same day of the year
same_day_count = count_same_day(birth_dates)

print("Out of 50 birth dates, {} have the same day of the year.".format(same_day_count))


Output:
6.List Programs(Python Lists & its Functionality)
 Display of List with elements.
 Finding the range of the Lists.
 Indexing in the Lists (Including Negative Indexing).
 Use of Loop in the Lists.
 Adding, removing and Joining two Lists

Aim:
List Programs(Python Lists & its Functionality)
 Display of List with elements.
 Finding the range of the Lists.
 Indexing in the Lists (Including Negative Indexing).
 Use of Loop in the Lists.
 Adding, removing and Joining two Lists

Procedure:
Display of List with elements:
 Iterate through each element in the list.
 Print or display each element.
Finding the range of the Lists:
 Find the minimum and maximum values in the list using min() and max() functions.
 Calculate the range by subtracting the minimum value from the maximum value.
Indexing in the Lists (Including Negative Indexing):
 Access elements by their index in the list.
 Use positive indices to access elements from the beginning of the list.
 Use negative indices to access elements from the end of the list.
Use of Loop in the Lists:
 Iterate through each element in the list using a loop.
 Perform operations or print/display each element within the loop.
Adding, removing, and Joining two Lists:
 To add elements to a list, use the append() method to add elements one by one, or
use the extend() method to add elements from another list.
 To remove elements from a list, use the remove() method to remove a specific
element, or use the pop() method to remove an element by index.
 To join two lists, you can use the + operator to concatenate two lists or use the
extend() method to add elements from one list to another.

Source code:

 Display of List with elements.

my_list = [1, 2, 3, 4, 5]
print("List with elements:", my_list)

Output:
 Finding the range of the Lists.

my_list = [1, 2, 3, 4, 5]
list_range = max(my_list) - min(my_list)
print("Range of the list:", list_range)

Output:

 Indexing in the Lists (Including Negative Indexing).

my_list = ['a', 'b', 'c', 'd', 'e']


print("First element:", my_list[0])
print("Last element:", my_list[-1])

Output:

 Use of Loop in the Lists.

my_list = [1, 2, 3, 4, 5]
print("Elements of the list using a loop:")
for element in my_list:
print(element)

Output:
 Adding, removing and Joining two Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Adding two lists


added_list = list1 + list2
print("Added lists:", added_list)

# Removing an element from the list


list1.remove(2)
print("List1 after removing element:", list1)

# Joining two lists


joined_list = list1.extend(list2)
print("Joined lists:", list1)

Output:
7.Tuple Programs(Python Tuple & its Functionality)
 Creation of Tuple with values.
 Finding the range of the Tuple.
 Indexing in the Tuple (Including Negative Indexing).
 Use of Loop in the Tuple.
 Adding, removing and Joining two Tuple

Aim:
Tuple Programs(Python Tuple & its Functionality)
 Creation of Tuple with values.
 Finding the range of the Tuple.
 Indexing in the Tuple (Including Negative Indexing).
 Use of Loop in the Tuple.
 Adding, removing and Joining two Tuple

Procedure:
Creation of Tuple with values:
 Initialize a tuple with values enclosed within parentheses.
Finding the range of the Tuple:
 Find the minimum and maximum values in the tuple using min() and max()
functions.
 Calculate the range by subtracting the minimum value from the maximum value.
Indexing in the Tuple (Including Negative Indexing):
 Access elements by their index in the tuple.
 Use positive indices to access elements from the beginning of the tuple.
 Use negative indices to access elements from the end of the tuple.
Use of Loop in the Tuple:
 Iterate through each element in the tuple using a loop.
 Perform operations or print/display each element within the loop.
Adding, removing, and Joining two Tuple:
 Tuples are immutable, so you cannot add or remove elements from a tuple after
creation.
 To join two tuples, you can use the + operator to concatenate two tuples.

Source code:
 Creation of Tuple with values.

my_tuple = (1, 2, 3, 4, 5)
print("Tuple with values:", my_tuple)

output:
 Finding the range of the Tuple.
my_tuple = (1, 2, 3, 4, 5)
tuple_range = max(my_tuple) - min(my_tuple)
print("Range of the tuple:", tuple_range)

Output:

 Indexing in the Tuple (Including Negative Indexing).

my_tuple = ('a', 'b', 'c', 'd', 'e')


print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])

output:

 Use of Loop in the Tuple.

my_tuple = (1, 2, 3, 4, 5)
print("Elements of the tuple using a loop:")
for element in my_tuple:
print(element)

output:

 Adding, removing and Joining two Tuple


tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Adding two tuples


added_tuple = tuple1 + tuple2
print("Added tuples:", added_tuple)

# Removing an element from the tuple is not possible as tuples are immutable

# Joining two tuples


joined_tuple = tuple1 + tuple2
print("Joined tuples:", joined_tuple)

output:

8.Dictionary Programs(Python Dictionary& its Functionality)


 Display of unordered elements.
 Accessing the elements in the dictionary.
 Use of Loop in the Dictionary.
 Adding, removing and Joining two Dictionary

Aim:
Dictionary Programs(Python Dictionary& its Functionality)
 Display of unordered elements.
 Accessing the elements in the dictionary.
 Use of Loop in the Dictionary.
 Adding, removing and Joining two Dictionary

Procedure:
Display of unordered elements:
 Iterate through the dictionary.
 Print or display key-value pairs.
Accessing the elements in the dictionary:
 Use keys to access corresponding values in the dictionary.
Use of Loop in the Dictionary:
 Iterate through the keys, values, or key-value pairs in the dictionary using a loop.
 Perform operations or print/display each element within the loop.
Adding, removing, and Joining two Dictionary:
 To add or update elements in a dictionary, use the assignment operator (=) to assign
values to keys
 To remove elements from a dictionary, use the del keyword or the pop() method.
 To join two dictionaries, use the update() method to add key-value pairs from one
dictionary to another.

Source code:
 Display of unordered elements.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


print("Dictionary with unordered elements:", my_dict)

output:

 Accessing the elements in the dictionary.


my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print("Name:", my_dict['name'])
print("Age:", my_dict['age'])

output:

 Use of Loop in the Dictionary.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


print("Key-value pairs in the dictionary:")
for key, value in my_dict.items():
print(key, ":", value)

output:

 Adding, removing and Joining two Dictionary

dict1 = {'a': 1, 'b': 2}


dict2 = {'c': 3, 'd': 4}

# Adding two dictionaries


added_dict = {**dict1, **dict2}
print("Added dictionaries:", added_dict)

# Removing an element from the dictionary


del dict1['a']
print("Dict1 after removing 'a':", dict1)

# Joining two dictionaries


joined_dict = dict1.copy()
joined_dict.update(dict2)
print("Joined dictionaries:", joined_dict)

output:
9.Write a python program to convert speech to text.
Aim:
Write a python program to convert speech to text.

Procedure:
Initialize the speech recognition system:
 Import the speech_recognition library.
Create a recognizer object:
 Instantiate a recognizer object from the Recognizer class.
Capture audio from the microphone:
 Use the Microphone class to capture audio input from the microphone.
 Use the listen() method of the recognizer object to capture the audio input.
Recognize speech using Google Speech Recognition:
 Use the recognize_google() method of the recognizer object to convert the captured
audio into text.
 Pass the captured audio as input to the recognize_google() method.
Handle exceptions:
 Use try and except blocks to handle any exceptions that may occur during speech
recognition.
 Catch UnknownValueError if the recognizer is unable to understand the audio input.
 Catch RequestError if there is an issue with the Google Speech Recognition
service.

Source code:
import speech_recognition as sr

def convert_speech_to_text():
# Initialize recognizer
recognizer = sr.Recognizer()

# Capture audio from the microphone


with sr.Microphone() as source:
print("Please start speaking...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)

try:
# Recognize speech using Google Speech Recognition
print("Recognizing...")
text = recognizer.recognize_google(audio)
print("You said:", text)
except sr.UnknownValueError:
print("Sorry, I couldn't understand what you said.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service;
{0}".format(e))

# Call the function to convert speech to text


convert_speech_to_text()

output:
Please start speaking...
Recognizing...
You said: Hello, how are you doing today?

10.Write a python program to create a game “MONTE HALL _ 3 - DOORS AND A TWIST”.
This comprises of three doors. In which two doors contain GOAT and one door contain
BMW. User has to pick his/her choice of door. If the choice of door contains BMW then user
WINS otherwise LOST

Aim:
Write a python program to create a game “MONTE HALL _ 3 - DOORS AND A TWIST”. This
comprises of three doors. In which two doors contain GOAT and one door contain BMW.
User has to pick his/her choice of door. If the choice of door contains BMW then user WINS
otherwise LOST

Procedure:
Initialize the game:
 Set up three doors, one containing a BMW (prize) and the other two containing
goats.
 Randomly assign the prize (BMW) behind one of the doors.
Display instructions to the player:
 Print instructions explaining the game to the player.
Accept user input:
 Prompt the player to choose one of the three doors.
Reveal a goat:
 Randomly select one of the doors that doesn't contain the prize (BMW) and reveal
that it contains a goat.
Offer the player a choice:
 Ask the player if they want to switch their choice to the other unopened door or stick
with their original choice.
Determine the outcome:
 If the player's final choice matches the door containing the prize (BMW), the player
wins.
 If the player's final choice does not match the door containing the prize (BMW), the
player loses.
Display the result:
 Print a message indicating whether the player won or lost.

Source code:
import random

def monty_hall_game():
doors = ['GOAT', 'GOAT', 'BMW']
random.shuffle(doors)

print("Welcome to the Monty Hall game!")


print("There are 3 doors: Behind one door is a BMW, behind the others, goats.")

# Let the user pick a door


while True:
try:
user_choice = int(input("Choose a door (1, 2, or 3): "))
if user_choice in [1, 2, 3]:
break
else:
print("Invalid choice. Please choose a number between 1 and 3.")
except ValueError:
print("Invalid input. Please enter a number.")

# Reveal a goat behind one of the other doors


revealed_door = None
for i in range(3):
if i + 1 != user_choice and doors[i] == 'GOAT':
revealed_door = i + 1
break

print(f"We reveal a goat behind door {revealed_door}.")

# Give the user the option to switch doors


switch_door = input("Do you want to switch doors? (yes/no): ").lower().strip()
if switch_door == 'yes':
user_choice = next(i + 1 for i in range(3) if i + 1 not in [user_choice, revealed_door])

# Determine if the user won


if doors[user_choice - 1] == 'BMW':
print("Congratulations! You won the BMW!")
else:
print("Sorry, you lost. Better luck next time!")

# Play the game


monty_hall_game()

output:

11.Write a python program to implement visualization concept to plot the values in a chart
with x-axis and y-axis.
Aim:
Write a python program to implement visualization concept to plot the values in a chart with
x-axis and y-axis.

Procedure:

Import the necessary libraries:


 Import the required visualization library, such as Matplotlib, which is commonly used
for plotting in Python.
Prepare the data:
 Create lists or arrays for the x-axis and y-axis values that you want to plot.
Create the plot:
 Use the appropriate plotting function from the visualization library to create the
desired plot (e.g., line plot, scatter plot, bar chart, etc.).
 Pass the x-axis and y-axis values as arguments to the plotting function.
Customize the plot (optional):
 Customize the appearance of the plot by adding labels, titles, legends, gridlines,
colors, markers, etc.
 Use additional functions provided by the visualization library to customize the plot as
desired.
Display the plot:
 Use the appropriate function from the visualization library to display the plot.

Source Code:

import matplotlib.pyplot as plt


def plot_values(x_values, y_values):
plt.plot(x_values, y_values)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot of Values')
plt.show()
# Example values
x_values = [1, 2, 3, 4, 5]
y_values = [2, 4, 6, 8, 10]
# Plot the values
plot_values(x_values, y_values)

output:
12.Write a python program using pandas library to perform the following operation.
 Create DataFrame
 Manipulate the values in DataFrame
 Barcharts
 Pie Charts
 Scatter Plots

Aim:
Write a python program using pandas library to perform the following operation.
 Create DataFrame
 Manipulate the values in DataFrame
 Barcharts
 Pie Charts
 Scatter Plots

Procedure:
Import the necessary libraries:
 Import the Pandas library for data manipulation and analysis.
 Import the Matplotlib library for plotting.
Create DataFrame:
 Use the pd.DataFrame() constructor to create a DataFrame from data (e.g., lists,
dictionaries, arrays, etc.).
 Pass the data and optional parameters such as column names and index.
Manipulate the values in DataFrame:
 Access and modify DataFrame values using indexing and assignment.
Use DataFrame methods and functions to perform operations such as filtering, sorting,
aggregation, etc.
Barcharts:
 Use the plot() method of the DataFrame with kind='bar' to create a bar chart.
Customize the plot as needed using additional parameters and functions provided by
Matplotlib.
Pie Charts:
 Use the plot() method of the DataFrame with kind='pie' to create a pie chart.
Customize the plot as needed using additional parameters and functions provided by
Matplotlib.
Scatter Plots:
 Use the plot() method of the DataFrame with kind='scatter' to create a scatter plot.
Specify the x and y columns in the DataFrame to plot.
Customize the plot as needed using additional parameters and functions provided by
Matplotlib.

Source code:
import pandas as pd
import matplotlib.pyplot as plt

# Create DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 30, 35, 40, 45],
'Score': [80, 85, 90, 95, 100]}

df = pd.DataFrame(data)

print("DataFrame:")
print(df)
print()
# Manipulate the values in DataFrame
df['Age'] = df['Age'] + 5
df['Score'] = df['Score'] - 5

print("DataFrame after manipulation:")


print(df)
print()

# Bar chart
plt.figure(figsize=(8, 6))
plt.bar(df['Name'], df['Score'], color='skyblue')
plt.xlabel('Name')
plt.ylabel('Score')
plt.title('Bar Chart of Scores')
plt.show()

# Pie chart
plt.figure(figsize=(8, 6))
plt.pie(df['Age'], labels=df['Name'], autopct='%1.1f%%', startangle=140)
plt.axis('equal')
plt.title('Pie Chart of Ages')
plt.show()

# Scatter plot
plt.figure(figsize=(8, 6))
plt.scatter(df['Age'], df['Score'], color='green')
plt.xlabel('Age')
plt.ylabel('Score')
plt.title('Scatter Plot of Age vs Score')
plt.show()

Output:

You might also like