-1

When I comment on all the key - values in my_dict, I should be given the last line, return 'No distance info to available', but it gives me an error

my_dict = {
    # "distance": 500.5,
    # 'speed': 60,
    # 'time': 55
}

    def rout_info(my_data):
        if type(my_data["distance"]) is int:
            return f'Distance to your distination is {my_data["distance"]}'
        elif 'speed' and 'time' in my_data:
            return f'Disntace to your destination is {my_data["speed"] * my_data["time"]}'
        else:
            return 'No distance info to available'
    

print(rout_info(my_dict))

My Error:

Traceback (most recent call last):
     print(rout_info(my_dict))
          ^^^^^^^^^^^^^^^^^^
     if type(my_data["distance"]) is int:
            ~~~~~~~^^^^^^^^^^^^
    KeyError: 'distance'

When I remove the comment, the if operator and the elif operator work for me

egrqX
  • 11
  • 1
  • Welcome to Stack Overflow. Please include your code and traceback errors as text and not as images. – ewokx Aug 07 '23 at 02:34
  • [This](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) is how to add code block – Bench Vue Aug 07 '23 at 02:47
  • I would like to see an example of how to use the line: if type(my_data["distance"]) is int: to make everything work – egrqX Aug 07 '23 at 03:01
  • Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – ryanwebjackson Aug 10 '23 at 14:45

2 Answers2

1

Based on the code provided your error comes from the fact the dictionary is commented out so of course you can't access distance key.

The other issue is that type(my_data["distance"]) is int is a bad practice. is keyword is used to test that objects on both sides refer to the same object and it is normally used for singletons, for example:

a = None
a is None    # True

In other cases isinstance function should be used, so your code should look like:

if isinstance(my_data["distance"], int):
NotAName
  • 3,821
  • 2
  • 29
  • 44
1

When the dictionary does not have a key, trying to access it results in an error. In order to prevent such an error you can access your dictionary value using get(), so when a key does not exist it returns None instead of raising an error. the code would look like this:

    if type(my_data.get('distance')) is int: