Variables & Data Types — Python

A variable is a name stuck onto a value with =, for example price = 5. There is no extra word in front of the name, and you don't write the type (the kind of…

Mr. Darto wants his till to show Price: 5. He writes print("Price: " + price), but Python stops with a TypeError. The code looks reasonable. The problem is that price holds a number, but "Price: " is text. Python refuses to join two different kinds of value. To understand why, we start with variables and the types of their values.

A variable is a name stuck onto a value, so that you can use the value again later. Think of the price labels in the stall's display case: a label that says price is stuck onto the number 5. The label is the variable's name, and the number 5 is its value. When the price goes up, the label is removed and stuck onto the new number. The same label can go on a number or on text. So in Python, the type (the kind of value, such as a number or text) belongs to the value, not to the name.

Making a variable

Here are five variables. The comment on the right names the type of each value:

item_name = "Sweet tea"   # str: text
price = 5                 # int: a whole number
rating = 4.5              # float: a fractional number
is_open = True            # bool: True or False
note = None               # None: nothing in it yet

Five basic types and type()

Type Example Meaning
int 5, -3, 0 a whole number
float 4.5, 5.0 a fractional number, always with a dot
str "Sweet tea", '5' text, between double or single quotes
bool True, False true or false
NoneType None nothing in it yet

The type() function (a ready-made command in Python) tells you the type of a value. The comment on the right shows what is printed: the name of the type is inside the quotes.

print(type(price))      # <class 'int'>
print(type(rating))     # <class 'float'>
print(type(item_name))  # <class 'str'>
print(type(is_open))    # <class 'bool'>
print(type(note))       # <class 'NoneType'>

5 and 5.0 have the same value, but their types are different: the first is an int, the second is a float. print(5.0) writes 5.0, with the dot and the zero. And "5" in quotes is a str: text that happens to hold digits.

Dynamic typing

One name can be stuck onto a value of another type at any time:

price = 5
price = "five dollars"
print(type(price))  # <class 'str'>

This is called dynamic typing. A variable's type is decided while the program runs (at runtime), not when the variable is first written. The type follows the value the name is stuck to at that moment. This is convenient, but it has a cost: a type mistake, like the TypeError at the start of this lesson, is only found when the line with the mistake runs.

Text and numbers don't mix

This is Mr. Darto's code from the start of the lesson:

price = 5
print("Price: " + price)

The result is an error:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 2, in <module>
    print("Price: " + price)
          ~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to str

The opposite of str() exists too: int("5") turns text into an int, and float("4.5") turns text into a float.

Before you read on, guess: price = "5" (in quotes), then print(price * 2). Is the result 10, 55, or an error?

The result is 55. A value's type decides what an operator (a sign such as + and *) means. Because price holds text, price * 2 does not multiply numbers: it writes the text "5" two times in a row. But price + 1 is a TypeError, because text can't be joined to a number.

Text that holds a number most often comes from what a user types. input() shows a question, waits for someone to type and press Enter, then gives what they typed to your code, always as a str. So convert it with int() before you calculate:

glasses = input("How many glasses? ")  # someone types 3, so glasses holds "3"
print(int(glasses) * 5)                 # 15

On this site, code can't wait for you to type while it runs, so try this input() example with python3 on your own computer.

f-strings: putting values inside text

An example:

name = "Budi"
age = 25
print(f"Hello, {name}! You are {age} years old.")

The result:

Hello, Budi! You are 25 years old.

⚠️ Quotes, thousands commas and forgotten letters

TL;DR: A variable is a name stuck onto a value with =, for example price = 5. There is no extra word in front of the name, and you don't write the type (the kind of value). Five basic types: int (5), float (4.5, 5.0), str ("Sweet tea"), bool (True/False) and None. type(x) shows the type, for example <class 'int'>. Dynamic typing: the type is decided while the program runs, from the value, and one name may change type. "Price: " + 5 is a TypeError (an error because the types don't match), so turn the number into text first with str(). Another way is an f-string, text that starts with f and replaces {name} with the value of the variable name: f"Hello, {name}! You are {age} years old.". Text times a number writes the text that many times: "5" * 2 becomes 55.

⚡ A name stuck onto a value

Write:

item_name = "Sweet tea"   # str: text
price = 5                 # int: a whole number
rating = 4.5              # float: a fractional number
is_open = True            # bool: True or False
note = None               # None: nothing in it yet

Meaning: = sticks the name on the left onto the value on the right. That name is called a variable. The comment on the right names the type (the kind) of each value. You don't write the type, and no special word comes before the variable's name. type(price) tells you the type, so print(type(price)) writes <class 'int'>. If you already know JavaScript: Python has no let or var.

⚡ The type follows the value

Write:

price = 5
price = "five dollars"
print(type(price))  # <class 'str'>

Meaning: This is dynamic typing: a variable's type is decided while the program runs, from the value the name is stuck to at that moment. One name may change type at any time.

⚡ Text and numbers don't mix

Guess first: price = "5" (in quotes), then print(price * 2). What's the result?

55. price holds text, so the text "5" is written two times in a row, not multiplied.

Meaning: The type of the value decides what a sign such as + means: two texts are joined, two numbers are added. If price = 5, "Price: " + price is a TypeError (an error because the types don't match), because text can't be joined to a number. Turn the number into text first with str(price).

⚡ f-strings

Write:

name = "Budi"
age = 25
print(f"Hello, {name}! You are {age} years old.")
Guess first: with the letter f, this code writes the values of name and age into the text. If you forget the f, what gets printed?

Hello, {name}! You are {age} years old. exactly as written, curly braces included.

Meaning: The letter f before the opening quote replaces each variable name inside curly braces, such as {name}, with that variable's value. The value may be any type, and no str() is needed.

What you will learn