-1

I am making a small address book program as practice, do you know what's wrong with my code when I tried to add new entry?

Also, how can I make it go back to choose 1-4 instead of keep in the same sub condition like error 2?

Thanks so much!

print('|-----Welcome to Q\'s Addrss Book-------|')
print('|--------------------------------------|')
print('|Please choice from the following:-----|')
print('|----------1: Find   Contacts----------|')
print('|----------2: Add    Contacts----------|')
print('|----------3: Delete Contacts----------|')
print('|----------4: Quit Address Book--------|')

i = int(input('Can I help you? :'))
address = {'ray':1234,'simon':2345,'alen':8888}
while 1:
    if i == 1:
        x=input('What\'s his/her name?')
        print(address[x])

    if i == 2:
        x = (input('New Contact name?'))
        if address[x] is not None:
            z = str(input('Contact'+x+' with phone number: '+str(address[x])+ ' address already existed, do you want to override?(Yes/No)'))
            if z == 'yes':
                address[x] = input('New number?')
            elif z == 'no':
                break
            else:
                print('Please choose yes or no')
        else:
            address[x] = input('New number?')

    if i == 3:
        z = input('Who you want to delete:')
        if address[z] is not None:
            del address[z]
        else:
            print('Contact not existed!')

    if i == 4:
        break

Error1:

>>> 
|-----Welcome to Q's Addrss Book-------|
|--------------------------------------|
|Please choice from the following:-----|
|----------1: Find   Contacts----------|
|----------2: Add    Contacts----------|
|----------3: Delete Contacts----------|
|----------4: Quit Address Book--------|
Can I help you?:2
New Contact name?q
Traceback (most recent call last):
  File "/Users/xxx/Documents/1.py", line 18, in <module>
    if address[x] is not None:
KeyError: 'q'
>>> 

Error 2: keep looping in a sub if condition:

>>> 
|-----Welcome to Q's Addrss Book-------|
|--------------------------------------|
|Please choice from the following:-----|
|----------1: Find   Contacts----------|
|----------2: Add    Contacts----------|
|----------3: Delete Contacts----------|
|----------4: Quit Address Book--------|
Can I help you?:1
What's his/her name?ray
1234
What's his/her name?
>>>

Ok, thanks for all your guys, I have made it work, here is the correct code:

print('|-----Welcome to Q\'s Addrss Book-------|')
print('|--------------------------------------|')
print('|Please choice from the following:-----|')
print('|----------1: Find   Contacts----------|')
print('|----------2: Add    Contacts----------|')
print('|----------3: Delete Contacts----------|')
print('|----------4: Quit Address Book--------|')


address = {'ray':123456789,'simon':222222222,'alen':88888888}
while 1:
    i = int(input('Can I help you?'))
    if i == 1:
        x=input('What\'s his/her name?')
        if x in address:
            print(address[x])
        else:
            print('Contact does not exist!')

    if i == 2:
        x = (input('New Contact name?'))
        if x in address:
            z = str(input('Contact'+x+' with phone number: '+str(address[x])+ ' address already existed, do you want to override?(Yes/No)'))
            if z == 'yes':
                address[x] = input('New number?')
            elif z == 'no':
                continue
            else:
                print('Please choose yes or no')
        else:
            address[x] = input('New number?')

    if i == 3:
        z = input('Who you want to delete:')
        if z  in address:
            del address[z]
        else:
            print('Contact does not exist!')

    if i == 4:
        break
ray
  • 641
  • 2
  • 8
  • 13
  • http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary Is a better way to check if a name exists instead of `if address[x] is not None:` – Stack of Pancakes Aug 09 '14 at 20:22
  • It's not just a better way, it's the *only* way. `if address[x] is not None:` doesn't work. It throws a KeyError whenever `x` is not in the `address` dictionary. – David Robinson Aug 09 '14 at 20:22
  • 1
    @DavidRobinson Well, not the only way. The best way. However you could also use a default dict and use OPs method. Or you could use the dict.get method with None being the default. But yes, I understand what you're saying and agree that using `in` should be the only way used. – Stack of Pancakes Aug 09 '14 at 20:26
  • 1
    For the second error you just need to put `i = int(input('Can I help you? :'))` inside the while loop. Or put a condition that will break if i==1 and the input is blank or something. – Stack of Pancakes Aug 09 '14 at 20:27
  • thanks so much Stack of Pancakes!!! it worked!!! sorry for my dump question :) – ray Aug 09 '14 at 22:16

1 Answers1

0

'Stack of Pancakes' has answered the second part of your question already (see comments above)

When you're trying to check whether the contact already exists, it's important to clarify that address[x] == None will never return True if x is not a key in the dictionary. If Python can't find a key in a dictionary, it doesn't return None, but throws a KeyError exception. Python uses exceptions far more liberally than some other languages - this article covers them in a bit more detail, and you can also read the docs

The 'pythonic' way to work with them is more like this:

if x not in address:
    ....

And then in your block for deleting contacts:

try:
    del address[z]
except KeyError:
    print('Contact does not exist!')

Here the code 'tries' to delete the key from the dictionary. If the key never existed in the first place, a KeyError exception is raised on the second line of this code. But we have an except clause specifically designed to catch KeyError exceptions, so you won't see a stack trace. Execution moves to the print function on the final line.

Stephan
  • 2,863
  • 1
  • 17
  • 14
  • HI Stephan, I tried adding " except KeyError:" that one, but it said invalid sytax? – ray Aug 09 '14 at 22:24
  • Did the error give any more detail than that? You could check indentation first - make sure it matches that above and in [the docs](https://docs.python.org/2/tutorial/errors.html#handling-exceptions). If not that, the syntax error is probably in the blocks themselves - either on the line `del address[z]` or in the print function. If you keep getting the error then make an edit to the question and paste your code in there. – Stephan Aug 09 '14 at 22:36