Sometimes, developers return a positive value of a number they've set. Python has a function for this.
The abs()
function makes the number non-negative:
balance = -200
amount = abs(balance)
print(amount) # => 200
200
will appear on the screen. But then we call print(balance)
and see the old value: -200
. The abs()
function returned new data but did not change the data passed to it. It couldn't do it because the primitive types in Python are immutable.
If you remember, primitives are simple data types built-in into the programming language. For example, it can be a number or a string.
We will use ready-made and self-made functions in lessons and assignments, but none of these can modify data of primitive types. The number -200
is the value of the balance
variable, and we cannot change the number itself.
However, we can replace a variable value with another one. In other words, we can write:
balance = -200
balance = abs(balance)
print(balance)
First, we wrote a value to a variable. Then, we add a new value to the same variable instead of the previous one, which is what the abs(balance)
call will return.
The line balance = abs(balance)
can be read like this:
Write to the variable
balance
what the call toabs()
will return if we pass the current value of the variable balance to it`
We changed not the number but the variable. We wrote a new number into it instead of the old one.
Changing a variable that already exists may seem like a harmless action. But in real programs, rewriting a variable can sometimes cause big problems. Code with changeable variables is difficult to understand and analyze. You can never be sure what value a variable will have at a particular point in time.
You will likely encounter bugs and errors in applications quite regularly. Many of them appear because the variables changed. Such mistakes are hard to find and correct.
Loops are the only place where variables are not needed. You will learn about this later. In all other cases, you should treat variables like constants and immutable entities. Create variables, give them a value, and don't change them again unless you have to do it.