Skip to content
Sign inGet all access
Chapter 2·10 minFree

Types & Variables

Everything is an object, operators, conversion, and dynamic-but-strong typing.

Everything is an object

There are no primitives. An integer is an object with methods, and type() tells you what anything is:

print(type(42))
print(type("hi"))
print(type(3.14))
Output<class 'int'><class 'str'><class 'float'>

Which means even a literal number has methods you can call:

print((42).bit_length())
Output6

Dynamic but strongly typed

Variables have no declared type and can be reassigned to anything:

x = 42
print(type(x), end=" ")

x = "now a string"
print(type(x))
Output<class 'int'> <class 'str'>

But Python will not quietly convert between types the way JavaScript or PHP do:

print("1" + 1)
OutputTypeError: can only concatenate str (not "int") to str

You convert explicitly:

print("1" + str(1))   # convert the number to a string
print(int("1") + 1)   # convert the string to a number
Output112

Numbers

/ always produces a float. Use // for integer division:

print(7 / 2)     # true division — always a float
print(7 // 2)    # floor division
print(7 % 2)     # remainder
print(2 ** 10)   # power
Output3.5311024

Integers have no size limit and never overflow:

print(2 ** 100)
Output1267650600228229401496703205376

Comparison and logical operators

Comparisons return a bool:

print(3 > 2)
print(3 == 2)
print(3 != 2)
OutputTrueFalseTrue

The logical operators are words, not symbols:

print(True and False)
print(True or False)
print(not True)
OutputFalseTrueFalse

Converting between types

Each built-in type doubles as a conversion function:

print(int("42"))
print(str(42))
print(float("3.14"))
Output42423.14

None

None is Python’s null. There is only one of it, and it is its own type:

x = None
print(x, type(x))
OutputNone <class 'NoneType'>

Test for it with is, not ==:

x = None
print(x is None)
OutputTrue

Type hints

You can annotate a variable with the type it is meant to hold:

name: str = "ada"
age: int = 36

print(name)
print(age)
Outputada36

Python does not enforce them. Breaking a hint still runs:

age: int = "not a number"

print(age)   # no error — hints are not checked
Outputnot a number

Multiple assignment

Assign several names at once:

a, b = 1, 2

print(a)
print(b)
Output12

Which gives you a swap with no temporary variable:

a, b = 1, 2
a, b = b, a

print(a)
print(b)
Output21

is vs ==

== asks whether two values are equal. is asks whether they are the same object:

a = [1, 2]
b = [1, 2]

print(a == b)   # same contents
print(a is b)   # but two separate lists
OutputTrueFalse