Python Lab Manual 2018 by K.Kesavapandian
Python Lab Manual 2018 by K.Kesavapandian
Program:
print("Select operation.")
print("1.Fahrenheit to Celsius")
print("2.Celsius to Fahrenheit")
if choice == 1:
fahrenheit = float(fah)
celsius = (fahrenheit-32)/1.8
elif choice == 2:
celsius = float(cel)
fahrenheit = (1.8*celsius) + 32
else:
print("Invalid input")
1
Output:
Select operation.
1.Fahrenheit to Celsius
2.Celsius to Fahrenheit
Enter choice(1/2):1
Enter choice(1/2):2
2
2. Student Mark List
Program:
sub1=int(input("Enter marks of the first subject: "))
tot=sub1+sub2+sub3
avg=tot/3
if(avg>=80):
print("Grade: A")
print("Grade: B")
print("Grade: C")
print("Grade: D")
else:
print("Grade: F")
Output:
Grade: C
3
3. Calculate area of Square, Circle, Triangle,
Rectangle
Program:
print("Select operation.")
print("1.Area of Square")
print("2.Area of Circle")
print("3.Area of Triangle")
print("4.Area of Rectangle")
if choice == 1:
side_length = int(side);
area_square = side_length*side_length;
elif choice == 2:
radius = float(rad);
elif choice == 3:
4
a = float(side1);
b = float(side2);
c = float(side3);
s = (a + b + c)/2;
elif choice == 4:
length = int(leng);
breadth = int(brea);
area = length*breadth;
else:
print("Invalid input")
Output:
Select operation.
1. Area of Square
2. Area of Circle
3. Area of Triangle
4. Area of Rectangle
Area of Square = 36
5
Enter choice (1/2/3/4):2
Area of Rectangle = 63
6
4. Fibonacci Series
Program:
nterms = int(input("How many terms? "));
n1 = 0
n2 = 1
count = 0
if nterms <= 0:
elif nterms == 1:
print n1
else:
print n1
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:
How many terms? 10
0 1 1 2 3 5 8 13 21 34
7
5. Factorial Number
Program:
num = input("Enter a number to find its factorial: ");
number = int(num);
if number == 0:
print("\nFactorial of 0 is 1");
else:
fact = 1;
fact = fact*i;
print(fact);
Output:
Factorial of 5
24
120
8
6. Sum of Natural Numbers
Program:
print("Enter '0' for exit.")
if num == 0:
exit();
else:
sum = 0;
sum += num;
num -= 1;
Output:
9
7. Sum and Product of the Matrices
Program:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
for r in result:
print(r)
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
for r in result:
print(r)
10
Output:
[17, 15, 4]
[10, 12, 9]
11
8. Mathematical Objects in 3D Images
Program:
from visual import *
print("Select operation.");
print("1.Curve");
print("2.Sphere");
print("3.Cone");
print("4.Arrow");
print("5.Ring");
print("6.Cylinder");
if choice == 1:
elif choice == 2:
elif choice == 3:
elif choice == 4:
elif choice == 5:
elif choice == 6:
else:
12
print("Invalid input")
Output:
13
9. Histogram for the Numbers
Program:
def histogram( items ):
for n in items:
output = ''
times = n
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Output:
Histogram for the numbers:
**
***
******
*****
14
10. Show Sine, Cosine, Exponential, Polynomial
Curves
Program:
print("Select Operation")
if choice == 1:
x = numpy.linspace(-pi,pi,100)
ysin=sin(x)
ycos=cos(x)
def Create_plot(c,v,b,n,m):
plt.plot(c,v)
plt.plot(c,b)
plt.ylabel("y")
plt.xlabel("x")
plt.legend((n,m))
plt.show()
Create_plot(x,ysin,ycos,'sin(x)','cos(x)')
15
elif choice == 2:
import numpy as np
a = 5
b = 2
c = 1
y = (a * np.exp(-b*x)) + c
axes = plt.gca()
axes.set_xlim([x.min(), x.max()])
axes.set_ylim([y.min(), y.max()])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Exponential Curve')
plt.legend(loc='upper left')
plt.show()
elif choice == 3:
import numpy as np
a = 3
b = 4
c = 2
y = (a * (x * x)) + (b * x) + c
16
plt.plot(x, y, '-g', label=r'$y = 3x^2 + 4x + 2$')
axes = plt.gca()
axes.set_xlim([x.min(), x.max()])
axes.set_ylim([y.min(), y.max()])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Polynomial Curve')
plt.legend(loc='upper left')
plt.show()
Output:
17
11. Calculate the pulse and height rate graph
Program:
import scipy.interpolate as inter
import numpy as np
p, h = list(), list()
for i in range(int(n)):
pn = input()
p.append(int(pn))
x = np.array(p)
for i in range(int(n)):
hn = input()
h.append(int(hn))
y = np.array(h)
s = inter.InterpolatedUnivariateSpline(x, y)
plt.xlabel('Pulse')
18
plt.ylabel('Height')
plt.show()
Output:
Pulse vs Height Graph:-
19
12. Calculate mass in a chemical reaction
Program:
import numpy as np
def chemical_reaction(t):
m = 60/(t+2)
plot.legend(loc='upper left')
plot.show()
t= np.arange(100);
chemical_reaction(t)
20
Output:
21
13. Initial velocity & acceleration and plot
graph
Program:
import matplotlib.pyplot as plt
a=int(input('Enter acceleration:'))
v=[]
t=[1,2,3,4,5,6,7,8,9,10]
for i in t:
v.append(u + (a*i))
plt.plot(t,v)
plt.axis([0,max(t)+2,0,max(v)+2])
plt.xlabel('Time')
plt.ylabel('Velocity')
plt.show()
s=[]
for i in t:
s.append(u*i+(0.5)*a*i*i)
plt.plot(t,s)
plt.axis([0,max(t)+2,0,max(s)+2])
plt.xlabel('Time')
plt.ylabel('Distance')
plt.show()
s=[]
22
for i in v:
s.append((i*i-u*u)/(2*a))
plt.plot(v,s)
plt.axis([0,max(v)+2,0,max(s)+2])
plt.xlabel('Velocity')
plt.ylabel('Distance')
plt.show()
Output:
Enter intial velocity:60
Enter acceleration:10
23
14. Checking Password using condition
Program:
special_str = "$#@"
accepted = []
lower = 0
upper = 0
digits = 0
special = 0
if char.islower():
lower += 1
elif char.isupper():
upper += 1
elif char.isdigit():
digits += 1
special += 1
if lower >= 1 and upper >= 1 and digits >= 1 and special >=
1 and len(password) in range(6,13):
accepted.append(password)
print (",".join(accepted))
24
Output:
Selected Password:
ABd1234@1
25
15. Tuples check under name, age and value
Program:
from operator import itemgetter
persons = []
while True:
if not line:
break
persons.append(tuple(line.split(',')))
print ("Output:")
print (','.join(person))
Output:
Enter the input values:
> tom,17,90
> rex,18,89
> zen,20,85
Output:
rex,18,89
tom,17,90
zen,20,85
26
16. Show the numbers divisible by 7
Program:
n=input("Enter the range n value:");
def putNumbers(n):
i = 0
while i<n:
j=i
i=i+1
if j%7==0:
yield j
for i in putNumbers(n):
print i
Output:
Enter the range n value:50
14
21
28
35
42
49
27
17. Direction of robot values
Program:
print ("Enter the input values:")
pos = {
"x": 0,
"y": 0
while True:
if not line:
break
if direction == "UP":
pos["y"] += int(steps)
pos["y"] -= int(steps)
pos["x"] -= int(steps)
pos["x"] += int(steps)
print ("Output:")
28
Output:
> UP 2
> DOWN 3
> LEFT 4
> RIGHT 4
>
Output:
1.0
29
18. Count the frequency of words in text
Program:
print("Enter the input:")
line = raw_input()
freq[word] = freq.get(word,0)+1
words = freq.keys();
words.sort()
for w in words:
Output:
Enter the input:
2:1
3?:1
New:1
Python:3
and:1
between:1
choosing:1
or:1
to:1
30