Kodokon kodokon.com

Variables and basic types

You store values in variables and work with the int, float, str, and bool types.

8 min · 3 questions

Open this lesson in Kodokon

A variable is like a labeled box in which you store a value to reuse it later. You create a variable with the = sign, which means "store this value in this box" (and not "is equal to" as in mathematics). On the left, the name of the variable; on the right, the value.

PYTHON
age = 25
price = 19.99
name = "Alice"
is_student = True
print(age)
print(name)
Four variables, then displaying two of them.

Every value has a type, that is, a category that determines what Python can do with it. The four basic types: int for a whole number (25), float for a decimal number (19.99, written with a dot, never a comma), str for a string inside quotation marks, and bool for a boolean, a value that can only be True or False. The type function reveals the type of a value.

PYTHON
print(type(25))
print(type(19.99))
print(type("Alice"))
print(type(True))
Displays int, float, str, then bool.

You often need to convert a value from one type to another. Three functions handle this: int(...) turns a value into an integer, float(...) into a decimal number, str(...) into a string. A classic example: to insert a number into a sentence with +, you first have to convert it into a string.

PYTHON
age = 25
message = "I am " + str(age) + " years old"
print(message)
text_number = "42"
number = int(text_number)
print(number + 8)
str(age) allows the joining; int(text_number) makes the calculation possible (50).

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the type of the value 3.14?
    • int
    • float
    • str
    • bool
  2. What does the statement x = 5 do?
    • It checks whether x is equal to 5
    • It stores the value 5 in the variable x
    • It displays 5 on screen
  3. How do you turn the string '10' into an integer?
    • int('10')
    • str(10)
    • float('10')
    • bool('10')