PRACTICAL FILE
PROGRAM: MBA (BUSINESS ANALYTICS)
SEMESTER-II
ACADEMIC YEAR: 2024-
2025
SUBJECT: “INTRODUCTION TO PYTHON”
SUBJECT CODE: KMBA251
SUBMITTED BY: SUBMITTED TO:
SATENDRA DIWAKAR DR. SHWETA RAI
1
LIST OF EXPERIMENTS
Course Code: KMBA 251
Course Title: Introduction to Python
SN Name of the Experiment Page No. Signature
1 Start the Python interpreter and use it as a calculator.
• How many seconds are there in 42 minutes 42
seconds? 1
• How many miles are there in 10 kilometers? Hint:
there are 1.61 kilometers in a mile.
• If you run a 10 kilometer race in 42 minutes 42
seconds, What is your average speed in miles per
hour?
2 Write a python program to add two numbers. 1-2
3 Write a python program to swap two numbers 2
4 WAP to print a table of any given number. 2-3
5 WAP to find larger of two number. 3-4
6 a. Write a program to combine two lists into a dictionary.
8-9
7 Write a python program to read and write on CSV File. 10-11
8 Demonstrate Map() with Lambda Functions 11-12
Demonstrate Map() with Tuple
9 Write a python program to demonstrate array 12-13
characteristics using numpy
10 Write a Python program to demonstrate indexing in numpy 13
11 Write a Python program to demonstrate basic operations 14-15
on single array
12 Write a Python program to demonstrate binary operators 15-16
in Numpy
13 Write a Python program to demonstrate sorting in numpy 16
14 Write a Pandas program to create and display a one-
dimensional array-like object containing an array of 16-17
data
using Pandas module
2
15 Write a Pandas program to get the first 3 rows of a given
DataFrame.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima',
'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 21-22
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no',
'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
16 Write a Pandas program to create a dataframe and set a 27-28
title or name of the index column.
17 Write a Pandas program to join the two given dataframes 28-29
along rows and assign all data.
18 Write a Pandas program to create the todays date 37
19 Write a Pandas program to convert given datetime to 38-39
timestamp.
20 Write a Pandas program to create a line plot of the
historical stock prices of Alphabet Inc. between two 39-40
specific dates
21 Write a Pandas program to create a histograms plot of 42-43
opening, closing, high, low stock prices of Alphabet Inc.
between two specific dates.
22 Write a python program to demonstrate image processing 50-51
3
1
1. Start the Python interpreter and use it as a calculator.
• How many seconds are there in 42 minutes 42 seconds?
• How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers
in a mile. If you run a 10 kilometer race in 42 minutes 42 seconds, What is your
average speed in miles per hour?
Time_min = 42
Time_sec = 42
New_Time_sec = Time_min * 60 + Time_sec
print(New_Time_sec)
OUTPUT:
2. Write a python program to add two numbers.
num1 = int(input("Enter Number
1 : ")) num2 = int(input("Enter
Number 2 : ")) result = num1 +
num2
print("{0} + {1} = {2}".format(num1,num2,result))
OUTPUT:
2. Write a python program to multiple two numbers.
CODE:
num1 = int(input("Enter Number
1 : ")) num2 = int(input("Enter
Number 2 : "))
Result = num1 * num2
print("{0} * {1} = {2}".format (num1,num2,result))
OUTPUT:
1
2
3. Write a python program to swap two numbers
num1 = int(input("Enter Number
1 : ")) num2 = int(input("Enter
Number 2 : "))
print("Before swapping num1 = {0} num2 =
{1}".format(num1,num2)) temp = num1
num1 = num2
num2 = temp
print("After swapping num1 = {0} num2 = {1}".format(num1,num2))
OUTPUT:
4. WAP to print a table of any given number.
CODE:
#For Loop:-
n=int(input("Enter any
number")) for i in
range(1,11):
print(n,"x",i,"=",n*i)
OUTPUT:-
2
3
#While Loop:-
n=int(input("Enter any
number")) i=1
while i<11:
print(n,"x",i,"=",n*i
) i=i+1
OUTPUT:
5. WAP to find larger of two number.
CODE:
n1=int(input("Enter the 1
number")) n2=int(input("Enter
the 2 number")) if n1>n2:
print(n1,"is the largest
number") else:
print(n2,"is the largest number")
3
4
OUTPUT:
[Link] a program in python for a user define function diff which is use to function
diff num?
CODE:
def diff(num1, num2):
# calculate the absolute difference between num1 and
num2 diff = abs(num1 - num2)
# return the result
return diff
# example
usage result =
diff(10, 7)
print("The absolute difference between 10 and 7 is:", result)
OUTPUT:
2.a. Write a program to combine two lists into a dictionary.
CODE:
dat1 = ["Name","Age","City"]
dat2 = ["Andy",6,"Ohayo"]
my_dict =
dict(zip(dat1,dat2))
print(my_dict)
OUTPUT:
4
5
3. Write a python program to read and write on CSV
File. CODE:
import csv
# Open CSV file for writing
with open('my_data.csv', mode='w', newline='') as file:
writer = [Link](file)
# Write header row
[Link](['Name', 'Age', 'Country'])
# Write data rows
[Link](['Alice', 25, 'USA'])
[Link](['Bob', 30, 'Canada'])
[Link](['Charlie', 20, 'Australia'])
# Open CSV file for reading
with open('my_data.csv', mode='r') as file:
reader = [Link](file)
# Read header row
header =
next(reader)
# Print header
print(header)
# Read and print data
rows for row in reader:
print(row)
OUTPUT:
5
6
CODE: b.
# Define list of tuples
tuples = [(1, 2), (3, 4), (5,
6)]
# Define lambda function to sum the elements of a
tuple sum_tuple = lambda x: x[0] + x[1]
# Use map() with lambda function
sums = map(sum_tuple, tuples)
# Convert map object to list and print
print(list(sums))
OUTPUT:
4. Write a python program to demonstrate array characteristics using
numpy. CODE:
import numpy as np
arr =
[Link](1,11)
print("Array:","arr")
print("Number of dimension:",[Link])
print("Shape:",[Link])
print("Size:",[Link])
print("Data type:",[Link])
print("Maximum value:",[Link]())
print("Minimum value:",[Link]())
print("Sum:",[Link]())
print("Average:",[Link]())
OUTPUT:
6
7
[Link] a Python program to demonstrate indexing in NumPy.
CODE:
# Python program to
demonstrate # the use of
index arrays. import numpy as
np
# Create a sequence of integers
from # 10 to 1 with a step of -2
a = [Link](10, 1, -2)
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the [Link]
method. newarr = a[[Link]([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)
OUTPUT:
7
8
[Link] a Python program to demonstrate basic operations on single array.
CODE:
import numpy as np
# create a numpy array
arr=[Link]([1,2,3,4,5])
# basics operations on the array
print("original array:",arr)
# Addition
addition = arr + 2
print("Addition:",addition)
# Subtraction
subtraction = arr - 2
print("Subtraction array:",subtraction)
# Multiplication
multiplication = arr * 2
print("Multiplication:",multiplication)
# Division
division = arr / 2
print("Division:",division)
# Exponentiation
exponentiation = arr **
2
print("Exponentiation:",exponentiation)
# Square root
sqrt = [Link](arr)
print("Square root:",
sqrt) # Sum of all
elements
sum_of_elements = [Link](arr)
8
9
print("Sum_of_elements:",sum_of_elements)
# Minimum and Maximum
minimum = [Link](arr)
maximum = [Link](arr)
print("Minimum:",minimum)
print("Maximum:",maximum)
# Mean and Standard Deviation
mean = [Link](arr)
std_dev = [Link](arr)
print("Mean:",mean)
print("Standard deviation:",std_dev)
OUTPUT:
[Link] a Python program to demonstrate binary operators in Numpy.
CODE:
# Python program
explaining #
bitwise_and() function
import numpy as
np in_num1 = 10
in_num2 = 11
9
10
print ("Input number1 : ",
in_num1) print ("Input number2 :
", in_num2)
out_num = np.bitwise_and(in_num1, in_num2)
print ("bitwise_and of 10 and 11 : ",
out_num)
OUTPUT:
13. Write a Python program to demonstrate sorting in
numpy. CODE:
# Sort the array
import numpy as np
arr = [Link]([3, 2, 0, 1])
arr1 = [Link](['banana', 'cherry', 'apple'])
print([Link](arr))
print([Link](arr1))
# Sort a 2-D array
arr2 = [Link]([[3, 2, 4], [5, 0, 1]])
print([Link](arr2))
OUTPUT:
14. Write a Pandas program to create and display a one-dimensional array-like
object containing an array of data using Pandas module.
CODE:
import pandas as pd
10
11
# Create an array of data
data = [10, 20, 30, 40, 50]
# Create a Series using Pandas
series = [Link](data)
# Display the Series
print(series)
OUTPUT:
11
12
15. Write a Pandas program to get the first 3 rows of a given
DataFrame. Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CODE:
import pandas as pd
import numpy as np
# Define the dictionary data
exam_data = {
'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin',
'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
}
# Define the index labels
labels = ['a','b','c','d','e','f','g','h','i','j']
# Create a DataFrame from the dictionary with index labels
df = [Link](exam_data, index = labels)
# Get the first 3 rows of the DataFrame
first_three_rows = [Link](3)
# Display the first 3 rows
print(first_three_rows)
OUTPUT:
12
13
16. Write a Pandas program to create a dataframe and set a title or name of the
index column.
CODE:
import pandas as pd
# Create a
DataFrame data = {
'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
}
df = [Link](data)
# Set the name of the index column
df = df.rename_axis('Index Title')
# Display the
DataFrame print(df)
OUTPUT:
13
14
17. Write a Pandas program to join the two given dataframes along rows and assign all
data. CODE:
import pandas as pd
# Create the first
DataFrame data1 = {
'Name' : ['ana', 'andy', 'samara'],
'Age' : [20, 22, 34],
'City' : ['Newyork', 'London', 'Paris']
}
df1 = [Link](data1)
data2 = {
'Name' : ['Akanksha', 'Dhruva',
'Rajeev'], 'Age' : [15, 20, 25],
'City' : ['chicago', 'Berlin', 'Tokyo']
}
df2 = [Link](data2)
# Join the two DataFrames along rows and assign all data
joined_df = [Link]([ df1, df2 ])
# Display the joined DataFrame
print(joined_df)
OUTPUT:
14
15
18. Write a Pandas program to create the todays
date. CODE:
import pandas as pd
# Create today's date
today = [Link]().date()
# Print today's date
print("Today's date:", today)
OUTPUT:
19. Write a Pandas program to convert given datetime to
timestamp. CODE
import pandas as pd
# Given datetime string
datetime_str = '2023-07-20 [Link]'
# Convert the datetime string to a Pandas Timestamp object
timestamp = pd.to_datetime(datetime_str)
15
16
# Extract the timestamp
timestamp_value = [Link]()
print("Given Datetime:", datetime_str)
print("Timestamp:", timestamp_value)
OUTPUT
20. Write a Pandas program to create a line plot of the historical stock prices of Alphabet
Inc. between two specific dates
CODE:-
import yfinance as yf
import pandas as pd
import [Link] as plt
def plot_stock_prices(ticker, start_date, end_date):
# Fetch the stock data using yfinance
stock_data = [Link](ticker, start=start_date, end=end_date)
# Create the line plot
[Link](figsize=(12, 6))
[Link](stock_data['Close'], label='Closing Price', color='blue')
[Link](stock_data['Open'], label='Opening Price', color='green')
[Link](stock_data['High'], label='High Price', color='red')
[Link](stock_data['Low'], label='Low Price', color='orange')
16
17
[Link](f"Historical Stock Prices for {ticker} between {start_date} and {end_date}")
[Link]('Date')
[Link]('Stock Price')
[Link]()
[Link](True)
[Link]()
# Specify the date range
start_date = '2023-01-01'
end_date = '2023-07-01'
# Call the function with the stock symbol of Alphabet Inc. (GOOGL)
plot_stock_prices('GOOGL', start_date, end_date)
OUTPUT:-
17
18
21. Write a Pandas program to create a histograms plot of opening, closing, high, low
stock prices of Alphabet Inc. between two specific dates.
CODE:-
import yfinance as yf
import pandas as pd
import [Link] as plt
def plot_stock_histogram(ticker, start_date, end_date):
# Fetch the stock data using yfinance
stock_data = [Link](ticker, start=start_date, end=end_date)
# Create the histogram
plot [Link](figsize=(10,
6))
[Link](stock_data['Open'], bins=20, alpha=0.7, label='Opening Price')
18
19
[Link](stock_data['Close'], bins=20, alpha=0.7, label='Closing
Price') [Link](stock_data['High'], bins=20, alpha=0.7, label='High
Price') [Link](stock_data['Low'], bins=20, alpha=0.7, label='Low
Price')
[Link](f"Stock Price Histogram for {ticker} between {start_date} and {end_date}")
[Link]('Stock Price')
[Link]('Frequency')
[Link]()
[Link](True)
[Link]()
# Specify the date range
start_date = '2023-01-01'
end_date = '2023-07-01'
# Call the function with the stock symbol of Alphabet Inc. (GOOGL)
plot_stock_histogram('GOOGL', start_date, end_date)
OUTPUT:-
19
20
22. Write a python program to demonstrate image
processing CODE:-
import cv2
# Read the image.
image = [Link]("C:\\Users\\tgeor\\OneDrive\\Pictures\\digital_camera_photo.jpg")
# Convert the image to grayscale.
gray_image = [Link](image, cv2.COLOR_BGR2GRAY)
# Apply a Gaussian blur to the image.
blurred_image = [Link](gray_image, (5, 5), 0)
# Threshold the image.
thresholded_image = [Link](blurred_image, 127, 255, cv2.THRESH_BINARY)[1]
# Show the original image.
[Link]("Original Image",
image)
# Show the grayscale image.
[Link]("Grayscale Image", gray_image)
# Show the blurred image.
[Link]("Blurred Image", blurred_image)
# Show the thresholded image.
[Link]("Thresholded Image", thresholded_image)
20
21
# Wait for the user to press a key.
[Link](0)
# Close all the windows.
[Link]()
OUTPUT
21