Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Modifying Functions | Functions
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

book
Modifying Functions

Let's revisit the example with the country information. What happens if the name parameter isn't found in the data?

1234567891011121314
# 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')
copy

Can we manage this problem? Absolutely, by implementing conditional statements!

1234567891011121314151617
# 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")
copy

Note

d.keys() is a method used with dictionaries that produces a list of all keys in the dictionary d. Here, it's utilized to verify whether the name 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.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 9
We're sorry to hear that something went wrong. What happened?
some-alt