Skip to content

Names and values: variables and types

BeginnerLesson 2 of 146 min

Give values names with =, then meet the five types you use every day (int, float, str, bool and None) and ask any value for its type().

= gives a value a name, so you can use it later:

plant = "basil"
height_cm = 14.5
leaves = 9
print(plant, "is", height_cm, "cm tall with", leaves, "leaves")

Read = as "is now", not "equals": leaves = leaves + 1 makes perfect sense in Python (work out leaves + 1, then make leaves name the result).

Names can use letters, digits and _, can't start with a digit, and are case sensitive: Leaves and leaves are two different names. The habit in Python is lower case with underscores, height_cm.

Every value has a type

The type decides what a value can do. These five cover most everyday code:

TypeExamplesWhat it is
int9, -3, 2026a whole number
float14.5, 0.1, 3.0a number with a decimal point
str"basil", '9'text (a string of characters)
boolTrue, Falseyes or no
NoneTypeNone"nothing here (yet)"

type() tells you a value's type:

print(type(9), type(14.5), type("9"))
print(type(True), type(None))
<class 'int'> <class 'float'> <class 'str'>
<class 'bool'> <class 'NoneType'>

Look closely at "9": with quotes it's text, not a number. "9" + 1 is a TypeError, while int("9") + 1 is 10. int(), float() and str() turn values into those types.

True, False and None are written with a capital letter and no quotes.

Try it:Run print(type(3.0)) and print(type(3)). Same amount, different types: a decimal point makes a float.

A name is not glued to one type

A name can be given a new value at any time, even of another type: leaves = "lots" is allowed. The name doesn't have a type; the value does. That small fact explains a lot of Python, and the Advanced lessons come back to it.

More in the Python docs: built-in types and type().

Your turn

Fill in a recipe card. Make title the text Lentil soup, servings the whole number 4, cost the decimal 1.75, vegan the value True and notes the value None. Then print the type of servings.

Next →