Python Programs-
Question:1
Write a python script to take input for a number calculate and print its
square and cube?
a=int(input("Enter any no "))
b=a*a
c=a*a*a
print("Square = ",b)
print("cube = ",c)
Question:2
Write a python script to take input for 2 numbers calculate and print
their sum, product and difference?
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s=a+b
p=a*b
if(a>b):
d=a-b
else:
d=b-a
print("Sum = ",s)
print("Product = ",p)
print("Difference = ",d)
Question:3
Write a python script to take input for 3 numbers, check and print the
largest number?
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
c=int(input("Enter 3rd no "))
if(a>b and a>c):
m=a
else:
if(b>c):
m=b
else:
m=c
print("Max no = ",m)
Method:2
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
c=int(input("Enter 3rd no "))
if(a>b and a>c):
m=a
elif(b>c):
m=b
else:
m=c
print("Max no = ",m)
Question:4
Write a python script to take input for 2 numbers and an operator (+ , – ,
* , / ). Based on the operator calculate and print the result?
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
op=input("Enter the operator (+,-,,/) ")
if(op=="+"):
c=a+b
print("Sum = ",c)
elif(op==""):
c=a*b
print("Product = ",c)
elif(op=="-"):
if(a>b):
c=a-b
else:
c=b-a
print("Difference = ",c)
elif(op=="/"):
c=a/b
print("Division = ",c)
else:
print("Invalid operator")
Question:5
Write a python script to take input for name and age of a person check
and print whether the person can vote or not?
name=input("Enter name ")
age=int(input("Enter age "))
if(age>=18):
print("you can vote")
else:
print("you cannot vote")
Question:6
Write a python script to take input for a number and print its table?
n=int(input("Enter any no "))
i=1
while(i<=10):
t=n*i
print(n," * ",i," = ",t)
i=i+1
Questions:7
Write a python script to take input for a number and print its factorial?
n=int(input("Enter any no "))
i=1
f=1
while(i<=n):
f=f*i
i=i+1
print("Factorial = ",f)
Question:8
Write a python script to take input for a number check if the entered
number is Armstrong or not.
n=int(input("Enter the number to check : "))
n1=n
s=0
while(n>0):
d=n%10;
s=s + (d *d * d)
n=int(n/10)
if s==n1:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
Question:9
Write a python script to take input for a number and print its factorial
using recursion?
Sol:
#Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
#for fixed number
num = 7
#using user input
num=int(input("Enter any no "))
check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Question:10
Write a python script to Display Fibonacci Sequence Using Recursion?
Sol:
#Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
#check if the number of terms is valid
if (nterms <= 0):
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Question: 11
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
Write a python program to maintain employee details like empno,name
and salary using Queues data structure? (implement insert(), delete()
and traverse() functions)
Sol:
#queue implementation (using functions)
#program to create a queue of employee(empno,name,sal).
"""
add employee
delete employee
traverse / display all employees
"""
employee=[]
def add_element():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def del_element():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop(0)
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(0,n):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Add employee");
print("2. Delete employee");
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
add_element()
elif(ch==2):
del_element();
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
Question:13
Write a python program to read a file named “article.txt”, count and
print total alphabets in the file?
Sol:
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
Write a python program to read a file named “article.txt”, count and
print the following:
(i). length of the file(total characters in file)
(ii).total alphabets
(iii). total upper case alphabets
(iv). total lower case alphabets
(v). total digits
(vi). total spaces
(vii). total special characters
Sol:
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"
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if(line[0] in vowels):
#print(line)
print("Line {}: {}".format(cnt, line.strip()))
cnt=cnt+1
line = fp.readline()
Question: 17
Python program to plot a sine wave using a line chart
Sol:
#program to plot a sine wave using a line chart
import matplotlib.pyplot as plt
import numpy as np
xvals=np.arange(-2,1,0.01)
yvals=np.sin(xvals) #evaluate function on xvals
create line plot with xvals and yvals
plt.plot(xvals,yvals)
show the grid
plt.grid(True)
plt.show()
Question:18
Python program to plot bar chart
Sol:
#program to plot bar chart
import matplotlib.pyplot as plt
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.title("Programming language usage")
plt.bar(y_pos,performance,align="center",width=.5, color='r')
plt.barh(y_pos,performance,align="center", color='r')
plt.show()
Question:19
Python interface with MySQL
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
#to insert data into the existing table in an existing database
import pymysql
# Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
c = db.cursor()
r=int(input("Enter roll no "))
n=input("Enter name ")
p=int(input("Enter per "))
try:
# execute SQL query using execute() method.
c.execute("insert into student (roll,name,per) values (%s,%s,%s)",(r,n,p))
#to save the data
db.commit()
print("Record saved")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
insert_data()
Program 20:
Python interface with MySQL
Write a function to display all the records stored in a table using python and MySQL interface.
Sol:
def display_all():
#display the records from a table
#field by field
import pymysql
# Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
try:
c = db.cursor()
sql='select * from student;'
c.execute(sql)
countrow=c.execute(sql)
print("number of rows : ",countrow)
#data=a.fetchone()
data=c.fetchall()
#print(data)
print("=========================")
print("Roll No Name Per ")
print("=========================")
for eachrow in data:
r=eachrow[0]
n=eachrow[1]
p=eachrow[2]
# Now print fetched result
print(r,' ',n,' ',p)
print("=========================")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
display_all()
Program :21
Python interface with MySQL
Write a function to search a record stored in a table using python and MySQL interface.
Sol:
def search_roll():
#searching a record by roll no
#display the records from a table
#field by field
import pymysql
# Open database connection
#conn=pymysql.connect(host='localhost',user='root',password='',db='test')
db = pymysql.connect("localhost","root","","test4")
# prepare a cursor object using cursor() method
try:
z=0
roll=int(input("Enter roll no to search "))
c = db.cursor()
sql='select * from student;'
c.execute(sql)
countrow=c.execute(sql)
print("number of rows : ",countrow)
#data=a.fetchone()
data=c.fetchall()
#print(data)
for eachrow in 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):
print("Record is not present")
except:
db.rollback()
# disconnect from server
db.close()
# function calling
search_roll()