Python Basics
Theory: Return values
In this lesson, we will look at how to work with the functions we created.
When we define a function, it prints data on the screen:
These functions are useless because we cannot use its result in a program.
Let us look at another example. Suppose we process email addresses. When users register on the site, they can enter their email addresses any way they want:
- Add spaces at the beginning or the end by accident:
_support@hexlet.io__ - Use letters in a different case:
SUPPORT@hexlet.io
In this case, users cannot log in if we save data like this in the database. We can prevent it and prepare the email addresses before writing them to the database. We should convert them to lowercase and trim the spaces around the string edges. We can solve the problem in a couple of lines:
This code works because the strip() and lower() methods do not print anything on the screen. Instead, they return the results of their work so we can write the calculated values to variables. We can not assign the results to variables when the program prints the values on the screen. For example, we cannot do it with the greeting() function:
Now, we will change the greeting() function to make it return the data. To do this, we use a return instead of printing to the screen:
The return is an instruction. It takes the expression from the right and gives it to a method. It is where the function ends:
Python does not execute any code after the return instruction:
Even when the function returns data, there are no limits on printing. In addition to returning data, we can also print it:
You can print more than a specific value. Since return works with expressions, we can use anything to the right of it. But still, we should keep with the code readability:
Here we do not return a variable, but Python always returns its value. You can see an example with calculations below:
We cannot define functions without thinking about whether we will be able to use their results or not.
For practice, think about the results the call to run() returns:
Completed
0 / 43