Write a python program to implement the arithmetic operations for the following
Write a python program to implement the arithmetic operations for the following
LAB RECORD
RRN : _____22211016_____
during 2023-2024.
---------------------------------------
Signature of LAB In-Charge
INDEX
Page
Ex.No Date Program Title Sign
No.
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
# Example usage:
num1 = 10
num2 = 3
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)
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)
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
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
# Count how many of them have the same day of the year
same_day_count = count_same_day(birth_dates)
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:
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:
Output:
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]
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:
output:
my_tuple = (1, 2, 3, 4, 5)
print("Elements of the tuple using a loop:")
for element in my_tuple:
print(element)
output:
# Removing an element from the tuple is not possible as tuples are immutable
output:
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.
output:
output:
output:
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()
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))
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)
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:
Source Code:
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
# 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: