1.5: Values and types
- Page ID
- 40777
A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2
, 42.0
, and 'Hello, World!'
.
These values belong to different types: 2
is an integer, 42.0
is a floating-point number, and 'Hello, World!'
is a string, so-called because the letters it contains are strung together.
If you are not sure what type a value has, the interpreter can tell you:
>>> type(2) <class 'int'> >>> type(42.0) <class 'float'> >>> type('Hello, World!') <class 'str'>
In these results, the word “class” is used in the sense of a category; a type is a category of values.
Not surprisingly, integers belong to the type int
, strings belong to str
and floating-point numbers belong to float
.
What about values like '2'
and '42.0'
? They look like numbers, but they are in quotation marks like strings.
>>> type('2') <class 'str'> >>> type('42.0') <class 'str'>
They’re strings.
When you type a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000
. This is not a legal integer in Python, but it is legal:
>>> 1,000,000 (1, 0, 0)
That’s not what we expected at all! Python interprets 1,000,000
as a comma-separated sequence of integers. We’ll learn more about this kind of sequence later.