Variables and core types

RequiredRequired

Juan Camilo ZúñigaBackend & data developer

A variable is a name that points to a value. There is no declaration: assigning creates the name, and the value carries the type, not the variable.

count = 3            # int
price = 9.99         # float
name = "Ada"         # str
active = True        # bool
nothing = None       # NoneType: "no value"

type(value) tells you what something is:

>>> type(price)
<class 'float'>

Numbers

int has no size limit (2 ** 100 just works). float is a binary floating point number, so 0.1 + 0.2 is 0.30000000000000004. For money, use decimal.Decimal or count in cents with int.

Division always returns a float: 7 / 2 is 3.5. Use // for floor division (7 // 2 is 3) and % for the remainder.

Truthiness

Every value is true or false in a condition. These are false: False, None, 0, 0.0, "", and empty collections ([], {}, set()). Everything else is true, so if items: reads as “if there are items”.

Converting

Input from a user or a file is text. Convert it explicitly:

age = int(input("Age: "))   # "31" -> 31; "abc" raises ValueError