You are on page 1of 30

1.

Fahrenheit to Celsius and Vice Versa

Program:
print("Select operation.")

print("1.Fahrenheit to Celsius")

print("2.Celsius to Fahrenheit")

choice = input("Enter choice(1/2):")

if choice == 1:

fah = input("Enter Temperature in Fahrenheit: ")

fahrenheit = float(fah)

celsius = (fahrenheit-32)/1.8

print("Temperature in Celsius =%d" %celsius)

elif choice == 2:

cel = input("Enter Temperature in Celsius: ")

celsius = float(cel)

fahrenheit = (1.8*celsius) + 32

print("Temperature in Fahrenheit =%d" %fahrenheit)

else:

print("Invalid input")

1
Output:

Select operation.

1.Fahrenheit to Celsius

2.Celsius to Fahrenheit

Enter choice(1/2):1

Enter Temperature in Fahrenheit: 98.5

Temperature in Celsius = 36.94444444444444

Enter choice(1/2):2

Enter Temperature in Celsius: 36.944

Temperature in Fahrenheit = 98.4992

2
2. Student Mark List
Program:
sub1=int(input("Enter marks of the first subject: "))

sub2=int(input("Enter marks of the second subject: "))

sub3=int(input("Enter marks of the third subject: "))

tot=sub1+sub2+sub3

avg=tot/3

if(avg>=80):

print("Grade: A")

elif(avg>=70 and avg<80):

print("Grade: B")

elif(avg>=60 and avg<70):

print("Grade: C")

elif(avg>=40 and avg<60):

print("Grade: D")

else:

print("Grade: F")

Output:

Enter the marks

Enter marks of the first subject: 65

Enter marks of the second subject: 75

Enter marks of the third subject: 55

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

choice = input("Enter choice(1/2/3/4):")

if choice == 1:

side = input("Enter side length of Square: ");

side_length = int(side);

area_square = side_length*side_length;

print("\nArea of Square =%d" %area_square);

elif choice == 2:

rad = input("Enter radius of circle: ");

radius = float(rad);

area = 3.14 * radius * radius;

print("\nArea of Circle = %0.2f" %area);

elif choice == 3:

side1 = input("Enter length of first side: ");

side2 = input("Enter length of second side: ");

side3 = input("Enter length of third side: ");

4
a = float(side1);

b = float(side2);

c = float(side3);

s = (a + b + c)/2;

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5;

print("\nArea of Triangle = %0.2f" %area);

elif choice == 4:

leng = input("Enter length of Rectangle: ");

brea = input("Enter breadth of Rectangle: ");

length = int(leng);

breadth = int(brea);

area = length*breadth;

print("\nArea of Rectangle =%d" %area);

else:

print("Invalid input")

Output:

Select operation.

1. Area of Square

2. Area of Circle

3. Area of Triangle

4. Area of Rectangle

Enter choice (1/2/3/4):1

Enter side length of Square: 6

Area of Square = 36

5
Enter choice (1/2/3/4):2

Enter radius of circle: 7

Area of Circle = 153.86

Enter choice (1/2/3/4):3

Enter length of first side: 6

Enter length of second side: 7

Enter length of third side: 9

Area of Triangle = 20.98

Enter choice (1/2/3/4):4

Enter length of Rectangle: 9

Enter breadth of Rectangle: 7

Area of Rectangle = 63

6
4. Fibonacci Series

Program:
nterms = int(input("How many terms? "));

n1 = 0

n2 = 1

count = 0

if nterms <= 0:

print "Please enter a positive integer"

elif nterms == 1:

print("Fibonacci sequence upto :%d" %nterms);

print n1

else:

print("Fibonacci sequence upto :%d" %nterms);

while count < nterms:

print n1

nth = n1 + n2

n1 = n2

n2 = nth

count += 1

Output:
How many terms? 10

Fibonacci sequence upto: 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");

elif number < 0:

print("\nFactorial of negative numbers doesn't exist..!!");

else:

fact = 1;

print("\nFactorial of %d" %number)

for i in range(1, number+1):

fact = fact*i;

print(fact);

Output:

Enter a number to find its factorial: 5

Factorial of 5

24

120

8
6. Sum of Natural Numbers

Program:
print("Enter '0' for exit.")

num = int(input("Upto which number ? "))

if num == 0:

exit();

elif num < 1:

print("Kindly try to enter a positive number..exiting..")

else:

sum = 0;

while num > 0:

sum += num;

num -= 1;

print("Sum of natural numbers =%d " %sum);

Output:

Enter '0' for exit.

Upto which number ? 10

Sum of natural numbers= 55

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]]

print("Sum of two matrix");

for i in range(len(X)):

for j in range(len(X[0])):

result[i][j] = X[i][j] + Y[i][j]

for r in result:

print(r)

print("Product of two matrix");

for i in range(len(X)):

for j in range(len(Y[0])):

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

10
Output:

Sum of two matrix

[17, 15, 4]

[10, 12, 9]

[11, 13, 18]

Product of two matrix

[131, 175, 64]

[84, 109, 82]

[130, 170, 130]

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");

choice = input("Enter choice(1/2/3/4/5/6):")

if choice == 1:

fig1 = curve(pos=[(0,0,0), (1,0,0), (2,1,0)], radius=0.05)

elif choice == 2:

fig2 = sphere(pos=(1,2,1), radius=0.5)

elif choice == 3:

fig3 = cone(pos=(5,2,0), axis=(12,0,0),radius=1)

elif choice == 4:

fig4 = arrow(pos=(0,2,1), axis=(5,0,0), shaftwidth=1)

elif choice == 5:

fig5 = ring(pos=(1,1,1), axis=(0,1,0), radius=0.5,


thickness=0.1)

elif choice == 6:

fig6 = cylinder(pos=(0,2,1),axis=(5,0,0), radius=1)

else:

12
print("Invalid input")

Output:

13
9. Histogram for the Numbers

Program:
def histogram( items ):

for n in items:

output = ''

times = n

while( times > 0 ):

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

choice=input("Enter the choice1/2/3:")

if choice == 1:

import numpy, matplotlib

from numpy import sin, cos, pi

from matplotlib import pyplot as plt

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.title('Plot of sin(x) and cos(x) from -pi to pi')

plt.show()

Create_plot(x,ysin,ycos,'sin(x)','cos(x)')

15
elif choice == 2:

import numpy as np

import matplotlib.pyplot as plt

a = 5

b = 2

c = 1

x = np.linspace(0, 10, 256, endpoint = True)

y = (a * np.exp(-b*x)) + c

plt.plot(x, y, '-r', label=r'$y = 5e^{-2x} + 1$')

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

import matplotlib.pyplot as plt

a = 3

b = 4

c = 2

x = np.linspace(0, 10, 256, endpoint = True)

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

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')

18
plt.ylabel('Height')

plt.title('Pulse vs Height Graph')

plt.show()

Output:
Pulse vs Height Graph:-

How many records? 5

Enter the pulse rate values: 1 2 3 4 5

Enter the height values: 15 9 20 12 18

Pulse vs Height graph is generated!

19
12. Calculate mass in a chemical reaction

Program:
import numpy as np

import matplotlib.pyplot as plot

def chemical_reaction(t):

m = 60/(t+2)

plot.plot (t, m, 'b.')

plot.plot(t, m, '-g', label='m=60/(t+2), t>=0')

plot.title("calculate the mass m in a chemical reaction")

plot.legend(loc='upper left')

plot.show()

print "Wait for few seconds to generate chemical reaction graph"

print "See graphs in new figure windows"

t= np.arange(100);

chemical_reaction(t)

20
Output:

21
13. Initial velocity & acceleration and plot
graph

Program:
import matplotlib.pyplot as plt

u=int(input('Enter intial velocity:'))

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 = []

passwords = raw_input("Enter comma-separated passwords:


").split(',')

for password in passwords:

lower = 0

upper = 0

digits = 0

special = 0

for char in password:

if char.islower():

lower += 1

elif char.isupper():

upper += 1

elif char.isdigit():

digits += 1

elif special_str.find(char) != -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:

Enter comma-separated passwords: ABd1234@1,a F1!,2w3E*,2We3345

Selected Password:

ABd1234@1

25
15. Tuples check under name, age and value

Program:
from operator import itemgetter

persons = []

print ("Enter the input values:")

while True:

line = raw_input("> ")

if not line:

break

persons.append(tuple(line.split(',')))

persons = sorted(persons, key=itemgetter(0,1,2))

print ("Output:")

for person in persons:

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:

line = raw_input("> ")

if not line:

break

direction, steps = line.split()

if direction == "UP":

pos["y"] += int(steps)

elif direction == "DOWN":

pos["y"] -= int(steps)

elif direction == "LEFT":

pos["x"] -= int(steps)

elif direction == "RIGHT":

pos["x"] += int(steps)

print ("Output:")

print (round((pos["x"]**2 + pos["y"]**2)**0.5))

28
Output:

Enter the input values:

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

freq = {} # frequency of words in text

line = raw_input()

for word in line.split():

freq[word] = freq.get(word,0)+1

words = freq.keys();

words.sort()

for w in words:

print ("%s:%d" % (w,freq[w]))

Output:
Enter the input:

New to Python or choosing between Python 2 and Python 3?

2:1

3?:1

New:1

Python:3

and:1

between:1

choosing:1

or:1

to:1

30

You might also like