Python Programs
Python Programs
Question:1
Write a python script to take input for a number calculate and print its
square and cube?
Write a python script to take input for 2 numbers calculate and print
their sum, product and difference?
Write a python script to take input for 3 numbers, check and print the
largest number?
Method:2
Write a python script to take input for name and age of a person check
and print whether the person can vote or not?
Write a python script to take input for a number and print its table?
Write a python script to take input for a number and print its factorial?
Write a python script to take input for a number check if the entered
number is Armstrong or not.
Write a python script to take input for a number and print its factorial
using recursion?
Sol:
Write a python program to maintain book details like book code, book
title and price using stacks data structures? (implement push(), pop()
and traverse() functions)
Sol:
"""
push
pop
traverse
"""
book=[]
def push():
bcode=input("Enter bcode ")
btitle=input("Enter btitle ")
price=input("Enter price ")
bk=(bcode,btitle,price)
book.append(bk)
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode ",bcode," btitle ",btitle," price ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
Question:12
def count_alpha():
lo=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
lo=lo+1
print("total lower case alphabets ",lo)
#function calling
count_alpha()
Question:14
def count():
a=0
ua=0
la=0
d=0
sp=0
spl=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
a=a+1
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
a=a+1
if(c>='A' and c<='Z'):
ua=ua+1
else:
la=la+1
elif(c>='0' and c<='9'):
d=d+1
elif(c==' '):
sp=sp+1
else:
spl=spl+1
print("total alphabets ",a)
print("total upper case alphabets ",ua)
print("total lower case alphabets ",la)
print("total digits ",d)
print("total spaces ",sp)
print("total special characters ",spl)
# function calling
count()
Question: 15
Write a python program to read a file named “story.txt”, count and print
total words starting with “a” or “A” in the file?
Sol:
def count_words():
w=0
with open("story.txt") as f:
for line in f:
for word in line.split():
if(word[0]=="a" or word[0]=="A"):
print(word)
w=w+1
print("total words starting with 'a' are ",w)
# function calling
count_words()
Question: 16
Write a python program to read a file named “story.txt”, count and print
total lines starting with vowels in the file?
Sol:
filepath = 'story.txt'
vowels="AEIOUaeiou"
line = fp.readline()
cnt = 1
while line:
if(line[0] in vowels):
#print(line)
cnt=cnt+1
line = fp.readline()
Question: 17
import numpy as np
xvals=np.arange(-2,1,0.01)
plt.plot(xvals,yvals)
plt.grid(True)
plt.show()
Question:18
import numpy as np
objects=("python","c++","Java","Perl","C","Lisp")
y_pos=np.arange(len(objects))
performance=[10,8,5,4,2,1]
plt.xlabel="Usage"
plt.ylabel="Languages"
plt.bar(y_pos,performance,align="center",width=.5, color='r')
plt.barh(y_pos,performance,align="center", color='r')
plt.show()
Question:19
Write a function to insert a record in table using python and MySQL interface.
Sol:
def insert_data():
#take input for the details and then save the record in the databse
import pymysql
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
c = db.cursor()
try:
db.commit()
print("Record saved")
except:
db.rollback()
db.close()
# function calling
insert_data()
Program 20:
Write a function to display all the records stored in a table using python and MySQL interface.
Sol:
def display_all():
#field by field
import pymysql
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
try:
c = db.cursor()
c.execute(sql)
countrow=c.execute(sql)
#data=a.fetchone()
data=c.fetchall()
#print(data)
print("=========================")
print("=========================")
r=eachrow[0]
n=eachrow[1]
p=eachrow[2]
# Now print fetched result
print("=========================")
except:
db.rollback()
db.close()
# function calling
display_all()
Program :21
Write a function to search a record stored in a table using python and MySQL interface.
Sol:
def search_roll():
#field by field
import pymysql
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
try:
z=0
c = db.cursor()
c.execute(sql)
countrow=c.execute(sql)
#data=a.fetchone()
data=c.fetchall()
#print(data)
r=eachrow[0]
n=eachrow[1]
p=eachrow[2]
# Now print fetched result
if(r==roll):
z=1
print(r,n,p)
if(z==0):
except:
db.rollback()
db.close()
# function calling
search_roll()