[Tutor] addressbook program
Alan Gauld
alan.gauld at btinternet.com
Sat Jun 28 23:28:33 CEST 2008
"FT" <chester_lab at fltg.net> wrote
> #Copying the Address Book With New Name!
> def copy_Book (book):
> save = 1
> file_name2 = text_Input(" Enter Name Of File To Save Address
> Book:")
> if file_name2 == "":
> print "No File Saved!"
> save = 0
> if save == 1:
> try:
> store = open(file_name2, 'w')
> except:
> print "File Error! No File Saved!"
> save = 0
> if save == 1:
> for name,entry in book.items():
> store.write(name + '\n')
> store.write(entry + '\n')
> store.close()
> print "%s File Saved and Closed!" % file_name2
This is unnecessarily complex. By rearranging the logic slightly we
can write it as:
def copy_Book (book):
file_name2 = text_Input(" Enter Name Of File To Save Address
Book:")
if file_name2:
try:
store = open(file_name2, 'w')
for name,entry in book.items():
store.write(name + '\n')
store.write(entry + '\n')
store.close()
print "%s File Saved and Closed!" % file_name2
except:
print "File Error! No File Saved!"
return
However, I'd prefer to pass the filename in as an argument since
mixing processing and user interaction is usually a bad idea.
Also in the tutorial I don't use try/except because I haven't
covered them yet!
> #Getting User Input
> def get_Choice( menu, msg=""):
> e=1
> while e==1:
> e=0
> try:
> choice = key_input(msg)
> except:
> choice=0
Again the use of the e flag is making the structure more complex
than is necessary. In Python you can usually avoid the use of
such flags by reworking the logic - often by reversing a boolean
test as I did above.
> #DO TEXT INPUT WITH ENTRY ON NEXT LINE!
> def text_Input(prompt):
> print prompt
> return (raw_input(">> "))
Just use:
raw_input(prompt + "\n>> " )
> def add_Entry (book):
> name = text_Input("Enter a name: ")
> if name != "":
> entry = text_Input("Enter Street, City/Town and Phone
> Number: ")
> if name != "" and entry != "":
> book[ name.capitalize()] = entry
> else:
> print "No entry saved!"
Could be simplified to:
def add_Entry (book):
name = text_Input("Enter a name: ")
entry = text_Input("Enter Street, City/Town and Phone Number: ")
if name and entry:
book[ name.capitalize()] = entry
else:
print "No entry saved!"
> def key_input( msg):
> "ENTER A KEY OR FUNCTION KEY, (ALT, CTRL, SHIFT...KEY)"
> # clear the keyboard buffer
> ch=""; ch1=""; sch=""
> while msvcrt.kbhit():
> ch = msvcrt.getch()
Given the OP was a novice I suspect this might be a tad advanced
at this stage :-)
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list