4.1. Values and Data Types¶
Programs are made up of two main things:
Operations that do stuff with the data
Let’s start by looking at data, which is any piece of information stored in a program. The most basic unit of data is called a value.
A value is a specific piece of data, such as a word or a number. Some
"Hello, World!", and
Each value is an example of a data type. We will use many different data types in this course, but here are your first three:
string - One or more characters enclosed in quotes, such as
"Hello, World". In Python, strings can be enclosed in single quotes or double quotes, so
"B"both count as strings.
int - Stands for integer, which is a whole number like
float - Any number with a decimal like
If you are not sure of the data type for a value, Python has the
function to let us know!
1 2 3
print(type("Hello, World!")) print(type(17)) print(type(3.14))
<class 'str'> <class 'int'> <class 'float'>
Not surprisingly, Python reports that the data type of
"Hello, World!" is
str, which stands for
string. The data types for
We will learn about other data types in later chapters.
4.1.1. More On Strings¶
What about values like
"3.2"? They look like numbers, but they are in quotation marks like strings.
Run the following code to find out.
What is the data type of the values
In Python we can use either single quotes (
') or double quotes (
") for strings. Triple quotes (
""") can be used for multi-line strings.
Add the following lines to the code editor above, then run the program again.
3 4 5 6 7
print(type('This is a string')) print(type("And so is this")) print('''Rutabagas in the spring''')
Double-quoted strings can contain single quotes inside them, like
Single-quoted strings can have double quotes inside them, like
'The knights who say "Ni!"'.
Python doesn’t care whether you use single or double quotes around strings, since the quote marks are not stored as part of the value.
If a string contains a single quote (such as
Bruce's beard), then
surrounding it with single quotes gives unexpected results.
Try running the following piece of code:
4.1.2. More On Numbers¶
When you type a large number, you might be tempted to use commas, as in
42,000. However, this is NOT allowed for the
types in Python.
42000 42 0
This may be a surprising output! Because of the comma, Python treats
42,000 as a pair of values. As we saw in the
print function section,
print(42, 17, 56, 34, 11, 4.35, 32) print(3.4, "hello", 45)
42 17 56 34 11 4.35 32 3.4 hello 45
Remember not to put commas or spaces in your numbers!
Also, remember that Python and other programming languages are strict about syntax. Even the smallest change can make your program do something you did not intend.
4.1.3. Check Your Understanding¶
Identify the data type for each of the following values. Click on each option to reveal the answer.