Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python lab manual

The Python Lab Manual for course BCS358D at Atria Institute of Technology includes various lab experiments focused on Python programming, data visualization using libraries like Matplotlib and Bokeh, and data analysis techniques. Each experiment provides a description, code examples, and expected outputs for tasks such as calculating averages, checking for palindromes, and creating different types of plots. The manual is structured to enhance practical skills in programming and data visualization for students in their third semester.

Uploaded by

faraazahmed2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python lab manual

The Python Lab Manual for course BCS358D at Atria Institute of Technology includes various lab experiments focused on Python programming, data visualization using libraries like Matplotlib and Bokeh, and data analysis techniques. Each experiment provides a description, code examples, and expected outputs for tasks such as calculating averages, checking for palindromes, and creating different types of plots. The manual is structured to enhance practical skills in programming and data visualization for students in their third semester.

Uploaded by

faraazahmed2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

PYTHON LAB MANUAL

BCS358D

2023-24

ATRIA INSTITUTE OF TECHNOLOGY


Adjacent to Bangalore Baptist Hospital
Hebbal Bengaluru-560024
Course Code BCS358D CIE Marks 50
Number of Contact Hours/Week 0:0:2 SEE Marks 50
Total Number of Lab Contact Hours 28 Exam Hours 03
Credits-1 Semester III

Sl NO Lab Experiments PgNo

PART A
1. a) Write a python program to find the best of two test average marks out 01
of three test’s marks accepted from the user.
b) Develop a Python program to check whether a given number is
palindrome or not and also count the number of occurrences of each
digit in the input number.
2. a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program 04
which accepts a value for N (where N >0) as input and pass this value to
the function. Display suitable error message if the condition for input
value is not followed.
b) Develop a python program to convert binary to decimal, octal to
hexadecimal using functions.
3. a) Write a Python program that accepts a sentence and find the number of 06
words, digits, uppercase letters and lowercase letters.
b) Write a Python program to find the string similarity between two given
strings.
Sample Output: Sample Output:
Original string: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercises
Similarity between two said strings: Similarity between two said
strings:1.0 0.967741935483871
4. a) Write a Python program to Demonstrate how to Draw a Bar Plot 09
using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Scatter Plot
using Matplotlib
5. a) Write a Python program to Demonstrate how to Draw a Histogram 11
Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Pie Chart
using Matplotlib.
6. a) Write a Python program to illustrate Linear Plotting using Matplotlib. 13
b) Write a Python program to illustrate liner plotting with line
formatting using Matplotlib.

7. Write a Python program which explains uses of customizing seaborn 15


plots with Aesthetic functions.
8. Write a Python program to explain working with bokeh line graph using 17
Annotations and Legends.
a) Write a Python program for plotting different types of plots using
Bokeh.

9. Write a Python program to draw 3D Plots using Plotly Libraries. 21


10. a) Write a Python program to draw Time Series using Plotly Libraries. 22
b) Write a Python program for creating Maps using Plotly Libraries.
Python Lab Manual BCS358D

Program 1 :
a) Write a python program to find the best of two test average marks out of three test’s marks
accepted from the user.

# Function to calculate average


def calculate_average(test1, test2, test3):
return (test1 + test2 + test3) / 3
# Get input from the user
test1 = float(input("Enter marks for test 1: "))
test2 = float(input("Enter marks for test 2: "))
test3 = float(input("Enter marks for test 3: "))

# Calculate averages for two best tests


average1 = calculate_average(test1, test2, test3)
average2 = calculate_average(test1, test2, test3)

# Find the best average


best_average = max(average1, average2)

# Print the best average


print(f"The best average marks out of two tests are: {best_average:.2f}")

Output:

AIT ,Dept. of CS&E Page 1


Python Lab Manual BCS358D

b) Develop a Python program to check whether a given number is palindrome or not and also
count the number of occurrences of each digit in the input number.

def is_palindrome(number):
# Convert the number to a string for easy comparison
number_str = str(number)

# Check if the string is equal to its reverse


return number_str == number_str[::-1]

def count_digit_occurrences(number):
# Initialize a dictionary to store digit occurrences
digit_occurrences = {str(i): 0 for i in range(10)}

# Convert the number to a string for easy iteration


number_str = str(number)

# Count occurrences of each digit


for digit in number_str:
digit_occurrences[digit] += 1

return digit_occurrences

# Get input from the user


input_number = int(input("Enter a number: "))

# Check if the number is a palindrome


if is_palindrome(input_number):
print(f"{input_number} is a palindrome.")
else:
print(f"{input_number} is not a palindrome.")

# Count digit occurrences


occurrences = count_digit_occurrences(input_number)

# Display the occurrences of each digit


print("Occurrences of each digit:")
for digit, count in occurrences.items():
print(f"Digit {digit}: {count} times")

AIT ,Dept. of CS&E Page 2


Python Lab Manual BCS358D

Output:

AIT ,Dept. of CS&E Page 3


Python Lab Manual BCS358D

Program 2 :
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error message
if the condition for input value is not followed.

def F(N):
if N <= 0:
print("Error: Number of terms must be a positive integer.")
return
elif N == 1:
return [0]
elif N == 2:
return [0, 1]
else:
f_n = [0, 1] # fn = [fn-1,fn-2]

while len(f_n) < N:


f_n_next = f_n[-1] + f_n[-2] #Next term fn = fn-1+fn-2
f_n.append(f_n_next) #Creating a list of terms
return f_n
# Accept input from the user
n = int(input("Enter a positive integer (N > 0): "))

# Call the Fibonacci function and display the result or error message
result = F(n)
if result is not None:
print(f"The numbers till N are: {result}")

Output:

AIT ,Dept. of CS&E Page 4


Python Lab Manual BCS358D

b) Develop a python program to convert binary to decimal, octal to hexadecimal using


functions.

def binary_to_decimal(binary):
decimal = int(binary, 2)
return decimal
def octal_to_hexadecimal(octal):
decimal = int(octal, 8)
hexadecimal = hex(decimal).upper()[2:]
return hexadecimal

# Example usage:

binary_number = "101010"
decimal_result = binary_to_decimal(binary_number)
print(f"Binary {binary_number} is equivalent to Decimal {decimal_result}")

octal_number = "52"
hexadecimal_result = octal_to_hexadecimal(octal_number)
print(f"Octal {octal_number} is equivalent to Hexadecimal {hexadecimal_result}")

Output:

AIT ,Dept. of CS&E Page 5


Python Lab Manual BCS358D

Program 3 :
a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.

def analyze_sentence(sentence):
word_count = len(sentence.split())
digit_count = sum(c.isdigit() for c in sentence)
uppercase_count = sum(c.isupper() for c in sentence)
lowercase_count = sum(c.islower() for c in sentence)

return word_count, digit_count, uppercase_count, lowercase_count

# Example usage:

sentence = input("Enter a sentence: ")


word_count, digit_count, uppercase_count, lowercase_count =
analyze_sentence(sentence)
print(f"Number of words: {word_count}")
print(f"Number of digits: {digit_count}")
print(f"Number of uppercase letters: {uppercase_count}")
print(f"Number of lowercase letters: {lowercase_count}")

Output :

AIT ,Dept. of CS&E Page 6


Python Lab Manual BCS358D

b) Write a Python program to find the string similarity between two given strings.

def levenshtein_distance(s1, s2):


m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]

for i in range(m + 1):


dp[i][0] = i

for j in range(n + 1):


dp[0][j] = j

for i in range(1, m + 1):


for j in range(1, n + 1):
cost = 0 if s1[i - 1] == s2[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)

return dp[m][n]

# Example usage:

string1 = "python"
string2 = "program"

distance = levenshtein_distance(string1, string2)


print(f"The Levenshtein distance between '{string1}' and '{string2}' is: {distance}")

AIT ,Dept. of CS&E Page 7


Python Lab Manual BCS358D

Output:

AIT ,Dept. of CS&E Page 8


Python Lab Manual BCS358D

Program 4:
a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.

import matplotlib.pyplot as plt


# Data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [15, 24, 12, 8]

# Create a bar plot


plt.bar(categories, values, color='skyblue')

# Add title and labels


plt.title('Bar Plot Example')
plt.xlabel('Categories')
plt.ylabel('Values')

# Display the plot


plt.show()

Output:

AIT ,Dept. of CS&E Page 9


Python Lab Manual BCS358D

b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib

import matplotlib.pyplot as plt


# Data
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [3, 5, 9, 7, 6, 8, 12, 10]

# Create a scatter plot


plt.scatter(x, y, color='red', marker='o')

# Add title and labels


plt.title('Scatter Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Display the plot


plt.show()

Output:

AIT ,Dept. of CS&E Page 10


Python Lab Manual BCS358D

Program 5 :
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.

import matplotlib.pyplot as plt


import numpy as np
# Generate some random data for demonstration
data = np.random.randn(1000) * 10 + 50

# Create a histogram
plt.hist(data, bins=30, alpha=0.7, color='blue', edgecolor='black')

# Add labels and title


plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Plot')

# Display the plot


plt.show()

Output:

AIT ,Dept. of CS&E Page 11


Python Lab Manual BCS358D

b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib

import matplotlib.pyplot as plt

# Data to plot
labels = 'Python', 'Java', 'C++', 'JavaScript'
sizes = [45, 30, 15, 10] # These are percentages
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice

# Plotting the pie chart


plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=140)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

# Adding a title
plt.title('Programming Languages Usage')

# Displaying the pie chart


plt.show()

output:

AIT ,Dept. of CS&E Page 12


Python Lab Manual BCS358D

Program 6 :
a) Write a Python program to illustrate Linear Plotting using Matplotlib

import matplotlib.pyplot as plt


# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Create a linear plot


plt.plot(x, y, marker='o', color='blue', linestyle='-')

# Add title and labels


plt.title('Linear Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Display the plot


plt.show()

Output:

AIT ,Dept. of CS&E Page 13


Python Lab Manual BCS358D

b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib.

import matplotlib.pyplot as plt


# Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plotting with line formatting


plt.plot(x, y, marker='o', linestyle='-', color='b', label='Line Plot')

# Adding labels and title


plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with Formatting')

# Adding a legend
plt.legend()

# Display the plot


plt.show()

Output:

AIT ,Dept. of CS&E Page 14


Python Lab Manual BCS358D

Program 7 :
Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.

import seaborn as sns


import matplotlib.pyplot as plt

# Load a sample dataset (Iris dataset for demonstration)


iris = sns.load_dataset('iris')

# Set the style of the plot


sns.set_style("whitegrid")

# Create a scatter plot with customized color palette


sns.scatterplot(x='sepal_length', y='sepal_width', hue='species', data=iris, palette='pastel')

# Set title and labels


plt.title('Customized Scatter Plot')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')

# Customize legend
plt.legend(title='Species', loc='upper right')
# Add grid
plt.grid(True)

# Show the plot


plt.show()

AIT ,Dept. of CS&E Page 15


Python Lab Manual BCS358D

Output:

AIT ,Dept. of CS&E Page 16


Python Lab Manual BCS358D

Program 8 :
Write a Python program to explain working with bokeh line graph using Annotations and
Legends.

from bokeh.plotting import figure, show, output_file


from bokeh.models import ColumnDataSource
from bokeh.layouts import layout
from bokeh.models.annotations import Title, Legend

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [2, 3, 5, 7, 11]
y2 = [1, 4, 9, 16, 25]

# Create a ColumnDataSource to hold the data


source = ColumnDataSource(data={'x': x, 'y1': y1, 'y2': y2})

# Create a figure
p = figure(title='Bokeh Line Graph with Annotations and Legends', x_axis_label='X-axis',
y_axis_label='Y-axis')

# Plot the lines


p.line('x', 'y1', source=source, line_width=2, line_color='blue', legend_label='Line 1')
p.line('x', 'y2', source=source, line_width=2, line_color='red', legend_label='Line 2')

# Add annotations
title = Title(text="Line Graph with Annotations and Legends", text_font_size="14pt")
p.title = title

# Add legend
p.legend.location = "top_left"
p.legend.click_policy="hide"

# Create an output HTML file


output_file("line_graph_with_annotations_legends.html")

# Show the plot


show(p)

AIT ,Dept. of CS&E Page 17


Python Lab Manual BCS358D

Output:

a) Write a Python program for plotting different types of plots using Bokeh.

from bokeh.plotting import figure, show, output_file


from bokeh.io import output_notebook, show
from bokeh.layouts import gridplot
from bokeh.models import ColumnDataSource

# Scatter Plot
output_file("scatter_plot.html")

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 6]

p1 = figure(title="Scatter Plot", x_axis_label='X-axis', y_axis_label='Y-axis')


p1.scatter(x, y, legend_label="Scatter", line_color="blue", fill_color="orange")

# Line Plot
output_notebook()

AIT ,Dept. of CS&E Page 18


Python Lab Manual BCS358D

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 6]

p2 = figure(title="Line Plot", x_axis_label='X-axis', y_axis_label='Y-axis')


p2.line(x, y, legend_label="Line", line_color="green")

# Bar Plot
output_notebook()

fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Fig']


counts = [4, 5, 8, 12, 7]

source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))

p3 = figure(x_range=fruits, title="Bar Plot", x_axis_label='Fruits', y_axis_label='Counts',


plot_height=350)
p3.vbar(x='fruits', top='counts', width=0.9, color="purple", legend_label="Fruits",
source=source)

# Grid Plot
output_file("grid_plot.html")

x = [1, 2, 3, 4, 5]
y1 = [6, 7, 2, 4, 6]
y2 = [2, 3, 1, 5, 8]

p4 = figure(title="Grid Plot", x_axis_label='X-axis', y_axis_label='Y-axis')


p4.line(x, y1, legend_label="Line 1", line_color="blue")
p4.line(x, y2, legend_label="Line 2", line_color="red")

# Arrange plots in a grid


grid = gridplot([[p1, p2], [p3, p4]])

# Show the grid plot


show(grid)

AIT ,Dept. of CS&E Page 19


Python Lab Manual BCS358D

Output:

AIT ,Dept. of CS&E Page 20


Python Lab Manual BCS358D

Program 9:
Write a Python program to draw 3D Plots using Plotly Libraries.

import plotly.graph_objects as go
# Generate sample data
import numpy as np
np.random.seed(42)
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

# Create a 3D scatter plot


fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z, mode='markers')])

# Add labels and title


fig.update_layout(scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
title='3D Scatter Plot')

# Show the plot


fig.show()

Output:

AIT ,Dept. of CS&E Page 21


Python Lab Manual BCS358D

Program 10 :
Write a Python program to draw Time Series using Plotly Libraries.

import plotly.graph_objects as go
from datetime import datetime

# Sample data
dates = [
datetime(2023, 1, 1),
datetime(2023, 2, 1),
datetime(2023, 3, 1),
datetime(2023, 4, 1),
datetime(2023, 5, 1)
]
values = [10, 14, 18, 24, 30]

# Create a trace
trace = go.Scatter(x=dates, y=values, mode='lines+markers')

# Create layout
layout = go.Layout(
title='Time Series Plot',
xaxis=dict(title='Date'),
yaxis=dict(title='Value')
)

# Create figure
fig = go.Figure(data=[trace], layout=layout)

# Display the figure


fig.show()

AIT ,Dept. of CS&E Page 22


Python Lab Manual BCS358D

Output:

b) Write a Python program for creating Maps using Plotly Libraries.

import plotly.express as px

# Create a sample dataset


data = dict(
lat=[37.7749, 40.7128, 34.0522, 41.8781],
lon=[-122.4194, -74.0060, -118.2437, -87.6298],
text=['San Francisco', 'New York', 'Los Angeles', 'Chicago'],
size=[20, 50, 10, 30]
)

# Create a scatter_geo figure


fig = px.scatter_geo(data, lat='lat', lon='lon', text='text', size='size')

# Show the map


fig.show()

AIT ,Dept. of CS&E Page 23


Python Lab Manual BCS358D

Output:

AIT ,Dept. of CS&E Page 24

You might also like