60 min

Variables and types

Names for values, numbers and strings, and input from the user.

A name for a value

A variable is a name that points at a value. You create one with =, which in Python means "store", not "equals":

age = 20
name = "Noa"
print(name, "is", age)

After the line age = 20, wherever we write age Python uses 20. If we later write age = 21, the name points at the new value and the old one is simply forgotten.

Types

Every value has a type, and the type decides what you can do with it. Three types show up right away:

TypeExampleWhat it is
int42a whole number
float3.5a number with a decimal point
str"hello"a string (text)

The function type tells you a value's type:

print(type(42))      # <class 'int'>
print(type("42"))    # <class 'str'>

42 and "42" look alike but are completely different values: the first is a number, the second is a text of two characters. That is why "7" + "5" gives "75": adding strings glues them together.

Input from the user

The function input pauses the program, waits for the user to type something, and returns it always as a string:

year = input("What year were you born? ")
age = 2026 - int(year)
print("This year you turn", age)

Without int(...) the second line would fail, because you cannot subtract a string from a number. You convert between types with int, float and str.

Practice