Functions in every programming language have fundamental properties. These properties help predict their behavior, how to test them, and where to use them. These properties include determinacy.
In this lesson, we'll deal with deterministic functions. We will find out why these function types produce a result that we cannot apply in any way.
Deterministic functions
A deterministic function returns the same result every time if the input parameters are the same. For example, we can consider a deterministic function counting the number of characters:
len('hexlet') # 6
len('hexlet') # 6
len('wow') # 3
len('wow') # 3
You can call this function as many times as you want and pass the value 'hexlet'
. It will always return 6
.
Let's also look at the opposite. For example, we can consider a nondeterministic function that returns a random number belonging to this category: we'll always get different results even if we use the same input. If at least one in a million calls to a function returns a different result, it's considered nondeterministic. It applies even if it doesn't take the parameters:
# You will learn more about import syntax later
from random import random
# A function that returns a random number
random() # 0.09856613113197676
random() # 0.8839904367241888
Determinism affects many aspects. For example, deterministic functions are convenient to work with, as they're easy to optimize and test. If possible, it is better to make the deterministic function.
Now consider a function that calls a result with which we can do nothing.
Side effects
Python has a print()
function. It takes any data type as input and outputs it to the screen. It causes a side effect — because of the execution of the function, it triggers an action that changes the execution environment. Any network interaction, reading and writing to files, displaying information on the screen, or printing to a printer, will cause more side effects.
Side effects are one of the sources of problems and errors in software systems. This sort of code is harder to test, reducing its reliability. That said, without side effects, programming is meaningless. Without them, it would be impossible to get the result of the program: for example, to write to a database, display something on the screen, or send something over the network.
The print()
side effects differ from all other functions, taking any data type as input. Others return reusable values, but in contrast, the print()
function returns an unusable result. Printing to the screen and returning a value are different and independent operations.
In this lesson, we learned about side effects at a basic level. But you should go deeper and study the nuances so that this knowledge can help you build quality programs. If you're interested in working with side effects, you can learn more about them in other courses on Hexlet.