Sample Applications - Python Programming Made Easy (2016)

Python Programming Made Easy (2016)

Chapter 13: Sample Applications

Project1: Inventory management

Create a class item to store information of different items, existing in a shop. At least following is to be stored w.r.t. each item code, name, price, qty. Write a program to accept the data from user and store it permanently in the file.

Program:

import pickle

import os

import sys

class ITEM:

def __init__(self):

self.itemcode=0

self.itemname=''

self.price=0.0

self.qty=0

def get(self):

self.itemcode=input("Enter item code")

self.itemname=raw_input("Enter item name")

self.price=float(raw_input("Enter price"))

self.qty=input("Enter quantity")

pickle.dump( self, open( "save.txt", "wb" ) )

print "Successfully Saved"

def display(self):

print "Reading from the file"

self = pickle.load( open( "save.txt", "rb" ) )

print"Item Code",self.itemcode

print"Item Name",self.itemname

print"Price",self.price

print"Quantity",self.qty

x = ITEM()

x.get()

x.display()

Output screenshot:

Project2: Quiz

The quiz project has an administrator who can create a quiz and view all questions. Any other user is given a set of say 20 questions one by one and their score is calculated for each correct answer. At the end of the quiz, their scores are displayed.

# Quiz class contains the questions and the correct answers

filename = "Quiz.txt"

ans = {}

# Get information from files

import os

if os.path.exists(filename):

store = open(filename,'r')

for line in store:

term = line.rstrip()

answer = store.next().rstrip()

ans[term] = answer

store.close()

cont=0

ch=0

while ch==0:

choice = int(raw_input("MENU 1- CREATE 2- PLAY 3- QUIT"))

if choice == 1:

while cont==0:

term = raw_input("Enter question:")

term = term.rstrip()

while term not in ans:

answer = raw_input("Enter answer")

ans[term] = answer

store = open(filename, 'w')

for term,answer in ans.items():

store.write( str(term)+ '\n')

store.write(answer+ '\n')

store.close()

cont = int(raw_input("Are there more questions 0 to continue"))

elif choice==2:

print "Welcome to Quiz"

score =0

for ques,answer in ans.items():

print str(ques)

correct = ans.get(ques)

userans =raw_input("Ans:")

if userans == correct:

score = score+1

print "You scored ",score, "out of",len(ans)

else:

print "Thank You"

break

ch = int(raw_input("Do you wish to continue ..press 0"))

Project 3: Databases operations using python

Problem Description

Write a simple python program to connect to a database and perform database operations.

Technical documentation:

Go to https://code.google.com/p/pyodbc/downloads/list

Download the required version

Start by importing the pyodbc module

import pyodbc

Connections

The Connection object represents a single connection to the database and is obtained from the module's connect function:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=mine;UID=me;PWD=pwd')

There are two primary features of the connection object:

1. You use cnxn.cursor() to create a new Cursor.

2. You use cnxn.commit() or cnxn.rollback() to commit or rollback work performed with the Cursor.

commit

We need to enable autocommit (in the pyodbc.connect function or with Connection.autocommit), all uncommited work will be discarded when the Connection object is closed. We must call cnxn.commit()

cnxn = pyodbc.connect(...)
# do work here...
cnxn.commit()
cnxn.close()

Cursors

Cursor objects are used to execute SQL.

Program

import pyodbc

# Connection string Server name , database name , userid =sa and password

con = pyodbc.connect('DRIVER={SQL Server};SERVER=WIN-URCSEH98ZFA;DATABASE=record;UID=sa;PWD=password12%')

# create a cursor for this connection

cur = con.cursor()

while True:

choice = input("1-VIEW 2-INSERT 3- DELETE 4-UPDATE 5-SEARCH 6-EXIT")

if choice==1:

Select_Command = ("SELECT * from student")

cur.execute(Select_Command)

results = cur.fetchall()

print "RollNo Name Grade"

for r in results:

print (str(r[0]) + " " + r[1] + r[2])

elif choice==2:

roll = input("Enter the roll number to be inserted")

sname = raw_input("Enter the name to be inserted")

grade = raw_input("Enter the grade to be inserted")

insert_command = ("insert into student (RollNo,Name,Grade) VALUES (?, ?, ?)")

cur.execute(insert_command,roll, sname,grade)

con.commit()

elif choice==3:

roll = input("Enter the roll number to be deleted")

delete_command = ("delete from student where rollno= ?")

try:

cur.execute(delete_command,roll)

con.commit()

except:

print("Error in delete")

elif choice ==4:

roll = input("Enter the roll number to be updated")

newgrade = raw_input("Enter the new grade")

update_command = ("update student set grade= ? where rollno= ?")

try:

cur.execute(update_command,newgrade,roll)

con.commit()

except:

print("Error in update")

elif choice ==5:

roll = input("Enter the roll number to be searched")

search_command = ("SELECT * from student where rollno= ?")

cur.execute(Select_Command,roll)

results = cur.fetchone()

print (str(r[0]) + " " + r[1] + r[2])

else:

print "Done"

break

con.close()

Output screenshot:

Project 4: CALCULATOR

This project aims to create a simple calculator using classes and GUI.

Source Code:

# calc.py - a Python calculator

from Tkinter import *

import math

# the main class

class Calc():

def __init__(self):

self.total = 0

self.current = ""

self.new_num = True

self.op_pending = False

self.op = ""

self.eq = False

def num_press(self, num):

self.eq = False

temp = text_box.get()

temp2 = str(num)

if self.new_num:

self.current = temp2

self.new_num = False

else:

if temp2 == '.':

if temp2 in temp:

return

self.current = temp + temp2

self.display(self.current)

def calc_total(self):

self.eq = True

self.current = float(self.current)

if self.op_pending == True:

self.do_sum()

else:

self.total = float(text_box.get())

def display(self, value):

text_box.delete(0, END)

text_box.insert(0, value)

def do_sum(self):

if self.op == "add":

self.total += self.current

if self.op == "minus":

self.total -= self.current

if self.op == "times":

self.total *= self.current

if self.op == "divide":

self.total /= self.current

if self.op=='square':

self.total = math.pow(self.total, self.current)

self.new_num = True

self.op_pending = False

self.display(self.total)

def operation(self, op):

self.current = float(self.current)

if self.op_pending:

self.do_sum()

elif not self.eq:

self.total = self.current

self.new_num = True

self.op_pending = True

self.op = op

self.eq = False

def cancel(self):

self.eq = False

self.current = "0"

self.display(0)

self.new_num = True

def all_cancel(self):

self.cancel()

self.total = 0

def sign(self):

self.eq = False

self.current = -(float(text_box.get()))

self.display(self.current)

sum1 = Calc()

root = Tk()

cal = Frame(root)

cal.grid()

root.title("Calculator")

text_box = Entry(cal, justify=RIGHT)

text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)

text_box.insert(0, "0")

# make the buttons

numbers = "123456789"

i = 0

bttn = []

for j in range(1,4):

for k in range(3):

bttn.append(Button(cal, text = numbers[i],bg= 'black',fg='white',font='bold'))

bttn[i].grid(row = j, column = k, pady = 5)

bttn[i]["command"] = lambda x = numbers[i]: sum1.num_press(x)

i += 1

zero = Button(cal, text = '0',bg= 'black',fg='white',font='bold')

zero['command'] = lambda: sum1.num_press(0)

zero.grid(row = 4, column = 1, pady = 5)

multiply = Button(cal, text = 'X',bg= 'green',fg='black',font='bold')

multiply['command'] = lambda: sum1.operation('times')

multiply.grid(row = 2, column = 3, pady = 5)

minus = Button(cal, text = '-',bg= 'green',fg='black',font='bold')

minus['command'] = lambda: sum1.operation('minus')

minus.grid(row = 3, column = 3, pady = 5)

point = Button(cal, text = '.',bg= 'black',fg='white',font='bold')

point['command'] = lambda: sum1.num_press('.')

point.grid(row = 4, column = 0, pady = 5)

add = Button(cal, text = '+',bg= 'green',fg='black',font='bold')

add['command'] = lambda: sum1.operation('add')

add.grid(row = 4, column = 3, pady = 5)

neg= Button(cal, text = '+/-',bg= 'blue',fg='black',font='bold')

neg['command'] = sum1.sign

neg.grid(row = 5, column = 0, pady = 5)

cancel = Button(cal, text = 'C',bg= 'red',fg='black',font='bold')

cancel['command'] = sum1.cancel

cancel.grid(row = 5, column = 1, pady = 5)

clear_all = Button(cal, text = 'AC',bg= 'red',fg='black',bd=10)

clear_all['command'] = sum1.all_cancel

clear_all.grid(row = 1, column = 3, pady = 5)

equals = Button(cal, text = '=',bg= 'orange',fg='black',font='bold')

equals['command'] = sum1.calc_total

equals.grid(row=4,column = 2, pady = 5)

divide=Button(cal,text='/',bg= 'green',fg='black',font='bold')

divide['command']=lambda: sum1.operation('divide')

divide.grid(row = 5, column = 3, pady = 5)

square=Button(cal,text='^',bg= 'blue',fg='white',font='bold')

square['command']=lambda:sum1.operation('square')

square.grid(row=5,column=2,pady=5)

root.mainloop()

SourceCode : Calculator project

Fig: Calculator project screenshots

Solutions to practice questions(selected)

Chapter 2

1. name1 = raw_input("First person - enter your name")

name2 = raw_input("Second person - enter your name")

print "Hello",name1

print "Hello",name2

3. a) 45

b) 7.0

Chapter 3

1. def SubtractNumber(x,y):

result = x -y

return result

# Get 2 numbers

num1 = input("Enter first number")

num2 = input("Enter second number")

res = SubtractNumber(num1,num2)

print "Subtraction result",num1,"-",num2,"=",res

2. def power( x, y=2):

sum=1

for i in range(1,y+1):

sum = sum * x

return sum

print "Using default argument"

num = input("Enter the base")

print power(num)

print "Value provided for both arguments"

exp = input("Enter exponent")

print power(num,exp)

Chapter 4

1.

import math

import cmath

print "\nEnter the values for a, b and c."

a = float(raw_input("a?"))

b = float(raw_input("b?"))

c = float(raw_input("c?"))

if b*b-4*a*c < 0:

print "This quadratic has imaginary roots."

root = (-b - cmath.sqrt(b*b - 4*a*c))/(2*a)

print "x =", root

root = (-b + cmath.sqrt(b*b - 4*a*c))/(2*a)

print "x =", root

elif b*b-4*a*c == 0:

print "This quadratic equation has equal roots."

root = -b/(2*a)

print "x =", root

else:

print "This quadratic has real and distinct roots."

root = (-b - math.sqrt(b*b - 4*a*c))/(2*a)

print "x =", root

root = (-b + math.sqrt(b*b - 4*a*c))/(2*a)

print "x =", root

raw_input()

2.

import math

print "\n Enter customer's name"

name = raw_input("name?")

print "\nEnter the previous month's reading."

prev = float(raw_input("prev?"))

print "\nEnter the current month's reading."

curr = float(raw_input("curr?"))

units = curr - prev

if units <= 100:

bill=units*4.00;

elif units >100 and units < 500:

bill=400 + (units-100)*5.00;

else:

bill = 400+ 2000+ (units-500)*6.00;

print "No. of units consumed= ",units

print "Amount payable to the electricity department= Rs", bill

raw_input()

3.

import math

sum=0

sign=1

x=0

n = int (raw_input("Enter the value of n:"))

x = int (raw_input("Enter the value of x:"))

j=1

i=1

while i < n:

f=1

while j < i:

f=f*j

j=j+1

sum =sum+ sign * (pow(x,i)/f)

sign = -sign;

i = i+1

print " 1 - x / 1! + x^2 /2! - x^3 /3! + … + (-1)^n x^n / n! =",sum

raw_input()

Chapter 5

1.# Counting vowels

count=0;

line = raw_input("Enter a word:")

i=0

for i in range (0,len(line)):

line = line.lower()

if((line[i]=='a') or (line[i]=='e')or (line[i]=='i')or(line[i]=='o')or(line[i]=='u')):

count=count+1

print "\nNo of vowels= ",count

raw_input()

2.

import re

value = []

print """" Rules: At least 1 uppercase letter, 1 lower case letter,

1 special character and 1 number min 6 character max 20 characters""""

items=[x for x in raw_input("Enter the password list").split(',')]

for p in items:

p = p.strip()

if len(p)<6 or len(p)>20:

print "Length error", p

continue

if not re.search("[a-z]",p):

continue

elif not re.search("[0-9]",p):

continue

elif not re.search("[A-Z]",p):

continue

elif not re.search("[?$#@!*]",p):

continue

elif re.search("\s",p):

continue

else:

pass

value.append(p)

print "The valid password list is"

print ",".join(value)

4.

# Get names from the user

names = list()

n = int (raw_input("Enter the number of names:-"))

print "Enter the names";

for i in range(0,n):

names.append(raw_input())

for i in range(0,n):

for j in range(i,n):

if names[i] > names[j]:

temp =names[i]

names[i]=names[j]

names[j]=temp

print "Sorted Array: \n"

for i in range(n):

print names[i]

raw_input()

Chapter 6

1. def sumodd(L):

pos = 0

sum = 0

while pos < len (L) :

if L[pos] %2 = = 1 :

sum = sum + L [pos]

pos = pos + 1

print sum

2. import random

print"To create a matrix of the form M *M"

m=input("Enter the number of rows :-")

n=input("Enter the number of columns :-")

a=[[random.randint(1,9)for row in range(n)]for col in range(m)]

for i in range (m):

for j in range (n):

print a[i][j],

print

print"__________To Print The Row Sum______________"

for i in range (m):

sum=0

for j in range (n):

sum=sum+a[i][j]

print sum,

print

print"___________To Print The Column Sum____________"

for i in range (n):

sum=0

for j in range (m):

sum=sum+a[j][i]

print sum

print"_______________LEFT DIAGONAL SUM______________"

sum=0

for i in range(m):

for j in range(n):

if i==j:

sum=sum+a[i][i]

print sum

print"_____________RIGHT DIAGONAL SUM______________"

sum=0

for i in range(m):

for j in range(n):

if i+j==m-1:

sum=sum+a[i][j]

print sum,

3. def overlapping (a, b) :

l1 = len (a)

l2 = len (b)

for i in range (l1) :

for j in range (l2) :

if a[i] == b[j] : return True

else: return False

6. def duplicates():

a =[1,2,3,2,1,5,6,5,5,5]

d={ }

for elem in a:

if elem in d: d[elem] += 1 else: d[elem] = 1

print elem

print [x for x, y in d.items() if y > 1], print “have duplicates”

print d

Chapter 7

1. city=dict( )

n=5

i=l

while i<=n:

a=raw_input(“ enter city name”)

b=raw_input(“enter population”)

city[a]=b

i=i+l

print city

2. def print_menu():

print('1. Add a Phone Number')

print('2. Remove a Phone Number')

print('3. Search a Phone Number')

print('4. Modify a Phone Number')

print('5. Display the phone book')

print('6. Quit')

phonebook = {}

menu_choice = 0

print_menu()

while menu_choice != 6:

menu_choice = int(raw_input(" Enter choice (1-5): "))

if menu_choice == 1:

print("Insertion")

name = raw_input("Name: ")

phone = raw_input("Number: ")

phonebook[name] = phone

elif menu_choice == 2:

print(" Deletion")

name = raw_input("Name: ")

if name in phonebook:

del phonebook[name]

else:

print(name, "was not found")

elif menu_choice == 3:

print ("Searching")

name = raw_input("Name: ")

if name in phonebook:

print("The number is", phonebook[name])

else:

print(name, "was not found")

elif menu_choice == 4:

print ("Update")

name = raw_input("Name: ")

if name in phonebook:

newno = raw_input("Enter new telephone number")

phonebook[name] = newno

else:

print(name, "was not found")

elif menu_choice == 5:

print("Phonebook:")

for x in phonebook.keys():

print( x, phonebook[x])

else:

print "Thank you"

3.

customer=dict( )

n=input(" Enter total number of customers")

i=1

while i<=n:

a=raw_input("enter customer name")

b=raw_input("enter customer number")

customer[a]=b

i=i+1

name=raw_input("enter customer name to delete")

del customer[name]

l=customer.keys( )

print "Customer Information"

print "Name",'\t',"number"

for i in l:

print i,'\t',customer[i]

Chapter 8

1. t=tuple( )

n=input(“Enter total number of employees”)

for i in range(n):

a=input(“enter salary of employee:)

t=t+(a,)

print “maximum salary=,max(t)

print “minimum salary=,min(t)

Chapter 10

1.

class items:

def __init__(self,s=None):

if s==None:

self.itemname=''

self.itemcode=0

self.itemprice=0.0

self.itemqty=0

else:

self.itemname=s.itemname

self.itemcode=s.itemcode

self.itemprice=s.itemprice

self.itemqty=s.itemqty

def get(self):

print ''

self.itemname=raw_input('Enter name of item: ')

self.itemcode=input('Enter itemcode: ')

self.itemprice=float(raw_input('Enter item price: '))

self.itemqty=input('Enter quantity: ')

print ''

def show(self):

print self.itemname,'\t\t',self.itemcode,'\t\t',self.itemprice,'\t\t',self.itemqty

s=items()

inventorylist=[]

n=input('Enter number of items: ')

for i in range(n):

s.get()

inventorylist.append(items(s))

print "ITEMS SORTED BY PRICE"

for i in range(len(inventorylist)):

for j in range(i+1,len(inventorylist)):

if inventorylist[i].itemprice>inventorylist[j].itemprice:

inventorylist[i],inventorylist[j]=inventorylist[j],inventorylist[i]

print 'ITEM\t\tCODE\t\tPRICE\t\tQUANTIY'

for item in inventorylist:

item.show()

raw_input()

2.

def insertionsort(a):

for i in range(1,len(a)):

currentval=a[i]

pos=i

while pos>0 and a[pos-1]>currentval:

a[pos]=a[pos-1]

pos=pos-1

a[pos]=currentval

print "Your sorted list is",a

a=[]

n=input("Enter number of integers :-")

for i in range(n):

a.append(input("Enter numbers :-"))

print"Your list is",a

insertionsort(a)

6.class stack:

s=[]

def push(self):

a=input("Enter number :")

stack.s.append(a)

def pop(self):

if (a.s==[]):

print "Stack Empty"

else:

print "Deleted element is : ",a.s.pop()

def display(self):

l=len(stack.s)

print "STACK CONTENTS"

for i in range(l-1,-1,-1):

print stack.s[i]

a=stack()

n= input("Enter count of numbers")

for i in range(n):

a.push()

a.pop()

a.display()

7. # Bookstack

class stack:

s=[]

count=0

def push(self):

no = input("Enter book number")

name=raw_input("Enter any name :")

stack.book=name

stack.s.append(stack.book)

stack.count=stack.count+1

def pop(self):

stack.count = stack.count-1

print stack.s.pop()

print stack.count

#print "Deleted element is : ",stack.s[stack.count].pop()

def display(self):

l=len(stack.s)

print "STACK CONTENTS"

print "BOOK NUM"," ","BOOK NAME"

for i in range(l-1,-1,-1):

print i+1," ",stack.s[i]

a=stack()

choice=0

while choice<4:

choice = int(raw_input("Enter 1-push 2- pop 3-view 4 - quit"))

if choice == 1:

n=input("Enter no. of names")

for i in range(n):

a.push()

elif choice==2:

a.pop()

elif choice==3:

a.display()

else:

break

8. class ReservationQ:

def __init__(self):

self.items = []

def isEmpty(self):

return self.items == []

def enqueue(self, item):

self.items.insert(0,item)

def dequeue(self):

return self.items.pop()

def size(self):

return len(self.items)

def display(self):

print "FRONT -->",

x = self.size()

for a in range(x-1,-1,-1):

print self.items[a],"-->",

print "REAR"

choice=0

x= ReservationQ()

while choice<4:

choice = input("Enter 1 -insert 2- delete 3-view 4- quit")

if choice==1:

if x.size() > 4:

print " Reservation is not possible"

break

item = raw_input("Enter PNR number")

x.enqueue(item)

elif choice==2:

if x.isEmpty():

print "Reservation Queue is empty"

break

x.dequeue()

elif choice==3:

x.display()

else:

break

Chapter 11

1. def CountDorM():

count=0

with open('DELHI.txt','r') as f:

while True:

line=f.readline()

if not line: break

if line[0]=='D' or line[0]=='M':

count = count+1

if count == 0:

print "no line starts with D or M"

else:

print "count=",count

CountDorM()

2. def countchar():

fname = "story.txt"

count=0

c = raw_input("Enter the character to search for")

with open(fname, 'r') as f:

for line in f:

for word in line:

for char in word:

if char.strip() == c.strip():

count=count + 1

print "No. of occurences of",c,"=",count

countchar()

3. Ans.

import pickle

# Creating the dictionary

R = {'I': 1, 'II': 2, 'III': 3, 'IV':4, 'V':5}

file = open('myfile.dat', 'wb')

pickle.dump(R,file)

file.close()

roman = raw_input("Enter the roman numeral")

# read python dict back from the file

ifile = open('myfile.dat', 'rb')

R = pickle.load(ifile) # reading data from binary file

try:

print "Decimal Equivalent of",roman,"is",R[roman]

except:

print "No equivalent found"

6.

Ans.

try:

for line in open("story.txt"):

line = line.strip()

if line[0]=='#':

print line

except:

print 'File Not Found'

Chapter 12

5.

try:

n = input("Enter year")

if n<1000 or n>2015:

raise "Invalid year",n

else:

month = input("Enter month")

if month<1 or month>12:

raise "Invalid month",month

else:

day = input("Enter day")

if day<1 or day>31:

raise "Invalid day",day

else:

print day,'/',month,'/',n

except:

print "Wrong Values"

6. class Student:

# constructor to create an object

def __init__(self):

self.rollno = 0

self.name = ''

self.marks = [0,0,0]

self.grade = ''

def read (self):

# This function gets the details of a student from the user

x=1

while x==1:

try:

self.rollno = input("Enter roll number:-")

except NameError:

print "Roll number should be a number"

continue

self.name = raw_input("Enter name:-")

try:

self.marks =float(raw_input("Enter the marks -"))

except NameError:

print "Marks should be decimal"

continue

except ValueError:

print "Marks should be decimal"

continue

x=0

s= Student()

s.read()

Reference books

1.“Python Programming for the Absolute Beginner” by Michael Dawson Premier Press 2003.

2.Python Tutorial Release 2.6.3 by Guido van Rossum and Fred L. Drake, Jr., editor October 06, 2009 - Python Software Foundation

3.“Computer Science – Class XI” by Central Board of Secondary Education, New Delhi 2013.

4.“Introduction to Programming Using Python” by Brian Heinold , Department of Mathematics and Computer Science , Mount St. Mary’s University

5.“COMPREHENSIVE COMPUTER SCIENCE WITH PYTHON–XI” by Pavithra Karthik, Laxmi Publications, 2015

6.“ COMPREHENSIVE COMPUTER SCIENCE WITH PYTHON–XII” by Pavithra Karthik, Laxmi Publications, 2016

Web links

1. http://www.tutorialspoint.com/python

2. http://docs.python.org/

3. http://www.pythontutor.com/

4. www.studiestoday.com

Other books by the same author

1. “A Practical Workbook for CBSE Computer Science (C++) – Class XI” by Pavithra Karthik, Laxmi Publications

2. “A Practical Workbook for CBSE Computer Science (C++) – Class XII” by Pavithra Karthik, Laxmi Publications

3. “A Practical Workbook for CBSE Computer Science (Python) – Class XI” by Pavithra Karthik, Laxmi Publications

4. “A Practical Workbook for CBSE Computer Science (Python) – Class XII” by Pavithra Karthik, Laxmi Publications

5. “COMPREHENSIVE COMPUTER SCIENCE WITH PYTHON–XI” by Pavithra Karthik, Laxmi Publications, 2015

6. “ COMPREHENSIVE COMPUTER SCIENCE WITH PYTHON–XII” by Pavithra Karthik, Laxmi Publications, 2016

7. “COMPREHENSIVE COMPUTER SCIENCE WITH C++–XI” by Pavithra Karthik, Laxmi Publications, 2016

8. “ COMPREHENSIVE COMPUTER SCIENCE WITH C++–XII” by Pavithra Karthik, Laxmi Publications, 2016