0% found this document useful (0 votes)
3 views19 pages

Python Lab PGM

The document contains a series of Python programming exercises covering various topics such as calculating averages, checking for palindromes, Fibonacci sequences, number base conversions, string analysis, plotting with Matplotlib and Plotly, and working with data visualization libraries. Each exercise includes code snippets, expected outputs, and explanations for the tasks. The exercises are designed to enhance programming skills in Python and familiarize users with data visualization techniques.

Uploaded by

kgf91897
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)
3 views19 pages

Python Lab PGM

The document contains a series of Python programming exercises covering various topics such as calculating averages, checking for palindromes, Fibonacci sequences, number base conversions, string analysis, plotting with Matplotlib and Plotly, and working with data visualization libraries. Each exercise includes code snippets, expected outputs, and explanations for the tasks. The exercises are designed to enhance programming skills in Python and familiarize users with data visualization techniques.

Uploaded by

kgf91897
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

Python lab progras

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.
m1 = int(input("Enter marks for test1 : "))

m2 = int(input("Enter marks for test2 : "))

m3 = int(input("Enter marks for test3 : "))

if m1 <= m2 and m1 <= m3:

avgMarks = (m2 + m3) / 2

elif m2 <= m1 and m2 <= m3:

avgMarks = (m1 + m3) / 2

elif m3 <= m1 and m2 <= m2:

avgMarks = (m1 + m2) / 2

print("Average of best two test marks out of three test’s marks is", avgMarks)

OUTPUT:

Enter marks for test1 : 54

Enter marks for test2 : 76

Enter marks for test3 : 34

Average of best two test marks out of three test’s marks is 65.0

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 value : "))

str_val = str(val)

if str_val == str_val[::-1]:

print("Palindrome")
Python lab progras

else:

print("Not Palindrome")

for i in range(10):

if str_val.count(str(i)) > 0:

print(str(i), "appears", str_val.count(str(i)), "times")

OUTPUT:
Enter a value : 121

Palindrome

1 appears 2 times

2 appears 1 times

Enter a value : 123

Not Palindrome

1 appears 1 times

2 appears 1 times

3 appears 1 times

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 fn(n):

if n == 1:

return 0 elif n == 2:

return 1

else:

return fn(n - 1) + fn(n - 2) num = int(input("Enter a number : "))


Python lab progras

if num > 0:

print("fn(", num, ") = ", fn(num), sep="")

else:

print("Error in input")

OUTPUT:
Enter a number : 5

fn(5) = 3

Enter a number : -1

Error in input

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


using functions.

def bin2Dec(val):

rev = val[::-1]

dec = 0

i=0

for dig in rev:

dec += int(dig) * 2 ** i

i += 1 return dec def oct2Hex(val):

rev = val[::-1]

dec = 0

i=0

for dig in rev:

dec += int(dig) * 8 ** i

i += 1

list = []
Python lab progras

while dec != 0:

[Link](dec % 16)

dec = dec // 16 nl = []

for elem in list[::-1]:

if elem <= 9:

[Link](str(elem))

else:

[Link](chr(ord('A') + (elem - 10)))

hex = "".join(nl) return hex num1 = input("Enter a binary number : ")

print(bin2Dec(num1))

num2 = input("Enter a octal number : ")

print(oct2Hex(num2))

OUTPUT:
Enter a binary number : 10111001

185

Enter a octal number : 675

1BD

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

sentence = input("Enter a sentence : ")

wordList = [Link](" ")

print("This sentence has", len(wordList), "words")

digCnt = upCnt = loCnt = 0

for ch in sentence:

if '0' <= ch <= '9':

digCnt += 1
Python lab progras

elif 'A' <= ch <= 'Z':

upCnt += 1

elif 'a' <= ch <= 'z':

loCnt += 1

print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case letters")

OUTPUT:
Enter a sentence : Welcome 2 VtuCode

This sentence has 3 words

This sentence has 0 digits 1 upper case letters 0 lower case letters

This sentence has 0 digits 1 upper case letters 1 lower case letters

This sentence has 0 digits 1 upper case letters 2 lower case letters

This sentence has 0 digits 1 upper case letters 3 lower case letters

This sentence has 0 digits 1 upper case letters 4 lower case letters

This sentence has 0 digits 1 upper case letters 5 lower case letters

This sentence has 0 digits 1 upper case letters 6 lower case letters

This sentence has 0 digits 1 upper case letters 6 lower case letters

This sentence has 1 digits 1 upper case letters 6 lower case letters

This sentence has 1 digits 1 upper case letters 6 lower case letters

This sentence has 1 digits 2 upper case letters 6 lower case letters

This sentence has 1 digits 2 upper case letters 7 lower case letters

This sentence has 1 digits 2 upper case letters 8 lower case letters

This sentence has 1 digits 3 upper case letters 8 lower case letters

This sentence has 1 digits 3 upper case letters 9 lower case letters

This sentence has 1 digits 3 upper case letters 10 lower case letters

This sentence has 1 digits 3 upper case letters 11 lower case letters
Python lab progras

3.b) Write a Python program to find the string similarity between two given strings.
str1 = input("Enter String 1:\n")
str2 = input("Enter String 2:\n")
if len(str2) < len(str1):
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2) matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt / long)

OUTPUT:
Enter String 1:
Welcome to vtucode
Enter String 2:
Welcome to vtucode
Similarity between two said strings:
1.0
Enter String 1:
Welcome to vtucode
Enter String 2:
author vtucode
Python lab progras

Similarity between two said strings:


0.1111111111111111

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

#before exuting this program you have to install matpilotlib package...


import [Link] as plt x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 2, 1]
[Link](x, y, color='green')
[Link]('Bar Plot Example')
[Link]('X Axis')
[Link]('Y Axis')
[Link]()
OUTPUT:
Python lab progras

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

import [Link] as plt

import numpy as np x = [Link](100)

y = [Link](100)

[Link](x, y)

[Link]('Scatter Plot')

[Link]('X')

[Link]('Y')

[Link]()

OUTPUT:
Python lab progras

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

import [Link] as plt

import numpy as np data = [Link](100, 10, 1000)

[Link](data, bins=20, edgecolor='black')

[Link]('Value')

[Link]('Frequency')

[Link]('Histogram of Data')

[Link](True)

[Link]()

OUTPUT:
Python lab progras

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

import [Link] as plt labels = ['A', 'B', 'C', 'D']

sizes = [15, 30, 45, 10]

[Link](sizes, labels=labels, autopct="%1.1f%%")

[Link]("Pie Chart")

[Link]()

OUTPUT:
Python lab progras

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

# Import the necessary libraries

import [Link] as plt

import numpy as np X = [Link]([2, 4, 6, 8, 10])

Y=X*2

[Link](X, Y)

[Link]("X-axis Label")

[Link]("Y-axis Label")

[Link]("This is the title of of the plot")

[Link]()

OUTPUT:
Python lab progras

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

import [Link] as plt

import numpy as np x = [Link](0, 10, 100)

y = [Link](x)

[Link](x, y, color='blue', linestyle='-', linewidth=2)

[Link]('Line Plot')

[Link]('X Axis')

[Link]('Y Axis')

[Link]()

OUTPUT:
Python lab progras

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

import seaborn as sns

import [Link] as plt tips = sns.load_dataset("tips")

[Link](x="total_bill", y="tip", data=tips)

sns.set_style("whitegrid")

sns.set_palette("Set2")

[Link]()

[Link]()

OUTPUT:
Python lab progras

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.

from [Link] import figure, show x = [1, 2, 3, 4, 5]

y = [6, 7, 2, 4, 5]

p = figure(title="Interactive line graph", x_axis_label='x', y_axis_label='y')

[Link](x, y, legend_label="Line", line_width=2)

p.annular_wedge(x=5, y=5, inner_radius=0.2, outer_radius=0.4,


start_angle=45, end_angle=135, line_color="red", fill_color="red")

show(p)

OUTPUT:
Python lab progras

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

# Import necessary libraries

import plotly.graph_objects as go

import numpy as np x = [Link](0, 10, 100)

y = [Link](0, 10, 100)

z = [Link](100, 100)

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

fig.update_layout(title='3D Scatter Plot', scene=dict(xaxis_title='X Axis',


yaxis_title='Y Axis', zaxis_title='Z Axis'))

[Link]()

OUTPUT:
Python lab progras

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

import plotly.graph_objects as go data = [

{'x': [1, 2, 3, 4, 5], 'y': [6, 7, 2, 4, 5]},

{'x': [6, 7, 8, 9, 10], 'y': [1, 3, 5, 7, 9]}

fig = [Link]()

for i in range(len(data)):

fig.add_trace([Link](x=data[i]['x'], y=data[i]['y'], mode='lines'))

fig.update_layout(title='Time Series', xaxis_title='Time',


yaxis_title='Value')

[Link]()

OUTPUT:
Python lab progras

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

import [Link] as px df = [Link]()

geojson = [Link].election_geojson() fig = [Link](df,


geojson=geojson, color="Bergeron",

locations="district", featureidkey="[Link]",

projection="mercator"

fig.update_geos(fitbounds="locations", visible=True)

fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

[Link]()

OUTPUT:
Python lab progras
Python lab progras

You might also like