Course Content
Introduction to Python
Introduction to Python
Functions Without Return in Python
Up to this point, functions have typically returned some form of information upon completing their tasks. However, it's not always necessary for a function to return or store data. Sometimes, the goal of a function might simply be to display information.
Consider a dictionary named countries_dict
, structured as country: (area, population)
. A function can be defined to accept two arguments: d
(expected to be a dictionary) and name
(expected to be a key in the dictionary). Rather than returning data, the function will display the information in an easily readable format.
# 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, 'Brazil') country_information(countries_dict, 'Germany')
Note
In the function
country_information(d, name)
, the parameterd
receives the dictionary (countries_dict
) when the function is called. Inside the function,d[name][0]
gives the area, andd[name][1]
gives the population of the specified country.
You can notice that the function includes two parameters not explicitly defined elsewhere in the code. These parameters are local variables—they exist only within the function and cannot be accessed externally.
When invoking the function (as in the last two lines), countries_dict
is passed to the parameter d
, while 'Brazil'
or 'Germany'
is passed to the parameter name
.
Thanks for your feedback!