Course Content
Introduction to Python
Introduction to Python
Functions With No Return
Up until now, we've always returned some kind of information from our functions. However, it's not always necessary to return and store values after a function completes its task. Sometimes, you might just want to display something.
Let's say we have a dictionary named countries_dict
that holds data in the format country: (area, population)
. We can create a function that takes two arguments: d
(intended to be a dictionary) and name
(intended to be a key in that dictionary). This function won't return any value; instead, it will just print the data in a user-friendly 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 this code,
d
represents a parameter in the functioncountry_information(d, name)
. Whencountry_information
function is called,countries_dict
is passed to the function with named
, which holds data about various countries. Inside the function,d[name][0]
accesses the area andd[name][1]
accesses the population for the specified country.Thus,
d
is essentially a copy of the variable (countries_dict
here) that was passed to that position when the function was called.
From the example, you'll notice that the function contains two parameters that aren't explicitly defined in the code. These are local variables, and they can't be accessed outside of the function. However, when you invoke the function (as shown in the last two lines), countries_dict
is used as the d
variable, and 'Brazil'
/'Germany'
serves as the name
.
Everything was clear?