dimanche 1 mars 2020

Write a Function [closed]

Write a function show_value() that takes two arguments:

a potential key and a dictionary name. If the potential key is in the dictionary, the function should return the value for that key. If the potential key, say invalid_key, is not in the dictionary, it should return the string:

invalid_key is not a valid key.

Hints and suggestions Hint: The built-in function str() may be useful. Also, make sure that the string that your function returns matches the example string above exactly.

You may want to write your function first in your favourite Python editor (for instance IDLE) and test it with test_dictionary. For this purpose, include the following line in your Python script:

test_dictionary = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Test the function with calls such as show_value(1, test_dictionary). You can include such a call in your script or run the script and then call the function from the shell. (For a reminder on how to use the shell and editor together, see for example Section 4.3.2 of Block 2, in particular, Figure 4.10 on Page 200.) Also try the function with values that are not in test_dictionary. For instance, show_value(10, test_dictionary).

Once you feel that your version of show_value() works as required, enter it in the answer box below, where indicated. Note that the answer box already contains a line that assigns a dictionary to test_dictionary. Do not change this line. Once you have added your function, you can check your answer. Your function will automatically be called with a variety of test inputs. You do not need to add any additional lines to call the function; it is called automatically when you press the 'check' button. You will receive feedback on whether your function produces the expected output for each of these test inputs.

Aucun commentaire:

Enregistrer un commentaire