Sharl
Sharl

Reputation: 175

Returning an exception after using a loop

My function is passed a dictionary (of a name and a score) and a name. It then compares the name to see if its in the dictionary, and if it is, it prints the name and score.

def display_marks_for(adict,name):
try:
    for key in adict:
        if name == key:
            print(name,"=",adict[key])
except KeyError:
    print(name,'not on list')

My code prints the right thing if the name is in the dictionary but if the name doesn't exist, it doesn't print anything?

I want it to say that the name is not on the list.

Thanks

Upvotes: 0

Views: 41

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Your code can be simplified to the following, as you do not need to loop through all the keys (that's the whole point of a dictionary - avoid looping to find something):

def display_marks_for(adict, name):
   mark = adict.get(name)
   if mark:
      print('{}={}'.format(name, mark))
   else:
      print('{} is not in the dictionary'.format(name))

The get() method of dictionaries tries to find a value for the given key, and if it doesn't exist - instead of raising KeyError, it returns None.

If you wanted to practice capturing the KeyError, you can modify your method thus - note again you don't need a loop:

def display_marks_for(adict, name):
    try:
        mark = adict[name]
        print('{}={}'.format(name, mark))
    except KeyError:
        print('{} is not in the dictionary'.format(name))

Upvotes: 1

user3636636
user3636636

Reputation: 2499

You wont get a keyError if you are iterating through the keys in the dictionary, because they will all be there. You might be best using an else statement if the key doesn't match name

def display_marks_for(adict,name):
    if name in adict.keys():
        print(name,"=",adict[name])
    else:
        print(name,'not on list')

Or if you do want to use KeyError exception, don't iterate through your dictionaries keys:

def display_marks_for(adict,name):
    try:
        print(name,"=",adict[name]) #Will Raise KeyError if does not exist
    except KeyError:
        print(name,'not on list')

Upvotes: 1

Related Questions