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

Part_B

The document contains multiple programming tasks including a calculator program, selection sort implementation, exception handling demonstration, and usage of dictionaries and tuples. It also includes examples of drawing charts with matplotlib, performing array operations with NumPy, and creating a DataFrame from an Excel sheet using pandas. Each section provides code snippets and explanations for the respective functionalities.
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)
5 views

Part_B

The document contains multiple programming tasks including a calculator program, selection sort implementation, exception handling demonstration, and usage of dictionaries and tuples. It also includes examples of drawing charts with matplotlib, performing array operations with NumPy, and creating a DataFrame from an Excel sheet using pandas. Each section provides code snippets and explanations for the respective functionalities.
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
You are on page 1/ 4

PART-B

1) Create a calculator program

def add(x, y):


return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:

choice = input("Enter choice(1/2/3/4): ")

if choice in ('1', '2', '3', '4'):


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
n = input("continue for next calculation (yes/no): ")
if n == "no":
break
else:
print("Invalid Input")

2) Implement selection sort

def selection_sort(array):
length = len(array)
for i in range(length - 1):
minInd = i
for j in range(i + 1, length):
if array[j] < array[minInd]:
minInd = j
array[i], array[minInd] = array[minInd], array[i]
return array

array = [67, 6, 98, 33, 388]


print("The sorted array is: ", selection_sort(array))

3) Demonstrate exception handling

try:
numerator = int(input("enter numerator value :"))
denominator = int(input("enter denominator value :"))
result = numerator/denominator
except ZeroDivisionError:
print("Error: Denominator cannot be 0.")
else: print(result)
finally:
print("This is finally block.")

4) Demonstrate use of Dictionaries.

# Create a dictionary
student = {
"name": "Smith",
"age": 20,
"university": "ABC University",
"major": "Computer Science"
}
# Accessing dictionary values
print("Name:", student["name"])
print("Age:", student["age"])
print("University:", student["university"])
print("Major:", student["major"])
# Modifying dictionary values
student["age"] = 21
student["university"] = "XYZ University"
print("Modified Dictionary:")
print(student)
# Adding a new key-value pair
student["gpa"] = 3.8
print("Updated Dictionary:")
print(student)
# Removing a key-value pair
del student["major"]
print("Dictionary after removing 'major' key:")
print(student)
# Iterating over dictionary keys
print("Dictionary Keys:")
for key in student.keys():
print(key)
# Iterating over dictionary values
print("Dictionary Values:")
for value in student.values():
print(value)
#Iterating over dictionary key-value pairs
print("Dictionary Key-Value Pairs:")
for key, value in student.items():
print(key + ":", value)
5) Demonstrate use of Tuples

# Creating a tuple
f = ("apple", "banana", "orange", "kiwi")
# Accessing tuple elements
print("First fruit:", f[0])
print("Second fruit:", f[1])
# Iterating over a tuple
print("All fruits:")
for fruit in f:
print(fruit)
# Concatenating tuples
more_fruits = ("grape", "mango")
all_fruits = f + more_fruits
print("All fruits combined:")
print(all_fruits)
# Tuple unpacking
a, b, c, d, e, f = all_fruits
print("Unpacked variables:")
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

6) Drawing Line and bar chart using matplotlib.

import matplotlib.pyplot as plt


# Data for the line chart
years = [2010, 2012, 2014, 2016, 2018, 2020]
population = [1123, 1274, 1390, 1523, 1680, 1800]
# Data for the bar chart
fruits = ["Apple", "Banana", "Orange", "Grape"]
quantity = [25, 40, 30, 35]
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
# Line chart - subplot 1
ax1.plot(years, population, marker='o')
ax1.set_title("Population Growth")
ax1.set_xlabel("Year")
ax1.set_ylabel("Population (in billions)")
# Bar chart - subplot 2
ax2.bar(fruits, quantity,color='red')
ax2.set_title("Fruit Quantities")
ax2.set_xlabel("Fruits")
ax2.set_ylabel("Quantity")
# Adjust spacing between subplots
plt.tight_layout()
# Display the chart
plt.show()
7) Create array using NumPy and perform array operations

import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Display the array
print("Original Array:")
print(arr)
# Perform array operations
# Calculate the sum of the array
arr_sum = np.sum(arr)
# Calculate the mean of the array
arr_mean = np.mean(arr)
# Calculate the maximum value in the array
arr_max = np.max(arr)
# Calculate the minimum value in the array
arr_min = np.min(arr)
# Display the results
print("Sum of the array:", arr_sum)
print("Mean of the array:", arr_mean)
print("Maximum value in the array:", arr_max)
print("Minimum value in the array:", arr_min)

8) Create data frame from excel sheet and perform simple operations.

import pandas as pd
# Read Excel sheet into a DataFrame
df = pd.read_excel("C:/Users/hp/Desktop/Book1.xlsx",sheet_name='Value')
# Display the DataFrame
print("Original DataFrame:")
print(df)
# Perform simple operations on the DataFrame
# Calculate the sum of a column
column_sum = df['data'].sum()
# Calculate the mean of a column
column_mean = df['data'].mean()
# Calculate the maximum value in a column
column_max = df['data'].max()
# Calculate the minimum value in a column
column_min = df['data'].min()
# Display the results
print("Sum of 'data' column:", column_sum)
print("Mean of 'data' column:", column_mean)
print("Maximum value in 'data' column:", column_max)
print("Minimum value in 'data' column:", column_min)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy