[Tutor] Still stuck - but a bit further on.

Alan Gauld alan.gauld at btinternet.com
Sun Aug 28 17:20:45 CEST 2011


On 28/08/11 14:53, Lisi wrote:

> Type the Name - leave blank to finishLisi

Notice no space before Lisi


> Type the Street, Town, Phone. Leave blank to finishth, rc, 123457
> Type the Name - leave blank to finish
> Which name to display?(blank to finish) Lisi

Notice the space before Lisi?

> Traceback (most recent call last):
>    File "/usr/local/bin/AddressBook", line 17, in<module>
>      print name, AddressBook[name]
> KeyError: ' Lisi'

Notice the space at the start of the string?
The stored entry is keyed on "Lisi" the search was for " Lisi"
which doesn't exist.

You could as an exercise make the program more robust to that kind of 
error by eliminating whitespace at each end of the key string both 
before storing the data and when searching...

You might also consider eliminating case errors by forcing both
the key string and search string to lowercase, but if you do
that you will want to store the name with case in the value
part and not rely on the key being part of the data...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list