Purposes of functions
New:
- generating a value
- separation of concerns
In Print you've learned that the interpreter eventually perceives pow(3, 2)
not as we see it, but as the result of raising 32. From Functions overview you know that functions are built (defined) to produce results. Thus, there must be some special code in the definition which is responsible for generating the result, so that the interpreter can see it in place of the call.
That special code is a mandatory command that must be written in the end of the definition. As mentioned before, you won't see definitions until the next course. For now, look at a visualization of its components:
The function's author decides what value the command generates. Usually, the value is computed in the lines of code which are located before the final command. The computation may depend on the passed arguments, or may be unrelated to anything in the definition. However, for the majority of functions, as for pow
, the generated value directly depends on the arguments. Indeed, arguments 3
and 2
are clearly "responsible" for the observed 9
. Different arguments would yield a different result.
Let's create a more complex call:
print(pow(pow(3, 2), 4))
6561
The same principle applies: pow(3, 2)
generates 9
, which is then used in another call as an argument; another call then generates 6561
and print
shows it on the screen.
The generated value and the purpose are separate aspects of a function. They may be dependent or independent of each other.
- The purpose of
print
: to display its argument. - The purpose of
pow
and most other functions: to generate a value.
Like any function1 print
obeys the rules of Python by generating a value, but it's a special value which is unrelated to anything in the definition or arguments of print
. Thus, for print
the purpose and the generated value are independent; but for pow
they are dependent.
The fact that built-in functions don't display their generated values is a good thing. There's an important principle of computer science called separation of concerns. The job of pow
is to calculate power, that's it. It should not be concerned with displaying values on screens. The job of print
is to display values on screens. It should not be concerned with anything else. A good software project consists of numerous functions, each concerned with a limited area of tasks. Just like a decent society separates, for example, manufacturers from delivery services. When concerns are well separated, it's easier to connect pieces and build complex systems.
Summary:
- Any function call generates a value.
- The only purpose of
print
is to display its argument. However, it still generates a value, like all functions.
print
became a function in Python version 3. Before, in Python 2, it was a code unit of different nature. It means that print
did not need to generate a value. You’ll learn about the differences between kinds of code in the last chapter.