CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
III MCS python lab (1).pdf
1. 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)
5. 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
6. 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")
7. print ("nThe Average marks is: t", average)
print ("nThe Percentage is: t", percentage, "%")
print ("nThe Grade is: t", grade)
OUTPUT
8. 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
9. 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")
10. # 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
11. 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
12. 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):
13. # 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')
15. 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
16. 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))
18. 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()
29. 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)
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()
32. 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]))
34. 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
35. 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")
37. 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")
38. # Display the Options Menu
w.grid(pady=20)
# Make the loop for displaying app
app.mainloop()
OUTPUT