Python Lab Mannual
Python Lab Mannual
Davanagere, Karnataka-570003
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(BCS358D)
PREPARED BY:
Davanagere-04
Bapuji Educational Association (Regd.)
Bapuji Institution of Engineering and Technology, Davangere
Department of Computer Science and Engineering
Analyze and develop solutions for problems that are complex in nature by
PSO1 applying the knowledge acquired from the core subjects of this program.
Ability to develop Secure, Scalable, Resilient and distributed applications
PSO2 for industry and societal requirements.
Ability to learn and apply the concepts and construct of emerging
PSO3 technologies like Artificial Intelligence, Machine learning, Deep learning,
Big Data Analytics, IoT, Cloud Computing etc for any real time problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze
complex computer engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern computer engineering and IT tools including prediction and modeling to
complex computer engineering activities with an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional
computer engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the computer engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
14.09.2023
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.
b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
Functions:https://www.youtube.com/watch?v=BVfCWuca9nw
Arguments:https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44
3 a) Write a Python program that accepts a sentence and find the number of words, digits, uppercase letters and
lowercase letters.
b) Write a Python program to find the string similarity between two given strings
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
https://www.youtube.com/watch?v=RRHQ6Fs1b8w&list=PLjVLYmrlmjGcC0B_FP3bkJ-
JIPkV5GuZR&index=3
https://www.youtube.com/watch?v=7ABCuhWO9II&list=PLjVLYmrlmjGcC0B_FP3bkJ-
JIPkV5GuZR&index=4
5
a) Write a Python program to Demonstrate how to Draw a Histogram Plot using Matplotlib.
b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
https://www.youtube.com/watch?v=Qk7caotaQUQ&list=PLjVLYmrlmjGcC0B_FP3bkJ-
JIPkV5GuZR&index=6
https://www.youtube.com/watch?v=PSji21jUNO0&list=PLjVLYmrlmjGcC0B_FP3bkJ-
JIPkV5GuZR&index=7
https://www.youtube.com/watch?v=UO98lJQ3QGI&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB_
7
Write a Python program which explains uses of customizing seaborn plots with Aesthetic functions.
https://www.youtube.com/watch?v=6GUZXDef2U0
8 Write a Python program to explain working with bokeh line graph using Annotations and Legends.
a) Write a Python program for plotting different types of plots using Bokeh.
https://www.youtube.com/watch?v=HDvxYoRadcA
https://www.youtube.com/watch?v=cCck7hCanpw&list=PLE50-dh6JzC4onX-
qkv9H3HtPbBVA8M94&index=4
14.09.2023
https://www.youtube.com/watch?v=xnJ2TNrGYik&list=PLE50-dh6JzC4onX-
qkv9H3HtPbBVA8M94&index=5
https://www.youtube.com/watch?v=D35m2CdMhVs&list=PLE50-dh6JzC4onX-
qkv9H3HtPbBVA8M94&index=6
The examination schedule and names of examiners are informed to the university before
the conduction of the examination. These practical examinations are to be conducted
between the schedule mentioned in the academic calendar of the University.
All laboratory experiments are to be included for practical examination.
(Rubrics) Breakup of marks and the instructions printed on the cover page of the answer
script to be strictly adhered to by the examiners. OR based on the course requirement
evaluation rubrics shall be decided jointly by examiners.
Students can pick one question (experiment) from the questions lot prepared by the
examiners jointly.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction
procedure and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall
be evaluated for 100 marks and scored marks shall be scaled down to 50 marks
(however, based on course type, rubrics shall be decided by the examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure
part are to be made zero.
The minimum duration of SEE is 02 hours
● Weightage of marks for PART A is 80% and for PART B is 20%. General rubrics suggested to be
followed for part A and part B.
● Change of experiment is allowed only once and Marks allotted to the procedure part to be made zero
(Not allowed for Part B).
● The duration of SEE is 03 hours
Rubrics suggested in Annexure-II of Regulation book
Textbooks:
1. Al Sweigart, “Automate the Boring Stuff with Python”,1stEdition, No Starch Press, 2015. (Available
under CC-BY-NC-SA license at https://automatetheboringstuff.com/)
2. Reema Thareja “Python Programming Using Problem Solving Approach” Oxford University Press.
3. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”,
2nd Edition, Green Tea Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf)
4. Jake VanderPlas “Python Data Science Handbook” 1st Edition, O’REILLY.
Data Visualization with Python BCS358D
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.
test1 = float(input("Enter Test1 marks: "))
test2 = float(input("Enter Test2 marks: "))
test3 = float(input("Enter Test3 marks: "))
Output:
Enter Test1 marks: 45
Enter Test2 marks: 20
Enter Test3 marks: 40
The Average of Best Two Tests is: 43
1 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.
val = int(input("Enter a number: "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i), "appears", str_val.count(str(i)), "times");
Output1:
Enter a number: 1001
Number is Palindrome
1 appears 2 times
0 appears 2 times
Output2:
Enter a number: 10011
Number is not Palindrome
1 appears 3 times
0 appears 2 times
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:
return 0
# Second Fibonacci number is 1
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
n = int(input("Enter a number:"))
print("Fibonacci number is:")
print(Fibonacci(n))
Output1:
Enter a number: 5
Fibonacci number is: 3
Output2:
Enter a number: -5
Incorrect input
Output3:
Enter a number: 1
Fibonacci number is: 0
Output4:
Enter a number: 2
Fibonacci number is: 1
Output1:
Enter the Binary Number: 1000
Equivalent Decimal Value = 8
Dr. Naresh Patel K M, Dept. of CS&E, BIET, Davangere 2
Data Visualization with Python BCS358D
Output2:
Enter Octal Number: 10
Equivalent Hexadecimal Value = 8
3 a). Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.
s = input("Enter a sentence: ")
w, d, u, l = 0, 0, 0, 0
l_w = s.split()
w = len(l_w)
for c in s:
if c.isdigit():
d=d+1
elif c.isupper():
u=u+1
elif c.islower():
l=l+1
Output:
Enter a sentence: Welcome to the World of Python Programming
No. of Words: 7
No. of Digits: 42
No. of Uppercase letters: 4
No. of Lowercase letters: 38
3 b). Write a Python program to find the string similarity between two given strings.
import difflib
str1 = "Welcome to Computer Science"
str2 = "Welcome to Computer Network"
sequence = difflib.SequenceMatcher(a=str1.lower(), b=str2.lower())
difference = sequence.ratio()*100
difference = round(difference,1)
print("Similarity between two said strings:"+str(difference))
Output:
Similarity between two said strings: 77.8
4 a). Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
#before executing this program you have to install matpilotlib package...
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 2, 1]
plt.bar(x, y, color='green')
plt.title('Bar Plot Example')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Dr. Naresh Patel K M, Dept. of CS&E, BIET, Davangere 3
Data Visualization with Python BCS358D
Output:
4 b). Write a Python program to Demonstrate how to Draw a Scatter Plot using
Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:
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
data = np.random.normal(100, 10, 1000)
plt.hist(data, bins=20, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of Data')
plt.grid(True)
plt.show()
Output:
5 b). Write a Python program to Demonstrate how to Draw a Pie Chart using
Matplotlib.
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels, autopct="%1.1f%%")
plt.title("Pie Chart")
plt.show()
Output:
overs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
runs_scored = [0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,198,203]
plt.plot(overs, runs_scored)
plt.xlabel('Overs')
plt.ylabel('Runs scored')
plt.title('Run scoring in an T20 Cricket Match')
plt.grid(True)
plt.show()
Output:
6 b). Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.
import matplotlib.pyplot as plt
overs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
runs_scored = [0,7,12,20,39,49,61,83,86,97,113,116,123,137,145,163,172,192,198,198,203]
plt.plot(overs, runs_scored, marker='X', linestyle='dashed',color='red', linewidth=2,
markerfacecolor='blue', markersize=8)
plt.xlabel('Overs', color = 'green')
plt.ylabel('Runs scored')
plt.title('Run scoring in an T20 Cricket Match')
plt.grid(True)
plt.show()
Output:
7. Write a Python program which explains uses of customizing seaborn plots with
Aesthetic functions.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def sinplot(n=10):
x = np.linspace(0, 14, 100)
for i in range(1, n + 1):
plt.plot(x, np.sin(x + i * .5) * (n + 2 - i))
sns.set_theme()
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()
plt.title('Seaborn plots with Aesthetic functions')
plt.show()
Output:
8. Write a Python program to explain working with bokeh line graph using Annotations
and Legends.
a) Write a Python program for plotting different types of plots using Bokeh.
import numpy as np
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p1.circle(x, y, legend_label="sin(x)")
p1.legend.title = 'Markers'
p2.circle(x, y, legend_label="sin(x)")
p2.line(x, y, legend_label="sin(x)")
p2.legend.title = 'Lines'
Output:
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
fig.update_layout(scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
Dr. Naresh Patel K M, Dept. of CS&E, BIET, Davangere 8
Data Visualization with Python BCS358D
zaxis_title='Z Axis'),
margin=dict(l=0, r=0, b=0, t=40),
title='3D Surface Plot of sin(sqrt(x^2 + y^2))')
fig.show()
Output:
10 a). Write a Python program to draw Time Series using Plotly Libraries.
import pandas as pd
import plotly.express as px
dollar_conv = pd.read_csv('CUR_DLR_INR.csv')
Output:
10 b). Write a Python program for creating Maps using Plotly Libraries.
import plotly.express as px
import pandas as pd
data = pd.read_csv('gapminder_with_codes.csv')
Output: