Using variables

Using variables#

The whole idea behind programming, and what it distinguishes from using a desktop calculator for example, is that values, such as for parameters or constants can be stored in variables, and hence be changed. The syntax for this is to use some string for the name of the variable, followed by an equal sign, which is the assigment operator and the value itself, which should be made available when using the variable. Any dataype can be used, when assiging a value to a variable. For example in order to assign the value to a variable named a use the following statement

a = 2

From this point on the variable can be used as a synomym to the value 1. So

a ** 2
4

will calculate the value of a to the power 2. When changing the value of a and repeating the calculation. The result will obviously change as well.

a = 3
a ** 2
9

Note

Python does not have the concept of constants. There is no real way in Python to make an expression, where the value truly cannot be changed. There are ways to come very close to the necessary behaviour, but there is no exactly matching concept of constants. And most usually this is never really necessary to have this in algorithms. The true reason for having constants in other programming languages is for efficiency reasons. Constants can be handled in a different, more memory efficient way than variables. And this was not considered to be of interest when designing the Python programming language. It is quite common though to indicate something should considered to be understood as a constant when the variable name is written in all uppercase letters.

We’ve used a very short and meaningless variable name here: a. This works in Python of course, but does not really help understanding what’s going on here. Those trivial variable names are good for showing trivial things, or short lived concepts, within interactive sessions for example. It is however not a good idea to use them in source code meant for production environments. Think of someone else needing to understand what you have implemented, or even your future self in half a year or more needs to revisit an algorithm to do some updates or bug fixing. Speaking variable names help a lot here and support one of the Pythin idioms to write down readable code.

Here’s a little example to help calculating a discount effective on a price with more meaningful variable names.

discount = 13 # in percent of price
price = 99.90 # in EUR
price - (discount / 100) * price
86.91300000000001