Program File
Program File
SOURCE CODE:
PYTHON_Calculator.py
#Addition
def add(a,b):
return a+b
#Subtract
def sub(a,b):
return a-b
#Multiply
def mul(a,b):
return a*b
#Divide
def div(a,b):
return a/b
#Exponents
def exp(a,b):
return a**b
choice=int(input("Select operation \n 1.Addition \n 2.Subtract \n 3.Multiply \n 4.Divide \n
5.Exponents \n 6.Exit \n"))
while choice!=6:
if choice>6:
if choice==1:
elif choice==2:
elif choice==3:
elif choice==4:
elif choice==5:
else:
break
else:
print("BYE BYE!!!")
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 2
OBJECTIVE: To create a program for a simple Temperature converter in python.
SOURCE CODE:
Functions:
temp.py
def in_f(c):
return (c*9//5)+32
def in_c(f):
return (f-32)*5//9
Program:
PYTHON_tempconverter.py
import temp
while choice!=3:
if choice>3:
if choice==1:
elif choice==2:
else:
break
else:
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 3
OBJECTIVE: To create packages in python and create a program for simple Mensuration
calculations with the use of user-defined packages.
SOURCE CODE:
Functions:
#RECTANGLE
def rectangle_area(l,b):
return l*b
def rectangle_perimeter(l,b):
return 2*(l+b)
#SQUARE
def square_area(s):
return s*s
def square_perimeter(s):
return 4*s
#TRIANGLE
def triangle_area(b,h):
return 1/2*b*h
def triangle_perimeter(a,b,c):
return a+b+c
#CIRCLE
def circle_area(r):
return 3.14*r**2
def circle_perimeter(r):
return 2*3.14*r
#CUBE
def cube_area(a):
return 6*a**2
def cube_volume(a):
return a**3
#CUBOID
def cuboid_area(l,b,h):
return 2*(l*b+b*h+h*l)
def cuboid_volume(l,b,h):
return l*b*h
#CYLINDER
def cylinder_area(h,r):
return 2*3.14*r*(r+h)
def cylinder_volume(h,r):
return 2*3.14*r*h
#CONE
def cone_area(l,r):
return 3.14*r*l
def cone_volume(l,r,h):
return 1/3*3.14*r**2*h
#SPHERE
def sphere_area(r):
return 4*3.14*r**2
def sphere_volume(r):
return 4/3*3.14*r**3
Program:
PYTHON_Mensuration_Calculator.py
while a!=3:
if a==1:
if c==1:
if b==1:
else:
elif c==2:
if b==1:
else:
elif c==3:
else:
elif c==4:
if b==1:
else:
else:
break
print()
elif a==2:
if c==1:
if b==1:
else:
if b==1:
else:
elif c==3:
if b==1:
else:
elif c==4:
if b==1:
else:
elif c==5:
if b==1:
else:
print("Area of sphere is: ",function_3D.sphere_area(x))
else:
break
print()
else:
SCREENSHOTS:
P.T.O
CONCLUSION:
The program is successfully executed.
PROGRAM 4
OBJECTIVE: (A) To create a program for calculating factorial of a given number.
SOURCE CODE:
Program (A):
Factorial.py
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
print(factorial(a))
Program (B):
fibonacci_series.py
def fibo(n):
if n<=1:
return n
else:
return fibo(n-1)+fibo(n-2)
for i in range(a):
print(fibo(i))
SCREENSHOT (A):
P.T.O
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 5
OBJECTIVE:
(A). Write a function that takes one argument (a positive integer) and reports if the argument is prime
or not. Write a program that invokes this function.
(B). Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns
the amount converted to rupees. Create the function in both void and non-void form
SOURCE CODE:
Program (A):
prime_test.py
def test_prime(n):
if n==1:
elif n==2:
else:
for x in range(2,n):
if n%x==0:
for j in range(0,5):
print(test_prime(a))
Program (B):
dollar_to_rupee_converter.py
#void version
def usd_to_inr(amt):
exc=71.08
print("Rs",amt*exc)
#non-void version
def usd_to_inr2(amt):
exc=71.08
return amt*exc
usd_to_inr(100)
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 6
OBJECTIVE:
(A). Write a program that inputs a main string and then creates an encrypted string by
embedding a short symbol based string after each character. The program should also be able to
produce the decrypted string from encrypted string.
(B). Write a number to implement ‘guess a number’ game. Python generates a number
randomly in the range[10,50]. The user is given five chances to guess a number in the range 10
<= number <= 50.
If the user’s guess matches the number generated, Python displays ‘You win’ and the loop
terminates without completing the five iterations.
If, however, cannot guess the number in five attempts, Python displays ‘You lose’.
SOURCE CODE:
Program (A):
String_encryptor _test.py
def encrypt(str,enkey):
return enkey.join(str)
def decrypt(str,enkey):
return str.split(enkey)
#main program
enStr=encrypt(mainString,encryptStr)
decStr=decrypt(enStr,encryptStr)
orig_decStr="".join(decStr)
print("The encrypted string is: ",enStr)
Program (B):
guess_a_number_game.py
import random
guessesTaken = 0
number = random.randint(10,50)
while guessesTaken<5:
guessesTaken+=1
if guess == number:
break
if guess == number:
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 7
OBJECTIVE:
(A). Write a program to get http request from url www.ted.com and open it from within your
program.
(B). Write a program to count the words “to” and “the” present in a text file “Poem.txt”
SOURCE CODE:
Program (A):
http_req_url.py
import urllib
import webbrowser
weburl=url.request.urlopen('http://www.ted.com/')
html=weburl.read()
data=weburl.geturl()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info()
print("Headers returned:\n",hd)
webbrowser.open_new(url)
Program (B):
count_words_from_text.py
f=open('Poem.txt','r')
c_to=0
c_the=0
for line in f:
c_to+=line.count('to')
c_the+=line.count('the')
print(c_to)
print(c_the)
f.close()
Poem.txt
Feeling so out-of-place.
SCREENSHOT (A):
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 8
OBJECTIVE:
(A). Create a file sports.dat contains information in the following format: Event ~ Participant.
Write a function that would read contents from the file sports.dat and creates a file named
Atheletic.dat copying only those records from sports.dat where the event name is “Atheletics”
(B). Write a recursive function to print a string backwards.
SOURCE CODE:
Program (A):
copying_records.py
#creating sports.dat
f1=open("sports.dat","w")
f2=open("atheletics.dat","w")
f1.write("EVENT ~ PARTICIPENTS\n")
for i in range(count):
rec=e+" ~ "+p+'\n'
f1.write(rec)
f2.write("EVENT ~ PARTICIPENTS\n")
f1=open("sports.dat","r")
words=line.split(" ")
if words[0]=="Atheletics":
f2.write(line)
f1.close()
f2.close()
Program (B):
reverse_string.py
def recursiveReverse(str,i=0):
n=len(str)
if i==n//2:
return
str[i],str[n-i-1]=str[n-i-1],str[i]
recursiveReverse(str,i+1)
# item assignment
org_lst=list(org_str)
recursiveReverse(org_lst)
rev_str=''.join(org_lst)
print(rev_str)
SCREENSHOT (A):
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 9
OBJECTIVE:
(A). Write a recursive function to calculate the gcd of given two numbers
(B). Write a recursive code to compute factorial of a given number.
(C). Write a recursive function to implement binary search algorithm.
SOURCE CODE:
Program (A):
GCD_recursively.py
def gcd(p,q):
if q==0:
return p
return gcd(q,p%q)
print()
print()
Program (B):
factorial_recursively.py
def factorial(n):
if n<2:
return 1
return n*factorial(n-1)
for i in range(3):
print()
Program (C):
Binary_search_recursively.py
def bin_ser(ar,key,low,high):
if low>high:
return -1
mid=int((low+high)//2)
if key==ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
return bin_ser(ar,key,low,high)
else:
low=mid+1
return bin_ser(ar,key,low,high)
#__main__
#sorted array
res=bin_ser(ary,item,0,len(ary)-1)
if res>=0:
else:
SCREENSHOT (B):
SCREENSHOT (C):
CONCLUSION:
The program is successfully executed.
PROGRAM 10
OBJECTIVE:
Create an array in the range 1 to 20 with values 1.25 apart. Another array contains the log
values of the elements in the first array.
(A). Simply plot the two arrays first vs second in a line chart.
(B). In the plot of first vs second array, specify the x-axis(containing first array’s values) title
as ‘Random Values’ and y-axis title as ‘Logarithm Values’
(C). Create a third array that stores the Cos values of first array and then plot both the second
and third arrays vs first array. The cos values should be plotted with a dash-dotted line.
(D). Change the marker type as circle with blue color in second array.
(E). Only mark the data points as this: second array data points as blue small diamonds, third
array data points as black circles.
CONCEPT USED: Using NumPy Arrays and its useful functions. Creating charts with
matplotlib library’s pyplot interface.
SOURCE CODE:
Ploting_two_ary.py
(A).
import numpy as np
a=np.arange(1,20,1.25)
b=np.log(a)
plt.plot(a,b)
(B).
plt.plot(a,b)
plt.xlabel("Random Values")
plt.ylabel("Logarithm Values")
plt.show()
(C).
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,linestyle="dashdot")
plt.show()
(D).
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,'bo',linestyle='dashdot')
plt.show()
(E).
c=np.cos(a)
plt.plot(a,b,'bd')
plt.plot(a,c,'ro')
plt.show()
SCREENSHOT:
(A).
(B).
(C).
(D).
(E).
CONCLUSION:
The program is successfully executed.
PROGRAM 11
OBJECTIVE:
Carefully go through the average data for Mumbai city from the Indian Met Department.
Jan Feb Mar Apr May Jun
High 31.1 31.3 32.8 33.2 33.6 32.4
Temp
Low 17.3 18.2 21.4 24.2 27.0 26.6
Temp
Rainfall 0.3 0.4 0.0 0.1 11.3 493.1
Relatie 69 67 69 71 70 80
Humiity
(A). Plot the four sequences on a bar chart where red color shows the HighTemp, blue colour
shoes the LowTemp, olive colour depicts the Rainfall sequence and silver colour depicts the
RelHumidity sequence.
(B). Make width of these bars as 0.28
(C). Change the x-ticks such that they display the month numbers in place of month names
(D). Add legends for these providing meaningful labels for these sequences
(E). Give appropriate title for the chart and axes
(F). Save the chart as “multibar.pdf”
CONCEPT USED: Using NumPy Arrays and its useful functions. Creating charts with
matplotlib library’s pyplot interface.
SOURCE CODE:
Bar_graph.py
(A).
import numpy as np
a=['Jan','Feb','Mar','Apr','May','Jun']
A=np.arange(len(a))
B=[[31.1,31.3,32.8,33.2,33.6,33.4],[17.3,18.2,21.2,24.2,27.0,26.6],[0.3,0.4,0.0,0.1,11.3,49.3],
[69.,67.,69.,71.,70.,80.]]
plt.bar(A+0.00,B[0],color='red',width=0.28,label='High Temperature')
plt.bar(A+0.28,B[1],color='blue',width=0.28,label='LowTemperature')
plt.bar(A+0.56,B[2],color='olive',width=0.28,label='Rainfall')
plt.bar(A+0.81,B[3],color='silver',width=0.28,label='Relative Humidity')
plt.legend(loc='upper left')
plt.xlabel("Month numbers")
plt.ylabel("Measurements")
plt.show()
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 12
OBJECTIVE:
Write to create a pie for sequence con = [23.4, 17.8, 25, 34, 40] for Zones = [‘East’, ‘West’,
‘North’, ‘South’, ‘Central’]
(A) Show North zone’s value exploded
(B). Show % contribution for each zone
(C). The pie chart should be circular.
SOURCE CODE:
pie_chart.py
con=[23.4,17.8,25,34,40]
zones=['East','West','North','South','Central']
plt.axis("equal")
plt.pie(con,labels=zones,explode=[0,0,0.2,0,0],autopct="%1.2f%%")
plt.show()
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 13
OBJECTIVE:
Write a menu driven program to do the following tasks:
(A). Traverse through a sorted list
(B). Search for an element in a sorted list by implementing Linear Search algorithm
SOURCE CODE:
Program (A):
traversal.py
def traverse(AR):
size=len(AR)
for i in range(size):
print(AR[i],end=' ')
#__main__
AR=[None]*size
for i in range(size):
traverse(AR)
Program (B):
Linear_search.py
def lsearch(ar,item):
i=0
i+=1
if i<len(ar):
return i
else:
return False
ar=[0]*n
for i in range(n):
index=lsearch(ar,item)
if index:
else:
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 14
OBJECTIVE:
Write a menu driven program to do the following tasks:
(A). Insert an element in a sorted list
(B). Delete an element from a sorted list
SOURCE CODE:
Program (A):
element_insertion.py
ar=[0]*n
for i in range(n):
import bisect
ind=bisect.bisect(ar,item)
bisect.insort(ar,item)
print(ar)
Program (B):
element_deletion.py
def bsearch(ar,item):
beg=0
last=len(ar)-1
while beg<=last:
mid=(beg+last)//2
if item==ar[mid]:
return mid
elif item>ar[mid]:
beg=mid+1
else:
last=mid-1
else:
return False
ar=[0]*n
for i in range(n):
pos=bsearch(ar,item)
if pos:
del ar[pos]
print(ar)
else:
SCREENSHOT (A):
SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 15
OBJECTIVE:
Use a list comprehension to create a list, CB4. The comprehension should consist of the
cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. Finally, print
that list to the console. Note that in this case, the cubed number should be evenly divisible by
4, not the original number
SOURCE CODE:
CB4.py
print(CB4)
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 16
OBJECTIVE: Write a menu based program to implement Stack operations.
CONCEPT USED: Creating functions and implementing them & some basics of python.
SOURCE CODE:
stack.py
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "Underflow!"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
return"Stack empty"
else:
top=len(stk)-1
print("\n",stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
#__main__
stack=[]
top=None
while True:
if ch==1:
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="Underflow":
else:
elif ch==3:
item=peek(stack)
if item=="Underflow":
else:
elif ch==4:
display(stack)
elif ch==5:
break
else:
print("\nINVALID choice!!")
SCREENSHOT:
CONCLUSION:
The program is successfully executed.
PROGRAM 17
OBJECTIVE: Write a menu based program to implement Queue operations.
CONCEPT USED: Creating functions and implementing them & some basics of python.
SOURCE CODE:
queue.py
def cls():
print("\n"*2)
def isempty(qu):
if qu==[]:
return True
else:
return False
def enqueue(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def dequeue(qu):
if isempty(qu):
return "Underflow!"
else:
item=qu.pop(0)
if len(qu)==0:
front=rear=None
return item
def peek(qu):
if isempty(qu):
return "Underflow"
else:
front=0
return qu[front]
def display(qu):
if isempty(qu):
return"Queue empty!"
elif len(qu)==1:
print(qu[0],"<-FRONT,REAR")
else:
front=0
rear=len(qu)-1
print(qu[front],"<-FRONT")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<-REAR")
#__main__
queue=[]
front=None
while True:
cls()
if ch==1:
enqueue(queue,item)
elif ch==2:
item=dequeue(queue)
if item=="Underflow":
else:
elif ch==3:
item=peek(queue)
if item=="Underflow":
print("Queue is empty")
else:
elif ch==4:
display(queue)
elif ch==5:
break
else:
print("\nINVALID choice!!")
SCREENSHOT
CONCLUSION:
The program is successfully executed.
PROGRAM 18
OBJECTIVE: Create a Django based web application.
CONCEPT USED: Creating functions and implementing them & some basics of python.
SOURCE CODE:
queue.py
def cls():
print("\n"*2)
def isempty(qu):
if qu==[]:
return True
else:
return False
def enqueue(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def dequeue(qu):
if isempty(qu):
return "Underflow!"
else:
item=qu.pop(0)
if len(qu)==0:
front=rear=None
return item
def peek(qu):
if isempty(qu):
return "Underflow"
else:
front=0
return qu[front]
def display(qu):
if isempty(qu):
return"Queue empty!"
elif len(qu)==1:
print(qu[0],"<-FRONT,REAR")
else:
front=0
rear=len(qu)-1
print(qu[front],"<-FRONT")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<-REAR")
#__main__
queue=[]
front=None
while True:
cls()
if ch==1:
enqueue(queue,item)
elif ch==2:
item=dequeue(queue)
if item=="Underflow":
else:
elif ch==3:
item=peek(queue)
if item=="Underflow":
print("Queue is empty")
else:
elif ch==4:
display(queue)
elif ch==5:
break
else:
print("\nINVALID choice!!")
SCREENSHOT
CONCLUSION:
The program is successfully executed.