Skip to content

Variables

As in maths, variables can be defined. In Python, this is done by assigning them using a simple =.

Example
i = 11

A data type cannot be specified explicitly: the variable inherits the data type of the value that was assigned to it. This data type does not have to remain the same permanently. Each assignment sets the content again:

Example
i = 11
i = "Hello"

Variable names are largely free. They may also contain unicode characters (such as umlauts or other fonts) and numbers, but not operators, spaces, line breaks or tabs. Numbers may not be used as the first character. Upper and lower case is respected. The following is advisable:

  • Names should be easy to understand: alpha is harder to read and understand than incident_angle.
  • Names should be English: energia_cinetica may still be guessable for others, but no longer mozgási_energia.
  • Names should match the content: speed is a scalar, velocity a vector.
  • Umlauts, special characters and unicode should be avoided.

The following conventions are common:

  • Consecutive indices in the order of concurrent use are i, j, k, ...
  • Variable names are written in lower case and spaces are replaced by underscores: incident_angle.
  • A temporary variable that is only required in this line is _
  • Variables beginning with an underscore are not intended for use by third parties - particularly relevant when using external libraries where future versions may rename such variables.
  • Variables beginning with two underscores emphasise the above character.
  • Variables that end with an underscore denote the results of a procedure. This is mainly used in the field of machine learning to clearly characterise output parameters.

Keywords (i.e. commands in Python such as if or for) are not permitted as variable names.

Assignment operators

A variable should often be used explicitly in the calculation of its new value. As this is so common, there is a shorthand notation for this:

Example
i = 11
i = i + 1 # i is now 12
i += 2 # i is now 14
i /= 2 # i is now 7.0
i *= 2 # i is now 14.0
i -= 2 # i is now 12.0
i //= 2 # i is now 6.0