50% found this document useful (2 votes)
655 views41 pages

Programming in Python 4639304

The document provides a list of programming problems and exercises related to Python programming. It includes problems on data types, control flow, functions, file handling, object oriented programming, and databases. Some example problems are to write programs to convert between Celsius and Fahrenheit, find the maximum of three numbers, check if a number is a palindrome, and implement a simple calculator using functions. The document is divided into three parts - the first covers basic Python concepts, the second covers regular expressions, and the third covers databases.

Uploaded by

test
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
50% found this document useful (2 votes)
655 views41 pages

Programming in Python 4639304

The document provides a list of programming problems and exercises related to Python programming. It includes problems on data types, control flow, functions, file handling, object oriented programming, and databases. Some example problems are to write programs to convert between Celsius and Fahrenheit, find the maximum of three numbers, check if a number is a palindrome, and implement a simple calculator using functions. The document is divided into three parts - the first covers basic Python concepts, the second covers regular expressions, and the third covers databases.

Uploaded by

test
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 41

Programming in Python 4639304

Sr.N Description Page No Sign


o
PART - 1
1. Write a Python Program to Convert Celsius to Fahrenheit and vice –a-
versa.
2. Write a program in python to swap two variables without using
temporary variable.
3. Write a Python Program to Convert Decimal to Binary, Octal and
Hexadecimal
4. Write a program to make a simple calculator (using functions).
5. Write a program in python to find out maximum and minimum
number out of three user entered number.
6. Write a program which will allow user to enter 10 numbers and
display largest odd numberfrom them. It will display appropriate
message in case if no odd number is found.
7. Write a Python program to check if the number provided by the user
is an Armstrong number.
8. Write a Python program to check if the number provided by the user
is a palindrome or not
9. 9 Write a Python program to perform following operation on given
string input:
a) Count Number of Vowel in given string
b) Count Length of string (donot use len() )
c) Reverse string
d) Find and replace operation
e) check whether string entered is a palindrome or not
10. Define a procedure histogram() that takes a list of integers and prints
a histogram to the screen. For example, histogram([4, 9, 7]) should
print the following:
****
*********
*******
11. Write a program in python to implement Fibonacci series up to user
entered number. (Use recursive Function
12. Write a program in python to implement Factorial series up to user
entered number. (Use recursive Function)
Write a program in python to implement simple interest and
compound interest values on chart using PyLab. Show the difference
between both. (Note: Use of object oriented
paradigm is compulsory.)
13. Write a program in Python to implement readline, readlines, write
line and writelines file handling mechanisms.
14. Write a program in python to implement Salary printing file read
operation. (File format:
EmployeeNo, name, deptno, basic, DA, HRA, Conveyance) should
perform below
operations.
a) Print Salary Slip for given Employee Number
b) Print Employee List for Given Department Number
15. Write a program in python to implement Railway Reservation System

175160693019 1
Programming in Python 4639304

using file handlingtechnique. System should perform


belowoperations.
a. Reserve a ticket for a passenger.
b. List information all reservations done for today’s trains.
(Note: Use of object oriented paradigm is compulsory.)
16. Write a program in python to implement Library Management System
using file handling technique. System should perform below
operations.
a. Issue a book for student.
b. List information today’s issued books.
(Note: Use of object oriented paradigm is compulsory.)
17. Write a program in python to implement Bank System using Class and
Methods and
perform below operations. (Note: Use of object oriented paradigm is
compulsory.)
a) Add Bank account
b) Deposit of money
c) withdrawal operation
d) Money transfer
e) Show Balance
18. A Python program to display employee id numbers on X-axis and their
salaries on Y-axis in the form a bar graph.
19. A program to display a histogram showing the number of employees
in specific age groups.
20. A program to display a pie chart showing the percentage of
employees in each department of a company
21. A program to create a line graph to show the profits of a company in
various years.
22. A program to create a line graph to show the profits of a company in
various years.
PART– 2Advanced Topic: Regular Expression
1. Create Regular Expressions that
a) Recongnize following strings bit, but, bat, hit, hat or hut
b) Match any pair of words separated by a single space, that is, first
and last names.
c) Match any word and single letter separated by a comma and single
space, as in last name, first initial.
d) Match simple Web domain names that begin with www and end
with a “.com” suffix; for example, www.yahoo.com. Extra Credit: If
your regex also supports other high-level domain names, such as
.edu, .net, etc. (for example: www.foothill.edu).
e) Match a street address according to your local format (keep your
regex general enough to match any number of street words, including
the type designation). For example,
American street addresses use the format: 1180 Bordeaux Drive.
Make your regex flexible enough to support multi-word street names
such as: 3120 De la Cruz Boulevard.
2. Create utility script to process telephone numbers such that
a. Area codes (the first set of three-digits and the accompanying
hyphen) are optional, that is, your regex should match both 800-555-

175160693019 2
Programming in Python 4639304

1212 as well as just 555-1212.


b. Either parenthesized or hyphenated area codes are supported, not
to mention optional; make your regex match 800-555-1212, 555-
1212, and also (800) 555-1212.
3. Chapter End Practical List of Main Text Book
PART- 3Database
1. Create Web Database Application “Address Book” with options to
a) add/ insert a record ,
b) modify a record ,
c) display a record
d) delete a record
2. 2 A Python program to retrieve all rows from employee table and
display thecolumn values in tabular form
3. A program to read CSV file and upload data into table
4. A program to retrieve all rows from employee table and dump into
CSV file.

175160693019 3
Programming in Python 4639304

1.Write a program to print hello world in python.

Code:

print("Hello world")

Output:

2. Write a program in python to swap two variables without using temporary variable.

Code:

var1=input("Enter First Number : ")

var2=input("\nEnter second number : ")

var1=int(var1)

var2=int(var2)

var1=var1+var2

var2=var1-var2

var1=var1-var2

print(var1)

print(var2)

Output:

175160693019 4
Programming in Python 4639304

3.Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal.

Code:

d=input("Enter decimal Number : ")

d=int(d)

print("Hexadecimal ",hex(d))

print("Octal ",oct(d))

print("binary ",int(bin(d)[2:]))

Output:

4.Write a program to make a simple calculator (using functions).

Code:

from os import system

def sum( a, b ):
s=a+b
return(s);

def sub(a,b):
return a-b

def mul(a,b):
return a*b

175160693019 5
Programming in Python 4639304

def div(a,b):
return a/b

a=int(input("Enter First Number : "))


b=int(input("Enter Second Number : "))

ch=0

while(ch!=5):

#system('cls')

print("\n 1. Addition ")


print("\n 2. substraction ")
print("\n 3. Multiplication ")
print("\n 4. division ")
print("\n 5. Exit ")

ch=int(input("Enter Choice "))

if(ch==1):

print("Sum : ",sum(a,b))

elif(ch==2):

print("Sub : ",sub(a,b))

elif(ch==3):

print("Mul : ",mul(a,b))

elif(ch==4):

print("div : ",div(a,b))

Output:

175160693019 6
Programming in Python 4639304

5. Write a program in python to find out maximum and minimum number out of three
user entered number.

Code:

a=int(input("Enter First Number : "))

b=int(input("Enter Second Number : "))

c=int(input("Enter Third Number : "))

print("Maximum Number : ",max(a,b,c))

print("Minimum Number : ",min(a,b,c))

Output:

175160693019 7
Programming in Python 4639304

6. Write a program which will allow user to enter 10 numbers and display largest odd
number from them. It will display appropriate message in case if no odd number is
found.

Code:

i=0

list=[]

while(i < 4):

list.append(int(input("Enter Number ")))

i=i+1

max=0

i=0

while(i < 4):

if(list[i] % 2 !=0):

if(list[i] > max):

max=list[i]

i=i+1

if(max==0):

print("No Odd number is found ")

else:

print("Maximum odd Number ",max)

Output:

175160693019 8
Programming in Python 4639304

7. Write a Python program to check if the number provided by the user is an


Armstrong Number.

Code:

a=int(input("Enter number "))

sum=0

temp=a

while(a>0):

r=a % 10

sum=sum+r**3

a=a // 10

if(temp==sum):

print("armstrong Number ")

else:

print("Not an armstrong Number ")

Output:

175160693019 9
Programming in Python 4639304

8. Write a Python program to check if the number provided by the user is a palindrome
or not.

Code:

a=int(input("Enter number "))

sum=0

temp=a

while(a>0):

r=a % 10

sum=sum*10+r

a=a // 10

print(sum)

if(temp==sum):

print("palindrome Number ")

else:

print("Not an palindrome Number ")

Output:

175160693019 10
Programming in Python 4639304

9. Write a Python program to perform following operation on given string input:

a) Count Number of Vowel in given string

b) Count Length of string (donot use len() )

c) Reverse string

d) Find and replace operation

e) check whether string entered is a palindrome or not

Code:

str=input("Enter string ")

v=0;l=0;s1=""

for s in str:

#Convert string to upper

s=s.upper()

#Count Vowels

if(s=='A' or s=='E' or s=='I' or s=='O' or s=='U'):

175160693019 11
Programming in Python 4639304

v=v+1

#Count Length

l=l+1

print("\nNumber of Vowels ",v)

print("\nLength ",l)

#Reversed string

for i in str:
s1=i+s1

#Function reversed(str)

print("\nReverse String ",s1)

#Find

ch=input("\nEnter string to Find : ")

print("\n",str.find(ch,0,l)) # 0-Start Position l-End Position

#Replace

old=input("\nEnter Old String ")


new=input("\nEnter New String ")

print("\n",str.replace(old,new))

#Palindrome

if(str==s1):
print("Palindrome String")
else:
print("Not an Palindrome")

Output:

175160693019 12
Programming in Python 4639304

10. Define a procedure histogram() that takes a list of integers and prints a histogram to
the screen. For example, histogram([4, 9, 7]) should print the following:

****

*********

*******

Code:

def histogram(list):
for n in list:
output=''
times=n

while(times>0):
output+='*'
times=times-1

print(output)

histogram([2,3,6,5])

Output:

175160693019 13
Programming in Python 4639304

11.Write a program in python to implement Fibonacci series up to user entered


number. (Use recursive Function)

Code:

def fibonacci(n):
if(n==0):
return 0
elif(n==1):
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)

n = int(input("Enter Number "))

i=1

while(i<=n):
print(fibonacci(i))
i=i+1

Output:

175160693019 14
Programming in Python 4639304

12. Write a program in python to implement Factorial series up to user entered


number. (Use recursive Function).

Code:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

n=int(input("Input a number to compute the factiorial : "))

print(factorial(n))

Output:

175160693019 15
Programming in Python 4639304

12.Write a program in python to implement simple interest and compound interest values on chart using
PyLab. Show the difference between both. (Note: Use of object oriented paradigm is compulsory.)

*************************NOTE***************************************

#command to install pylabpython -m pip install --user


numpyscipymatplotlibipythonjupyterpandassympy nose

importmatplotlib.pyplot as plt; plt.rcdefaults()


importnumpy as np
importmatplotlib.pyplot as plt

classsimpleInterest:

def __init__(self,p,rateOfInterest,term):
self.p=p
self.rateOfInterest=rateOfInterest
self.term=term

def display(self):
print ("Principal",self.p)
defcalculateInterest(self):
i=self.p*self.rateOfInterest*self.term
returni

defgetPrincipal():
return p

classcompoundInterest(simpleInterest):
def __init__(self,principal,rateOfInterest,term,ntimes=1):
super().__init__(principal,rateOfInterest,term)
self.ntimes=ntimes

defcalculateCompoundInterest(self):
a=self.p*(pow((1+self.rateOfInterest/self.ntimes),self.term))
return a

s1=simpleInterest(12000,0.05,5)

175160693019 16
Programming in Python 4639304

i=s1.calculateInterest()
#s1.display

c1=compoundInterest(12000,0.03,5)
j=c1.calculateCompoundInterest()
#c1.display()
#print('Interest {0:.2f} '.format(i))

objects = ('Simple Interest', 'Compound Interest')


y_pos = np.arange(len(objects))
performance = [i,j]

plt.bar(y_pos, performance, align='center', alpha=0.5,width=0.35)


plt.xticks(y_pos, objects)
plt.xlabel('Interest')
plt.title('Interest difference for the term of 5 years')
plt.show()

175160693019 17
Programming in Python 4639304

13.Write a program in Python to implement readline, readlines, write line and writelines file handling
mechanisms

Readline.py

importos

fileName=input("Enter the name of the file you want to read ")

ifos.path.exists(fileName):

f=open(fileName,"r")

print(f.readline())

print("You can return one line by using the readline() method\n")

print("readlines() reads the entire file until EOF \n")

print(f.readlines())

f.close()

else:

print("File has been created ",fileName)

f1=open(fileName,"x")

175160693019 18
Programming in Python 4639304

f1.close()

Writeline.py

importos

fileName=input("Enter the name of the file you want to write in : ")

ifos.path.exists(fileName):

f1=open(fileName,"a")

str=input("Enter contents you want to write into the file using write() : ")

f1.write(str)

f1.write("\n")

print(str,'written in file successfully \n \n')

print('List of numbers : ["1","2","3","4","5"] written using writelines() function')

list=["1","2","3","4","5"]

175160693019 19
Programming in Python 4639304

f1.write("\n")

f1.writelines(list)

f1.close()

else:

print("File doesn't exist")

OUTPUT:

175160693019 20
Programming in Python 4639304

14. Write a program in python to implement Salary printing file read operation.
(File format:
EmployeeNo, name, deptno, basic, DA, HRA, Conveyance) should perform
below operations.
a) Print Salary Slip for given Employee Number
b) Print Employee List for Given Department Number .

Code:

import re
import os
size = os.path.getsize("employee.txt")
file=open("employee.txt","r")
reclen = 75
n = int(size/reclen)
empno=input("Enter Employee No:")
position = 0
found=False
for i in range(n):
file.seek(position)
str=file.read(75)
if empno in str:
print("-----Salary Slip------")
print(str)

found = True
position+=reclen

OUTPUT :

175160693019 21
Programming in Python 4639304

15.Write a program in python to implement Railway Reservation System using


file handling technique. System should perform below operations.
a. Reserve a ticket for a passenger.
b. List information all reservations done for today’s trains.

CODE:

import sys

class Railway:

user=[['raj',1111],['manoj',2222],['rahul',3333],['sameer',4444]]

def login(self,username,pin):

if [username,pin] in Railway.user:
print('\n')
print('Welcome user:',username)

print('Would you like to:')


else:
print("Username or Password wrong:")
sys.exit(0)

def reservation(self,train,date,train_class,starting_From,destination):
filehandle = open("Railway_Reservation.txt","w")
filehandle.write("You Selected Train is:"+train)
filehandle.write("Your Journy dateis:"+date)
filehandle.write("Your Train class is:"+train_class)
#filehandle.write("No of Seats:",+seat)
filehandle.write("Your Journy starting From:"+starting_From)
filehandle.write("Your Destination is:"+destination)
filehandle.close()
print("Ticket Booked")

def showtrains(self):
file = open("Railway_Reservation.txt","r")
str=file.read()
print("Reserved Train")
print(str)

Rail = Railway()
print("Welcome to Railway:")

username=input("Enter Your Name:")


pin=int(input("Enter Your Pin:"))
Rail.login(username,pin)

while(True):

175160693019 22
Programming in Python 4639304

print('\n')
print("Railway Reservation:")
print('1:Reserve ticket:')
print('2:Show Reserved Trains:')
print('3.Exit:')

choice=int(input("Enter Your Choice:"))

if choice == 1:
train=input("Please Enter train No & Name:")
date = input("Please Enter Date Of Journey:")
train_class=input("Please Enter class(First or Second:)")
seat=(int(input("Please Enter no of Berths/seats:")))
starting_From=input("Please Enter Station Name where to Start:")
destination = input("Enter destination Name:")
Rail.reservation(train,date,train_class,starting_From,destination)

elif choice == 2:
Rail.showtrains()

elif choice == 3:
sys.exit(0)

else:
print("Enter Valid Choice")

Output:

175160693019 23
Programming in Python 4639304

175160693019 24
Programming in Python 4639304

16. Write a program in python to implement Library Management System using file
handling technique. System should perform below operations.
a. Issue a book for student.
b. List information today’s issued books.
(Note: Use of object oriented paradigm is compulsory.)

Code:

importdatetime

class book:
bname=""
bid=0

def __init__(self,b_name,b_id):
self.bname=b_name
self.bid=b_id
issuedate=""
sname=""
def show(self):
print("bookname ",self.bname,"bookid ",self.bid)

defissue_book(self,issue,to):
self.issuedate=issue

175160693019 25
Programming in Python 4639304

self.sname=to

now = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")

#b.issue_book(str(now),'nirav')

bookarray=[]
bookarray.append(book("python",5674))
bookarray.append(book("DBMS",9843))
bookarray.append(book("Java",9023))
bookarray.append(book("Maths",3210))

bookarray[0].issue_book(str(now),'nirav')
bookarray[1].issue_book(str(now),'zoya')
bookarray[2].issue_book(str(now),'viral')
bookarray[3].issue_book('2018-11-07 13:48:12','kishan')

dt = datetime.datetime.strptime(bookarray[2].issuedate,'%Y-%m-%d %H:%M:%S')

for i in bookarray:
dt = datetime.datetime.strptime(i.issuedate,'%Y-%m-%d %H:%M:%S')
dt2 = datetime.datetime.strptime(str(now),'%Y-%m-%d %H:%M:%S')

if(dt.date()==dt2.date()):
print(i.bname)

OUTPUT:

17. Write a program in python to implement Bank System using Class and Methods and
perform below operations. (Note: Use of object oriented paradigm is compulsory.)
a) Add Bank account
b) Deposit of money
c) withdrawal operation
d) Money transfer
e) Show Balance

175160693019 26
Programming in Python 4639304

Code:

importdatetime

class account:
accountName=""
accountNumber=0
accountBalance=0.0
accounttype=""

def __init__(self,aname,anum,abal,atype):
self.accountName=aname
self.accountNumber=anum
self.accountBalance=abal
self.accounttype=atype
defdeposite(self,amt):
self.accountBalance+=amt
returnself.accountBalance
def withdraw(self,amt):
self.accountBalance-=amt
returnself.accountBalance
def transfer(self,ac,amt):
self.accountBalance+=amt
ac.accountBalance-=amt

a=[]

a.append(account('Jatin',5764990907,100000,'saving'))
a.append(account('Raju',576499870,150000,'saving'))
a.append(account('Manisha',923190907,200000,'current'))

print('Main Balance')
print(a[0].accountName,"Account Balance "," ",a[0].accountBalance)
print(a[1].accountName,"Account Balance "," ",a[1].accountBalance)
print(a[2].accountName,"Account Balance "," ",a[2].accountBalance)

print("\n")
print('Add Deposit Amount')
print(a[0].accountName," ",a[0].deposite(200000))
print(a[1].accountName," ",a[1].deposite(250000))
print(a[2].accountName," ",a[2].deposite(150000))

print("\n")
print('Withdraw Amount')
print(a[0].accountName," ",a[0].withdraw(2000))
print(a[1].accountName," ",a[1].withdraw(15000))
print(a[2].accountName," ",a[2].withdraw(5000))

175160693019 27
Programming in Python 4639304

print("\n")
a[0].transfer(a[1],2000)

print(a[1].accountName," tranfer 2000 to"," ",a[0].accountName)

print("\n")
print(a[0].accountName,"Account Balance "," ",a[0].accountBalance)
print(a[1].accountName,"Account Balance "," ",a[1].accountBalance)

Output:

18. A Python program to display employee id numbers on X-axis and their salaries on
Y-axis in the form a bar graph.

Code:

importmatplotlib.pyplot as plt

import pandas as pd

empdata={"empid":[101,102,103,104,105],"ename":
["ruchi","sonu","birva","manisha","aparna"],"sal":[20000,25000,22000,35000,30000],"doj":
["1-1-2017","15-1-2017","23-12-2017","20-7-2016","16-8-1995"]}

df=pd.DataFrame(empdata)

x=df['empid']

y=df['sal']

plt.bar(x,y, label='Employee data',color='red')

plt.xlabel('Employee ids')

plt.ylabel('Employee salaries')

175160693019 28
Programming in Python 4639304

plt.title('MICROSOFT INC')

plt.legend()

plt.show()

Output:

19. A program to display a histogram showing the number of employees in specific age
groups

Code:

importmatplotlib.pyplot as plt

emp_ages=[22,45,30,59,58,56,57,45,43,43,50,40,34,33,25,19]

bins=[0,10,20,30,40,50,60]

plt.hist(emp_ages,bins,histtype='bar',rwidth=0.8,color='cyan')

plt.xlabel('Employee ages')

plt.ylabel('no. of employees')

plt.title('ORACLE CORP')

plt.legend()

plt.show()

175160693019 29
Programming in Python 4639304

Output:

20. A program to display a pie chart showing the percentage of employees in each
department of a company:

# import the pyplot library

import matplotlib.pyplot as plotter

# The slice names of a population distribution pie chart

pieLabels = 'account', 'finance', 'IT', 'HR'

# Population data

populationShare = [30, 20, 40, 10]

figureObject, axesObject = plotter.subplots()

# Draw the pie chart

axesObject.pie(populationShare,

labels=pieLabels,

autopct='%1.2f',

175160693019 30
Programming in Python 4639304

startangle=90)

# Aspect ratio - equal means pie is a circle

axesObject.axis('equal')

plotter.show()

OUTPUT:

21. A program to create a line graph to show the profits of a company in various years.

Code:

import matplotlib.pyplot as plt

year = [1960, 1970, 1980, 1990, 2000, 2010]


profit = [100000, 50000, 40000, 80000, 88000, 10000]
plt.plot(year, profit, color='g')
plt.xlabel('years')
plt.ylabel('profit')
plt.title('profit of company')
plt.show()

Output:

175160693019 31
Programming in Python 4639304

22. A program to create a line graph to show the profits of a company in various years.

Code:

importmatplotlib.pyplot as plt

years = [1983, 1984, 1985, 1986, 1987]

profit = [893900, 895451, 896038, 895674, 894372]

plt.plot(years, profit)

plt.title("Year vs Profit in Company")

plt.xlabel("Year")

plt.ylabel("Profit")

plt.show()

175160693019 32
Programming in Python 4639304

Output:

175160693019 33
Programming in Python 4639304

23. Create Regular Expressions that

a) Recongnize following strings bit, but, bat, hit, hat or hut

b) Match any pair of words separated by a single space, that is, first and last names.

c) Match any word and single letter separated by a comma and single space, as in last

name, first initial.

d) Match simple Web domain names that begin with www and end with a “.com” suffix;

for example, www.yahoo.com. Extra Credit: If your regex also supports other high-level

domain names, such as .edu, .net, etc. (for example: www.foothill.edu).

e) Match a street address according to your local format (keep your regex general
enough

to match any number of street words, including the type designation). For example,

American street addresses use the format: 1180 Bordeaux Drive. Make your regex

flexible enough to support multi-word street names such as: 3120 De la Cruz Boulevard.

Code:

import re

pattern = '[bh][aiu]t'

text = 'dddddfhat'

m = re.search(pattern, text)

if m is not None:

print(m.group())

pattern = '[a-zA-Z]+ [a-zA-Z]+'

text = 'John Lennon'

m = re.match(pattern, text)

if m is not None:

print(m.group())

pattern = '([A-Z]\. )+[A-Za-z]+'

text = 'W. J. Chun'

175160693019 34
Programming in Python 4639304

m = re.match(pattern, text)

if m is not None:

print(m.group())

pattern = 'w{3}(\.[\w_]+)+((\.com)|(.edu)|(.net))'

text = 'www.foothill.path.net'

m = re.search(pattern, text)

if m is not None:

print(m.group())

pattern = r'\d{4} ([a-zA-Z]+ )+[a-zA-Z]+'

text = '3120 De la Cruz Boulevard'

m = re.search(pattern, text)

if m is not None:

print(m.group())

Output:

175160693019 35
Programming in Python 4639304

24(A).Create utility script to process telephone numbers such that,


a. Area codes (the first set of three-digits and the accompanying hyphen) are optional,
that is, your regex should match both 800-555-1212 as well as just 555-1212.

import re

phoneNumRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('My number is 423-555-4242.')
no = phoneNumRegex.search('My number is 555-4242.')
print('Phone number found: ' + mo.group())
print('Phone number found: ' + no.group())

Output :-

175160693019 36
Programming in Python 4639304

24(a). Create utility script to process telephone numbers such that


(b). Either parenthesized or hyphenated area codes are supported, not to mention
optional; make your regex match 800-555-1212, 555-1212, and also (800) 555-1212.

import re

phoneNumRegex = re.compile(r'(\(\d\d\d\) ||(\d\d\d\-))*(\d\d\d-\d\d\d\d)')


no = phoneNumRegex.search('My phone number is 555-4242.')
print(no.group())
s = phoneNumRegex.search('My phone number is (415) 555-4242.')
print(s.group())
a = phoneNumRegex.search('My phone number is 415-555-4242.')
print(a.group())

Output :-

175160693019 37
Programming in Python 4639304

Q3_1) Create Web Database Application “Address Book” with options to

a) add/ insert a record ,

b) modify a record ,

c) display a record

d) delete a record

import sqlite3

db=sqlite3.connect('test.db')

print("1. ADD RECORD")

print("2. MODIFY RECORD")

print("3. DISPLAY RECORD")

print("4. DELETE RECORD")

print("0. EXIT")

i = input("Enter your Choice")

while i >= '1':

if i == '1':

id = input("Enter the P_ID")

name = input("Enter the name")

add = input("Enter the address")

qry="insert into AddressBook (P_ID, name, address)


values("+id+", \'"+name+"\', \'"+add+"\');"

try:

cur=db.cursor()

cur.execute(qry)

db.commit()

print ("one record added successfully")

except:

print ("error in operation")

175160693019 38
Programming in Python 4639304

db.rollback()

if i == '2':

id=input("Enter the id to be updated")

name=input("Enter the new updated name")

qry="update AddressBook set name=\'"+name+"\' where P_ID="+id+";"

try:

cur=db.cursor()

cur.execute(qry)

db.commit()

print("record updated successfully")

except:

print("error in operation")

db.rollback()

if i == '3':

id=input("Enter the id to be displayed");

sql="SELECT * from AddressBook where P_ID="+id+";"

cur=db.cursor()

cur.execute(sql)

while True:

record=cur.fetchone()

if record==None:

break

print (record)

if i == '4':

id = input("Enter the id to be deleted")

qry="DELETE from AddressBook where P_ID="+id+";"

175160693019 39
Programming in Python 4639304

try:

cur=db.cursor()

cur.execute(qry)

db.commit()

print("record deleted successfully")

except:

print("error in operation")

db.rollback()

i = input("Enter your choice")

db.close()

INSERT

DELETE

DISPLAY

UPDATE

175160693019 40
Programming in Python 4639304

Q3_2) A Python program to retrieve all rows from employee table and display the
column values in tabular form.

Code:

import sqlite3

db=sqlite3.connect('test.db')

sql="SELECT * from AddressBook;"

cur=db.cursor()

cur.execute(sql)

result_set = cur.fetchall()

#print "%9s, %9s, %9s" % ('Romil', 'Shhahh', 'Hello')

for row in result_set:

id=row[0]

name=row[1]

add=row[2]

print('%-5s %-10s %-10s'%(id,name,add))

Output:

175160693019 41

You might also like