Function:¶
1.Write a python program to compute area of a rectangle.
l=float(input("Enter the length"))
b=float(input("Enter the breadth"))
ar=l*b
print("The area of rectangle is: ",ar)
2.Write a python function that accepts a string and calculates the number of uppercase letter and lowercase letters:
Sample String:
Hello World
Expected Output:
No. Of Uppercase Character : 2
No of Lowercase Character: 8
def cal(st):
cnUp=0
cnLo=0
for i in st:
if i.isupper():
cnUp+=1
elif i.islower():
cnLo+=1
print("The number of uppercase character: ",cnUp)
print("The number of lowercase character: ",cnLo)
cal("Hello World")
3.Write a calculator function that can take two or more numbers and calculate Addition, multiplication, subtraction of these number among themselves
Example: Input: 2,3,4 Output: addition is 9, multiplication is 24 , subtraction is -5
Input: 1,2,3,4 Output: addition is 10, multiplication is 24 , subtraction is -8
def calcu(*arg):
sm=0
ml=1
su=0
for i in arg:
sm+=i
ml*=i
if su==0:
su+=i
else:
su-=i
print("Addition: ",sm)
print("Multiplication: ",ml)
print("Subtraction: ",su)
calcu(2,3,4)
calcu(1,2,3,4)
4.Write a python program that accepts a hyphen-seperated sequence of words as input and prints the words in a hyphen-seperated sequence after sorting them alphabetically.
Sample Input: green-red-yellow-black-white
Expected Output: black-green-red-white-yellow
st=input("Enter the hyphen-seperated sequence")
st=st.split("-")
st.sort()
fl=""
for i in st:
fl=fl+i+'-'
fl=fl.rstrip('-')
print(fl)
Python Libraries¶
1.Create a module lengthconversion.py that stores function for various lengths conversion e.g.
a. miletokm()
b. kmtomile()
c. feettoinches()
d. inchestofeet()
# Module length conversion
def miletokm(ml):
return ml*1.60934
def kmtomile(km):
return km/1.60934
def feettoinch(ft):
return ft*12
def inchtofeet(inc):
return inc/12
- Write a function that receives two numbers and generates a random number from that range. Using this function , the main program should be able to print three numbers randomly.
import random as rn
def ran(low,up):
return rn.randint(low,up+1)
for i in range(3):
print(ran(1,5))
File handling in python¶
1.Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blanks spaces is replaced by a single space.
#CREATING A FILE WITH BLANKS
fl=open("sample.txt","w")
txt="hello there, how are you"
fl.write(txt)
fl.close()
#CREATING A FILE WITHOUT BLANKS
fl=open("sample.txt","r")
tx=fl.read()
fg=0
ntxt=""
for i in tx:
#print(i)
if i==" " and fg==0:
fg+=1
ntxt=ntxt+i
elif i==" " and fg>0:
continue
else:
ntxt=ntxt+i
fg=0
print(ntxt)
2.Write a program to count the words ‘to’ and ‘the’ present in a text file ‘poem.txt’.
#Writing to the file
f=open("poem.txt",'w')
st="it is to say the say is to do and do being said"
f.write(st)
f.close()
#reading from the file and counting it
f=open("poem.txt",'r')
sr=f.read()
sr=sr.split()
cnto=0
cnthe=0
for i in sr:
if i.lower()=='to':
cnto+=1
elif i.lower()=='the':
cnthe+=1
f.close()
print("the number of 'to' are: ",cnto)
print("the number of 'the' are: ",cnthe)
3.Write a program to count the number of upper-case alphabet present in an text file ‘article,txt’.
#Writing to the file
f=open("article.txt",'w')
st="An SQL JOIN clause is used to combine rows from two or more tables based on a common field between them. While querying for a join, more than one table is considered in FROM clause."
f.write(st)
f.close()
#reading from the file and counting it
f=open("article.txt",'r')
pr=f.read()
cnup=0
cnlo=0
for i in pr:
if i.isupper():
cnup+=1
elif i.islower():
cnlo+=1
f.close()
print("The number of uppercase alphabets: ",cnup)
print("The number of lowercase alphabets: ",cnlo)
4.Write a program that appends the contents of one file to another. Have the program take the filename from the user.
# we will append the contents of poem.txt into article.txt
f1=open("article.txt",'a')
f2=open("poem.txt",'r')
f1.write(f2.read())
f1.close()
f2.close()
5.Write a method in python to read the context from a text file diary.txt line by line and display the same on the screen.
#creating the diary.txt file
f1=open("diary.txt",'w')
txt="today is good.\n good is a relative idea.\n one mans good is others bad."
f1.write(txt)
f1.close()
#rading line by line from the diary.txt file
f1=open("diary.txt",'r')
for i in f1.readlines():
print(i)
f1.close()
6.Write a program to create a binary file with name and roll number. Search for a given roll number and display the name, if not found display appropriate message.
import pickle as pk
class stu:
def __init__(self,name,roll):
self.name=name
self.roll=roll
def display(self):
print(self.name)
print(self.roll)
def addData(nm,rl): #To add data to the binary file
s=stu(nm,rl)
f=open("stuinfo.dat",'ab')
pk.dump(s,f)
f.close()
def showNm(rl): #To search for name base on roll number
f=open("stuinfo.dat",'rb')
cn=0
while True:
try:
dt=pk.load(f)
if dt.roll==rl:
print(dt.name)
cn+=1
except EOFError:
break
if cn==0:
print("Roll number not found!")
f.close()
addData("Kaushik",2)
showNm(2)
7.Write a program to create a binary file with roll number, name and marks. Input a roll number and update the marks.
import pickle as pk
class stuDt:
def __init__(self, roll, name, marks):
self.roll=roll
self.name=name
self.marks=marks
def display():
print(self.roll,self.name,self.marks)
def addData(roll,name,marks):
f=open("stData.dat",'ab')
s=stuDt(roll,name,marks)
pk.dump(s,f)
f.close()
def readData():
f=open("stData.dat",'rb')
while True:
try:
ln=pk.load(f)
print(ln.roll,ln.name,ln.marks)
except EOFError:
print("thats it")
break
f.close()
def updateMarks(roll,marks):
f=open("stData.dat",'rb+')
while True:
try:
ln=pk.load(f)
if ln.roll==roll:
print(ln.roll,ln.name,ln.marks)
ln.marks=marks
#pk.dump(d,f)
except EOFError:
break
f.close()
addData(1,"john",456)
addData(2,"harry",395)
addData(3,"terry",421)
readData()
updateMarks(2,498)
Data Structure¶
- Write a python program to implement the push operation on the stack using list.
st=[]
def push(ls,val):
ls.append(val)
def display(ls):
l=len(ls)
for i in range(l-1,-1,-1):
print(ls[i])
push(st,2)
push(st,8)
push(st,11)
push(st,15)
display(st)
- Write a python program to implement the pop operation on the stack using list.
st=[45,78,49,36,14,13]
def pop(ls):
ls.pop()
def display(ls):
l=len(ls)
for i in range(l-1,-1,-1):
print(ls[i])
print("Original Stack \n")
print(display(st))
print("Item removed \n")
print(st.pop())
print("Stack after deletion \n")
print(display(st))
Python - Mysql Connection¶
1.Write a python program to create a a table CLUB in mysql and insert the following data in it.
Coach_id coachName Age Sports
1 John 35 karate
2 David 34 karate
3 Tom 34 squash
4 Tim 33 basketball
5 Nathan 36 swimming
6 Peter 36 swimming
7 Tony 39 squash
8 Jack 37 basketball
import mysql.connector as con
connection=con.connect(host="localhost", user="root", password="root", database="test")
mycursor = connection.cursor()
mycursor.execute("CREATE TABLE club(coach_id int, coachName varchar(15), age int, sports varchar(25))")
mycursor.execute("INSERT INTO club VALUES(1, 'John', 35, 'karate')")
mycursor.execute("INSERT INTO club VALUES(2, 'David', '34', 'karate')")
mycursor.execute("INSERT INTO club VALUES(3, 'Tom', 34, 'squash')")
mycursor.execute("INSERT INTO club VALUES(4, 'Tim', 33,'basketball')")
mycursor.execute("INSERT INTO club VALUES(5, 'Nathan', 36, 'swimming')")
mycursor.execute("INSERT INTO club VALUES(6, 'Peter', 36, 'swimming')")
mycursor.execute("INSERT INTO club VALUES(7, 'Tony', 39, 'squash')")
mycursor.execute("INSERT INTO club VALUES(8, 'Jack', 37, 'basketball')")
mycursor.execute("commit")
connection.close()
2.Consider the CLUB table and write a python program to display all the data from the table in a python console
Coach_id coachName Age Sports
1 John 35 karate
2 David 34 karate
3 Tom 34 squash
4 Tim 33 basketball
5 Nathan 36 swimming
6 Peter 36 swimming
7 Tony 39 squash
8 Jack 37 basketball
import mysql.connector as con
connection=con.connect(host="localhost", user="root", password="root", database="test")
mycursor = connection.cursor()
mycursor.execute("SELECT * from club")
result=mycursor.fetchall()
print(result)
connection.close()