Programming in Python 4639304
Programming in Python 4639304
175160693019 1
Programming in Python 4639304
175160693019 2
Programming in Python 4639304
175160693019 3
Programming in Python 4639304
Code:
print("Hello world")
Output:
2. Write a program in python to swap two variables without using temporary variable.
Code:
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
Code:
d=int(d)
print("Hexadecimal ",hex(d))
print("Octal ",oct(d))
print("binary ",int(bin(d)[2:]))
Output:
Code:
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
ch=0
while(ch!=5):
#system('cls')
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:
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=[]
i=i+1
max=0
i=0
if(list[i] % 2 !=0):
max=list[i]
i=i+1
if(max==0):
else:
Output:
175160693019 8
Programming in Python 4639304
Code:
sum=0
temp=a
while(a>0):
r=a % 10
sum=sum+r**3
a=a // 10
if(temp==sum):
else:
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:
sum=0
temp=a
while(a>0):
r=a % 10
sum=sum*10+r
a=a // 10
print(sum)
if(temp==sum):
else:
Output:
175160693019 10
Programming in Python 4639304
c) Reverse string
Code:
v=0;l=0;s1=""
for s in str:
s=s.upper()
#Count Vowels
175160693019 11
Programming in Python 4639304
v=v+1
#Count Length
l=l+1
print("\nLength ",l)
#Reversed string
for i in str:
s1=i+s1
#Function reversed(str)
#Find
#Replace
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
Code:
def fibonacci(n):
if(n==0):
return 0
elif(n==1):
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
i=1
while(i<=n):
print(fibonacci(i))
i=i+1
Output:
175160693019 14
Programming in Python 4639304
Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
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***************************************
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))
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
ifos.path.exists(fileName):
f=open(fileName,"r")
print(f.readline())
print(f.readlines())
f.close()
else:
f1=open(fileName,"x")
175160693019 18
Programming in Python 4639304
f1.close()
Writeline.py
importos
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")
list=["1","2","3","4","5"]
175160693019 19
Programming in Python 4639304
f1.write("\n")
f1.writelines(list)
f1.close()
else:
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
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)
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:")
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:')
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
#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("\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.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:
# Population data
axesObject.pie(populationShare,
labels=pieLabels,
autopct='%1.2f',
175160693019 30
Programming in Python 4639304
startangle=90)
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:
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
plt.plot(years, profit)
plt.xlabel("Year")
plt.ylabel("Profit")
plt.show()
175160693019 32
Programming in Python 4639304
Output:
175160693019 33
Programming in Python 4639304
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
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
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())
m = re.match(pattern, text)
if m is not None:
print(m.group())
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())
m = re.search(pattern, text)
if m is not None:
print(m.group())
Output:
175160693019 35
Programming in Python 4639304
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
import re
Output :-
175160693019 37
Programming in Python 4639304
b) modify a record ,
c) display a record
d) delete a record
import sqlite3
db=sqlite3.connect('test.db')
print("0. EXIT")
if i == '1':
try:
cur=db.cursor()
cur.execute(qry)
db.commit()
except:
175160693019 38
Programming in Python 4639304
db.rollback()
if i == '2':
try:
cur=db.cursor()
cur.execute(qry)
db.commit()
except:
print("error in operation")
db.rollback()
if i == '3':
cur=db.cursor()
cur.execute(sql)
while True:
record=cur.fetchone()
if record==None:
break
print (record)
if i == '4':
175160693019 39
Programming in Python 4639304
try:
cur=db.cursor()
cur.execute(qry)
db.commit()
except:
print("error in operation")
db.rollback()
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')
cur=db.cursor()
cur.execute(sql)
result_set = cur.fetchall()
id=row[0]
name=row[1]
add=row[2]
Output:
175160693019 41