Value data types
Programmes process structured information: it is therefore not just a question of what exactly is displayed, but also how the information is stored. We can either say "next Monday" or specify a concrete date. The information is identical, but depending on the context, one is easier to process than the other.
Python basically offers very similar data types to other programming languages. Here we first cover the most important built-in data types. You can define your own, as we will see later.
- int (integer) stores an integer without restrictions in the value range (e.g. 42)
- float (float) stores a decimal number in (usual) double precision (e.g. 1.2)
- str (string) stores a character string (e.g. "a word"); in Python always in single or double inverted commas
- bool (Boolean) stores a truth expression (
True
orFalse
) - bytes (bytes) contains a byte sequence, i.e. binary data (e.g. an image or measurement data)
Data types are not declared, but arise through implicit use. This is also known as weak typing or "duck typing": as long as an object behaves like a number, it is irrelevant whether it is actually a number.
Each of the data types has its own functions that work on this data type. Number functions, for example, can only be applied to number data types, but not to character strings. Thus 1+1
or 1+1.2
is permitted, but 1+"1"
(i.e. the sum of number and character string) is not permitted and is acknowledged with an error, the TypeError
. An implicit conversion is only carried out from integers to decimal numbers (but not vice versa), as well as between Booleans and integers (in both directions). In general, implicit conversions of data types tend to have side effects that are not always clearly understood and therefore generate errors that go unrecognised for a long time. Explicit conversions are easily possible: int("2")
results in 2
and str(2)
results in "2"
.
Exercise questions
-
Which of the following expressions is allowed?
42 - 7
1 * True
1.1 * True
1.1 * "True"
-
Natural numbers are represented as
int
. How are rational numbers represented? -
Which of the following conversions fail and why?
str(1.2)
int(1,3)
float(2)