Question: Catching a Key Error There is a function foo ( n ) that takes an integer n does some calculations that involve dictionaries. Sadly, the

Catching a Key Error
There is a function foo(n) that takes an integer n does some calculations that involve dictionaries. Sadly, the people who wrote foo sometime look stuff up from the dictionary without checking if the key is in it first. This means the code sometimes throws a KeyError.
Write a function called safeFoo(n) that runs foo(n). If it runs successfully, it should return whatever foo returned. If it raises a KeyError, it should return None.
A sample Python run might look like this:
> foo(2) # This time it works
20
> foo(1) # This time it does not
Traceback (most recent call last):
File "", line 1, in
KeyError: 'x'
> safeFoo(1) # This will do the right thing.
None
Your code snippet should define the following variables:
Name Type Description
safeFoo function A function that safely calles foo

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!