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))Which means even a literal number has methods you can call:
print((42).bit_length())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))But Python will not quietly convert between types the way JavaScript or PHP do:
print("1" + 1)You convert explicitly:
print("1" + str(1)) # convert the number to a string
print(int("1") + 1) # convert the string to a numberNumbers
/ 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) # powerIntegers have no size limit and never overflow:
print(2 ** 100)Comparison and logical operators
Comparisons return a bool:
print(3 > 2)
print(3 == 2)
print(3 != 2)The logical operators are words, not symbols:
print(True and False)
print(True or False)
print(not True)Converting between types
Each built-in type doubles as a conversion function:
print(int("42"))
print(str(42))
print(float("3.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))Test for it with is, not ==:
x = None
print(x is None)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)Python does not enforce them. Breaking a hint still runs:
age: int = "not a number"
print(age) # no error — hints are not checkedMultiple assignment
Assign several names at once:
a, b = 1, 2
print(a)
print(b)Which gives you a swap with no temporary variable:
a, b = 1, 2
a, b = b, a
print(a)
print(b)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