Course Content
Introduction to Python
Introduction to Python
Modifying Functions
Let's revisit the example with the country information. What happens if the name
parameter isn't found in the data?
# Data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942), 'Brazil': (8515767, 212559417), 'India': (3166391, 1380004385)} # Defining a function def country_information(d, name): print('Country:', name) print('Area:', d[name][0], 'sq km') print('Population:', round(d[name][1]/1000000, 2), 'MM') # Testing the function country_information(countries_dict, 'USA') country_information(countries_dict, 'Ukraine')
Can we manage this problem? Absolutely, by implementing conditional statements!
# Data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942), 'Brazil': (8515767, 212559417), 'India': (3166391, 1380004385)} # Modify our function def country_information_mod(d, name): if name not in d.keys(): print("There is no information about", name) else: print("Country:", name) print("Area:", d[name][0], 'sq km') print("Population:", round(d[name][1]/1000000, 2), 'mln') # Testing the function country_information_mod(countries_dict, "USA") country_information_mod(countries_dict, "Ukraine")
Note
d.keys()
is a method used with dictionaries that produces a list of all keys in the dictionaryd
. Here, it's utilized to verify whether thename
is present in the dictionary's keys.
As demonstrated, the error message in this updated format is more user-friendly. While there are many other potential errors and methods to handle them, they're outside the purview of this course.
Thanks for your feedback!