0% found this document useful (0 votes)
25 views28 pages

rufh 2

Uploaded by

Satendra Diwakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views28 pages

rufh 2

Uploaded by

Satendra Diwakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Practical File

On

“Introduction To Python”
KMBA251

Submitted for the partial fulfillment of the Award


Of
Master of Business Administration
(Business Analytics)

DEGREE
(Session: 2024- 2025)

SUBMITTED BY
Satendra Diwakar
(2302721570023)

UNDER THE GUIDANCE OF


Dr. Shweta Rai

GREATER NOIDA INSTITUTE OF TECHNOLOGY (MBA Institute)

AFFILIATED TO
DR. A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY (FORMERLY UTTAR
PRADESH TECHNICAL UNIVERSITY), LUCKNOW (FS-

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, np.nan, 9, 20, 14.5, np.nan, 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:

4
5

5
6

6.Write 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:

6. 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:

6
7

7. 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 = csv.writer(file)

# Write header row

writer.writerow(['Name', 'Age', 'Country'])

# Write data rows

writer.writerow(['Alice', 25, 'USA'])

writer.writerow(['Bob', 30, 'Canada'])

writer.writerow(['Charlie', 20, 'Australia'])

# Open CSV file for reading

with open('my_data.csv', mode='r') as file:

7
8

reader = csv.reader(file)

# Read header row

header =

next(reader)

# Print

header

print(header)

# Read and print data

rows for row in reader:

print(row)

OUTPUT:

8. a.Demonstrate Map() with Lambda


Functions. b.Demonstrate Map() with Tuple.
CODE:

numbers = [1, 2, 3, 4, 5]

# Define lambda function to square a number

square = lambda x: x**2

# Use map() with lambda function

squares = map(square, numbers)

# Convert map object to list and print

print(list(squares))

OUTPUT:

8
9

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:

9. Write a python program to demonstrate array characteristics using

numpy. CODE:
import numpy as np
arr =
np.arange(1,11)
print("Array:","arr")
print("Number of dimension:",arr.ndim)
print("Shape:",arr.shape)
print("Size:",arr.size)
print("Data type:",arr.dtype)
print("Maximum value:",arr.max())
print("Minimum value:",arr.min())
print("Sum:",arr.sum())
print("Average:",arr.mean())
OUTPUT:

9
10

10.Write 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 = np.arange(10, 1, -2)
print("\n A sequential array with a negative step: \n",a)

# Indexes are specified inside the np.array


method. newarr = a[np.array([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)

OUTPUT:

10
11

11.Write a Python program to demonstrate basic operations on single array.


CODE:
import numpy as np
# create a numpy array
arr=np.array([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 = np.sqrt(arr)
print("Square root:",
sqrt) # Sum of all
elements
sum_of_elements = np.sum(arr)

11
12

print("Sum_of_elements:",sum_of_elements)

# Minimum and Maximum


minimum = np.min(arr)
maximum = np.max(arr)
print("Minimum:",minimum)
print("Maximum:",maximum)

# Mean and Standard Deviation


mean = np.mean(arr)
std_dev = np.std(arr)
print("Mean:",mean)
print("Standard deviation:",std_dev)
OUTPUT:

12.Write 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

12
13

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 = np.array([3, 2, 0, 1])
arr1 = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
print(np.sort(arr1))

# Sort a 2-D array


arr2 = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(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

13
14

# Create an array of data


data = [10, 20, 30, 40, 50]
# Create a Series using Pandas
series = pd.Series(data)
# Display the Series
print(series)
OUTPUT:

14
15

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, np.nan, 9, 20, 14.5, np.nan, 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, np.nan, 9, 20, 14.5, np.nan, 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 = pd.DataFrame(exam_data, index = labels)
# Get the first 3 rows of the DataFrame
first_three_rows = df.head(3)
# Display the first 3 rows
print(first_three_rows)
OUTPUT:

15
16

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 = pd.DataFrame(data)

# Set the name of the index column


df = df.rename_axis('Index Title')

# Display the
DataFrame print(df)
OUTPUT:

16
17

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 = pd.DataFrame(data1)
data2 = {
'Name' : ['Akanksha', 'Dhruva',
'Rajeev'], 'Age' : [15, 20, 25],
'City' : ['chicago', 'Berlin', 'Tokyo']
}
df2 = pd.DataFrame(data2)
# Join the two DataFrames along rows and assign all data
joined_df = pd.concat([ df1, df2 ])
# Display the joined DataFrame
print(joined_df)
OUTPUT:

17
18

18. Write a Pandas program to create the todays


date. CODE:
import pandas as pd

# Create today's date


today = pd.Timestamp.today().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 12:34:56'

# Convert the datetime string to a Pandas Timestamp object


timestamp = pd.to_datetime(datetime_str)

18
19

# Extract the timestamp


timestamp_value = timestamp.timestamp()

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 matplotlib.pyplot as plt

def plot_stock_prices(ticker, start_date, end_date):


# Fetch the stock data using yfinance
stock_data = yf.download(ticker, start=start_date, end=end_date)

# Create the line plot


plt.figure(figsize=(12, 6))
plt.plot(stock_data['Close'], label='Closing Price', color='blue')
plt.plot(stock_data['Open'], label='Opening Price', color='green')
plt.plot(stock_data['High'], label='High Price', color='red')
plt.plot(stock_data['Low'], label='Low Price', color='orange')

19
20

plt.title(f"Historical Stock Prices for {ticker} between {start_date} and {end_date}")


plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.grid(True)
plt.show()
# 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:-

20
21

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 matplotlib.pyplot as plt

def plot_stock_histogram(ticker, start_date, end_date):


# Fetch the stock data using yfinance
stock_data = yf.download(ticker, start=start_date, end=end_date)

# Create the histogram


plot plt.figure(figsize=(10,
6))
plt.hist(stock_data['Open'], bins=20, alpha=0.7, label='Opening Price')

21
22

plt.hist(stock_data['Close'], bins=20, alpha=0.7, label='Closing


Price') plt.hist(stock_data['High'], bins=20, alpha=0.7, label='High
Price') plt.hist(stock_data['Low'], bins=20, alpha=0.7, label='Low
Price')

plt.title(f"Stock Price Histogram for {ticker} between {start_date} and {end_date}")


plt.xlabel('Stock Price')
plt.ylabel('Frequency')
plt.legend()
plt.grid(True)
plt.show()

# 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:-

22
23

23
24

22. Write a python program to demonstrate image


processing CODE:-
import cv2

# Read the image.


image = cv2.imread("C:\\Users\\tgeor\\OneDrive\\Pictures\\digital_camera_photo.jpg")

# Convert the image to grayscale.


gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply a Gaussian blur to the image.


blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)

# Threshold the image.


thresholded_image = cv2.threshold(blurred_image, 127, 255, cv2.THRESH_BINARY)[1]

# Show the original image.


cv2.imshow("Original Image",
image)

# Show the grayscale image.


cv2.imshow("Grayscale Image", gray_image)

# Show the blurred image.


cv2.imshow("Blurred Image", blurred_image)

# Show the thresholded image.


cv2.imshow("Thresholded Image", thresholded_image)

24
25

# Wait for the user to press a key.


cv2.waitKey(0)

# Close all the windows.


cv2.destroyAllWindows()
OUTPUT

25

You might also like