Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Functions With No Return | 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

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.

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, 'Brazil') country_information(countries_dict, 'Germany')
copy

Note

In this code, d represents a parameter in the function country_information(d, name). When country_information function is called, countries_dict is passed to the function with name d, which holds data about various countries. Inside the function, d[name][0] accesses the area and d[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?

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