1. Python program to demonstrate Arithmetic and Relational operators.
x = 15
y = 4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
OUTPUT
2. Python program to Create a list and perform the following methods 1) insert()
2) remove() 3) append() 4) len() 5) pop() 6) clear()
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
a.insert(3,20)
print(a)
a.remove(7)
print(a)
a.append("hi")
print(a)
len(a)
print(a)
a.pop()
print(a)
a.pop(6)
print(a)
a.clear()
print(a)
OUTPUT
3. Write a Python program to convert temperatures to and from Celsius and
Fahrenheit.
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
OUTPUT
4. Python Program to Calculate Total Marks Percentage and Grade of a Student
print("Enter the marks of five subjects::")
subject_1 = float (input ())
subject_2 = float (input ())
subject_3 = float (input ())
subject_4 = float (input ())
subject_5 = float (input ())
total, average, percentage, grade = None, None, None, None
# It will calculate the Total, Average and Percentage
total = subject_1 + subject_2 + subject_3 + subject_4 + subject_5
average = total / 5.0
percentage = (total / 500.0) * 100
if average >= 90:
grade = 'A'
elif average >= 80 and average < 90:
grade = 'B'
elif average >= 70 and average < 80:
grade = 'C'
elif average >= 60 and average < 70:
grade = 'D'
else:
grade = 'E'
# It will produce the final output
print ("nThe Total marks is: t", total, "/ 500.00")
print ("nThe Average marks is: t", average)
print ("nThe Percentage is: t", percentage, "%")
print ("nThe Grade is: t", grade)
OUTPUT
5. Write a program to print Fibonacci series up to n terms in python
num = 10
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
print()
OUTPUT
6. Write a Python program to calculate the sum and product of two compatible
Matrices
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
print("Addition of two matrices")
result = [[X[i][j] + Y[i][j] for j in range
(len(X[0]))] for i in range(len(X))]
for r in result:
print(r)
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
print("Multiplication of two matrices")
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
OUTPUT
7.Write a function that takes a character and returns true if it is a vowel, false
otherwise.
def vowel(x):
if x in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]:
return "True"
else:
return "False "
a = input ("Enter the letter :- ")
print (vowel(a))
OUTPUT
8. Python program to read last 5 lines of a file
f=open('myfile.txt', 'w')
f.write('line1')
f.close()
f=open('myfile.txt','a')
f.write('nline2')
f.write('nline3')
f.write('nline4')
f.write('nline5')
f.write('nline6')
f.write('nline7')
f.write('nline8')
f.write('nline9')
f.write('nline10')
f.close()
# Python implementation to
# read last N lines of a file
# Function to read
# last N lines of the file
def LastNlines(fname, N):
# opening file using with() method
# so that file get closed
# after completing work
with open(fname) as file:
# loop to read iterate
# last n lines and print it
for line in (file.readlines() [-N:]):
print(line, end ='')
# Driver Code:
if __name__ == '__main__':
fname = 'myfile.txt'
N = 5
try:
LastNlines(fname, N)
except:
print('File not found')
OUTPUT
9.Demonstration of Modules in Python
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))
# using pi function contained in math module
print(math.pi)
# 2 radians = 114.59 degrees
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
# Tangent of 0.23 radians
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random
# printing random integer between 0 and 5
print(random.randint(0, 5))
# print random floating point number between 0 and 1
print(random.random())
# random number between 0 and 100
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))
OUTPUT
10. Multithreading in python
# Python program to illustrate the concept
# of threading
import threading
import os
def task1():
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 1: {}".format(os.getpid()))
def task2():
print("nTask 2 assigned to thread: {}".format(threading.current_thread().name))
print("nID of process running task 2: {}".format(os.getpid()))
if __name__ == "__main__":
# print ID of current process
print("ID of process running main program: {}".format(os.getpid()))
# print name of main thread
print("Main thread name: {}".format(threading.current_thread().name))
# creating threads
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
# starting threads
t1.start()
t2.start()
# wait until all threads finish
t1.join()
t2.join()
OUTPUT
11. Write a python program to create 3D object
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
theta1 = np.linspace(0, 2*np.pi, 100)
r1 = np.linspace(-2, 0, 100)
t1, R1 = np.meshgrid(theta1, r1)
X1 = R1*np.cos(t1)
Y1 = R1*np.sin(t1)
Z1 = 5+R1*2.5
theta2 = np.linspace(0, 2*np.pi, 100)
r2 = np.linspace(0, 2, 100)
t2, R2 = np.meshgrid(theta2, r2)
X2 = R2*np.cos(t2)
Y2 = R2*np.sin(t2)
Z2 = -5+R2*2.5
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
# ax.set_xlim(-2.5, 2.5)
# ax.set_ylim(-2.5, 2.5)
# ax.set_zlim(0, 5)
ax.set_aspect('equal')
ax.plot_surface(X1, Y1, Z1, alpha=0.8, color="blue")
ax.plot_surface(X2, Y2, Z2, alpha=0.8, color="blue")
# ax.plot_surface(X, Y, Z, alpha=0.8)
#fig. savefig ("Cone.png", dpi=100, transparent = False)
plt.show()
OUTPUT
12. Read n integers and display them as a histogram
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
# Creating dataset
np.random.seed(23685752)
N_points = 10000
n_bins = 20
# Creating distribution
x = np.random.randn(N_points)
y = .8 ** x + np.random.randn(10000) + 25
# Creating histogram
fig, axs = plt.subplots(1, 1,
figsize =(10, 7),
tight_layout = True)
axs.hist(x, bins = n_bins)
# Show plot
plt.show()
OUTPUT
13. Display Sine, cosine & polynomial
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def sine_curve():
Fs= 8000
f=5
sample = 8000
x=np.arange(sample)
y=np.sin(2*np.pi*f*x/Fs)
plt.plot(x, y)
plt.xlabel('voltage(V)')
plt.ylabel('sample(n)')
plt.show()
def cosine_curve():
Fs = 8000
f= 5
sample= 8000
x = np.arange(sample)
y = np.cos(2*np.pi*f*x/Fs)
plt.plot(x, y)
plt.xlabel('voltage(V)')
plt.ylabel('sample(n)')
plt.show()
def polynomial_curve():
x= np.arange(-5, 5, 0.25)
y= np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(x, y)
F= 3+2*X + 4*X*Y + 5*X*X
fig= plt.figure()
ax= fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, F)
plt.show()
def menu():
print('1. Sine Curve')
print('2. Cosine Curve')
print('3. Polynomial Curve')
ch = 'y'
while(ch=='y'):
menu()
choice = int(input('Enter choice...'))
if(choice ==1):
sine_curve()
elif(choice==2):
cosine_curve()
elif(choice==3):
polynomial_curve()
else:
print('Wrong choice')
ch = input('Do you want to continue (y/n)...')
OUTPUT
Sine
Cosine
Polynomial
14. Pulse vs Height graph
import scipy.interpolate as inter
import numpy as np
import matplotlib.pyplot as plt
p, h = list(), list()
print("Pulse vs Height Graph:-n")
n = input("How many records? ")
print("nEnter the pulse rate values: ")
for i in range(int(n)):
pn = input()
p.append(int(pn))
x = np.array(p)
print("nEnter the height values: ")
for i in range(int(n)):
hn = input()
h.append(int(hn))
y = np.array(h)
print("nPulse vs Height graph is generated!")
z = np.arange(x.min(), x.max(), 0.01)
s = inter.InterpolatedUnivariateSpline(x, y)
plt.plot (x, y, 'b.')
plt.plot (z, s(z), 'g-')
plt.xlabel('Pulse')
plt.ylabel('Height')
plt.title('Pulse vs Height Graph')
plt.show()
OUTPUT:
15. Write a Python function that takes two lists and returns True if they
have at least one common member.
def test_includes_any(nums, lsts):
for x in lsts:
if x in nums:
return True
return False
def underline(text):
print("u0332".join(text))
underline("Case - I : No Common Elements")
print(test_includes_any([10, 20, 30, 40, 50, 60], [22, 42]))
def underline(text):
print("u0332".join(text))
underline("Case - II : At least one Common Element")
print(test_includes_any([10, 20, 30, 40, 50, 60], [20, 80]))
OUTPUT
16. Write a Python program to print a specified list after removing the
0th,2nd,4th and 5th elements.
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow','Orange','Blue']
color = [x for (i,x) in enumerate(color) if i not in (0,2,4,5)]
print(color)
OUTPUT
17. Write a python program to implement exception handling
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
OUTPUT
18. Write a python program to change background color of Tkinter Option Menu
widget
# Python program to change menu background
# color of Tkinter's Option Menu
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title("DRW App")
# Construct the label in your app
l1 = Label(app, text="Choose the week day here")
# Display the label l1
l1.grid()
# Construct the Options Menu widget in your app
text1 = StringVar()
# Set the value you wish to see by default
text1.set("Choose here")
# Create options from the Option Menu
w = OptionMenu(app, text1, "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
# Se the background color of Options Menu to green
w.config(bg="GREEN", fg="WHITE")
# Set the background color of Displayed Options to Red
w["menu"].config(bg="RED")
# Display the Options Menu
w.grid(pady=20)
# Make the loop for displaying app
app.mainloop()
OUTPUT

III MCS python lab (1).pdf

  • 1.
    1. Python programto demonstrate Arithmetic and Relational operators. x = 15 y = 4 print('x + y =',x+y) print('x - y =',x-y) print('x * y =',x*y) print('x / y =',x/y) print('x // y =',x//y) print('x ** y =',x**y) print('x > y is',x>y) print('x < y is',x<y) print('x == y is',x==y) print('x != y is',x!=y) print('x >= y is',x>=y) print('x <= y is',x<=y)
  • 2.
  • 3.
    2. Python programto Create a list and perform the following methods 1) insert() 2) remove() 3) append() 4) len() 5) pop() 6) clear() a=[1,3,5,6,7,[3,4,5],"hello"] print(a) a.insert(3,20) print(a) a.remove(7) print(a) a.append("hi") print(a) len(a) print(a) a.pop() print(a) a.pop(6) print(a) a.clear() print(a)
  • 4.
  • 5.
    3. Write aPython program to convert temperatures to and from Celsius and Fahrenheit. temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ") degree = int(temp[:-1]) i_convention = temp[-1] if i_convention.upper() == "C": result = int(round((9 * degree) / 5 + 32)) o_convention = "Fahrenheit" elif i_convention.upper() == "F": result = int(round((degree - 32) * 5 / 9)) o_convention = "Celsius" else: print("Input proper convention.") quit() print("The temperature in", o_convention, "is", result, "degrees.") OUTPUT
  • 6.
    4. Python Programto Calculate Total Marks Percentage and Grade of a Student print("Enter the marks of five subjects::") subject_1 = float (input ()) subject_2 = float (input ()) subject_3 = float (input ()) subject_4 = float (input ()) subject_5 = float (input ()) total, average, percentage, grade = None, None, None, None # It will calculate the Total, Average and Percentage total = subject_1 + subject_2 + subject_3 + subject_4 + subject_5 average = total / 5.0 percentage = (total / 500.0) * 100 if average >= 90: grade = 'A' elif average >= 80 and average < 90: grade = 'B' elif average >= 70 and average < 80: grade = 'C' elif average >= 60 and average < 70: grade = 'D' else: grade = 'E' # It will produce the final output print ("nThe Total marks is: t", total, "/ 500.00")
  • 7.
    print ("nThe Averagemarks is: t", average) print ("nThe Percentage is: t", percentage, "%") print ("nThe Grade is: t", grade) OUTPUT
  • 8.
    5. Write aprogram to print Fibonacci series up to n terms in python num = 10 n1, n2 = 0, 1 print("Fibonacci Series:", n1, n2, end=" ") for i in range(2, num): n3 = n1 + n2 n1 = n2 n2 = n3 print(n3, end=" ") print() OUTPUT
  • 9.
    6. Write aPython program to calculate the sum and product of two compatible Matrices X = [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] print("Addition of two matrices") result = [[X[i][j] + Y[i][j] for j in range (len(X[0]))] for i in range(len(X))] for r in result: print(r) # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] print("Multiplication of two matrices")
  • 10.
    # result is3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) OUTPUT
  • 11.
    7.Write a functionthat takes a character and returns true if it is a vowel, false otherwise. def vowel(x): if x in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]: return "True" else: return "False " a = input ("Enter the letter :- ") print (vowel(a)) OUTPUT
  • 12.
    8. Python programto read last 5 lines of a file f=open('myfile.txt', 'w') f.write('line1') f.close() f=open('myfile.txt','a') f.write('nline2') f.write('nline3') f.write('nline4') f.write('nline5') f.write('nline6') f.write('nline7') f.write('nline8') f.write('nline9') f.write('nline10') f.close() # Python implementation to # read last N lines of a file # Function to read # last N lines of the file def LastNlines(fname, N):
  • 13.
    # opening fileusing with() method # so that file get closed # after completing work with open(fname) as file: # loop to read iterate # last n lines and print it for line in (file.readlines() [-N:]): print(line, end ='') # Driver Code: if __name__ == '__main__': fname = 'myfile.txt' N = 5 try: LastNlines(fname, N) except: print('File not found')
  • 14.
  • 15.
    9.Demonstration of Modulesin Python # importing built-in module math import math # using square root(sqrt) function contained # in math module print(math.sqrt(25)) # using pi function contained in math module print(math.pi) # 2 radians = 114.59 degrees print(math.degrees(2)) # 60 degrees = 1.04 radians print(math.radians(60)) # Sine of 2 radians print(math.sin(2)) # Cosine of 0.5 radians print(math.cos(0.5)) # Tangent of 0.23 radians print(math.tan(0.23)) # 1 * 2 * 3 * 4 = 24 print(math.factorial(4)) # importing built in module random import random # printing random integer between 0 and 5
  • 16.
    print(random.randint(0, 5)) # printrandom floating point number between 0 and 1 print(random.random()) # random number between 0 and 100 print(random.random() * 100) List = [1, 4, True, 800, "python", 27, "hello"] # using choice function in random module for choosing # a random element from a set such as a list print(random.choice(List)) # importing built in module datetime import datetime from datetime import date import time # Returns the number of seconds since the # Unix Epoch, January 1st 1970 print(time.time()) # Converts a number of seconds to a date object print(date.fromtimestamp(454554))
  • 17.
  • 18.
    10. Multithreading inpython # Python program to illustrate the concept # of threading import threading import os def task1(): print("Task 1 assigned to thread: {}".format(threading.current_thread().name)) print("ID of process running task 1: {}".format(os.getpid())) def task2(): print("nTask 2 assigned to thread: {}".format(threading.current_thread().name)) print("nID of process running task 2: {}".format(os.getpid())) if __name__ == "__main__": # print ID of current process print("ID of process running main program: {}".format(os.getpid())) # print name of main thread print("Main thread name: {}".format(threading.current_thread().name)) # creating threads t1 = threading.Thread(target=task1, name='t1') t2 = threading.Thread(target=task2, name='t2') # starting threads t1.start() t2.start() # wait until all threads finish t1.join() t2.join()
  • 19.
  • 20.
    11. Write apython program to create 3D object from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') theta1 = np.linspace(0, 2*np.pi, 100) r1 = np.linspace(-2, 0, 100) t1, R1 = np.meshgrid(theta1, r1) X1 = R1*np.cos(t1) Y1 = R1*np.sin(t1) Z1 = 5+R1*2.5 theta2 = np.linspace(0, 2*np.pi, 100) r2 = np.linspace(0, 2, 100) t2, R2 = np.meshgrid(theta2, r2) X2 = R2*np.cos(t2) Y2 = R2*np.sin(t2) Z2 = -5+R2*2.5 ax.set_xlabel('x axis') ax.set_ylabel('y axis') ax.set_zlabel('z axis') # ax.set_xlim(-2.5, 2.5) # ax.set_ylim(-2.5, 2.5)
  • 21.
    # ax.set_zlim(0, 5) ax.set_aspect('equal') ax.plot_surface(X1,Y1, Z1, alpha=0.8, color="blue") ax.plot_surface(X2, Y2, Z2, alpha=0.8, color="blue") # ax.plot_surface(X, Y, Z, alpha=0.8) #fig. savefig ("Cone.png", dpi=100, transparent = False) plt.show()
  • 22.
  • 23.
    12. Read nintegers and display them as a histogram import matplotlib.pyplot as plt import numpy as np from matplotlib import colors from matplotlib.ticker import PercentFormatter # Creating dataset np.random.seed(23685752) N_points = 10000 n_bins = 20 # Creating distribution x = np.random.randn(N_points) y = .8 ** x + np.random.randn(10000) + 25 # Creating histogram fig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) axs.hist(x, bins = n_bins) # Show plot plt.show()
  • 24.
  • 25.
    13. Display Sine,cosine & polynomial import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def sine_curve(): Fs= 8000 f=5 sample = 8000 x=np.arange(sample) y=np.sin(2*np.pi*f*x/Fs) plt.plot(x, y) plt.xlabel('voltage(V)') plt.ylabel('sample(n)') plt.show() def cosine_curve(): Fs = 8000 f= 5 sample= 8000 x = np.arange(sample) y = np.cos(2*np.pi*f*x/Fs) plt.plot(x, y) plt.xlabel('voltage(V)') plt.ylabel('sample(n)') plt.show() def polynomial_curve():
  • 26.
    x= np.arange(-5, 5,0.25) y= np.arange(-5, 5, 0.25) X, Y = np.meshgrid(x, y) F= 3+2*X + 4*X*Y + 5*X*X fig= plt.figure() ax= fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, F) plt.show() def menu(): print('1. Sine Curve') print('2. Cosine Curve') print('3. Polynomial Curve') ch = 'y' while(ch=='y'): menu() choice = int(input('Enter choice...')) if(choice ==1): sine_curve() elif(choice==2): cosine_curve() elif(choice==3): polynomial_curve() else: print('Wrong choice') ch = input('Do you want to continue (y/n)...')
  • 27.
  • 28.
  • 29.
    14. Pulse vsHeight graph import scipy.interpolate as inter import numpy as np import matplotlib.pyplot as plt p, h = list(), list() print("Pulse vs Height Graph:-n") n = input("How many records? ") print("nEnter the pulse rate values: ") for i in range(int(n)): pn = input() p.append(int(pn)) x = np.array(p) print("nEnter the height values: ") for i in range(int(n)): hn = input() h.append(int(hn)) y = np.array(h) print("nPulse vs Height graph is generated!") z = np.arange(x.min(), x.max(), 0.01)
  • 30.
    s = inter.InterpolatedUnivariateSpline(x,y) plt.plot (x, y, 'b.') plt.plot (z, s(z), 'g-') plt.xlabel('Pulse') plt.ylabel('Height') plt.title('Pulse vs Height Graph') plt.show()
  • 31.
  • 32.
    15. Write aPython function that takes two lists and returns True if they have at least one common member. def test_includes_any(nums, lsts): for x in lsts: if x in nums: return True return False def underline(text): print("u0332".join(text)) underline("Case - I : No Common Elements") print(test_includes_any([10, 20, 30, 40, 50, 60], [22, 42])) def underline(text): print("u0332".join(text)) underline("Case - II : At least one Common Element") print(test_includes_any([10, 20, 30, 40, 50, 60], [20, 80]))
  • 33.
  • 34.
    16. Write aPython program to print a specified list after removing the 0th,2nd,4th and 5th elements. color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow','Orange','Blue'] color = [x for (i,x) in enumerate(color) if i not in (0,2,4,5)] print(color) OUTPUT
  • 35.
    17. Write apython program to implement exception handling # Program to handle multiple errors with one # except statement # Python 3 def fun(a): if a < 4: # throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print("Value of b = ", b) try: fun(3) fun(5) # note that braces () are necessary here for # multiple exceptions except ZeroDivisionError: print("ZeroDivisionError Occurred and Handled") except NameError: print("NameError Occurred and Handled")
  • 36.
  • 37.
    18. Write apython program to change background color of Tkinter Option Menu widget # Python program to change menu background # color of Tkinter's Option Menu # Import the library tkinter from tkinter import * # Create a GUI app app = Tk() # Give title to your GUI app app.title("DRW App") # Construct the label in your app l1 = Label(app, text="Choose the week day here") # Display the label l1 l1.grid() # Construct the Options Menu widget in your app text1 = StringVar() # Set the value you wish to see by default text1.set("Choose here") # Create options from the Option Menu w = OptionMenu(app, text1, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") # Se the background color of Options Menu to green w.config(bg="GREEN", fg="WHITE") # Set the background color of Displayed Options to Red w["menu"].config(bg="RED")
  • 38.
    # Display theOptions Menu w.grid(pady=20) # Make the loop for displaying app app.mainloop() OUTPUT