Understanding that types live on values, not on names, explains most of Python's dynamic behaviour.
An assignment like count = 3 creates the integer object 3 and binds the name count to it. Python is dynamically typed: the name has no declared type, and you can later rebind it to a string. The object, however, always has a definite type, and Python is strongly typed in that it will not silently convert between unrelated types: "3" + 4 is a TypeError, not "34" or 7.
The core built-in types you will use constantly:
intwhole numbers of any size,floatdouble-precision decimals,complexstrtext,bool(True/False)list,tuple,dict,setcontainersNone, the single value of typeNoneType, meaning "no value"
type(x) returns an object's type, and isinstance(x, int) checks it (and also accepts subclasses, which is usually what you want). Convert explicitly with constructors such as int("42"), float("2.5"), str(10) and bool(0).
Names are case-sensitive, may contain letters, digits and underscores, and cannot start with a digit. Convention (PEP 8) is snake_case for variables and functions, UPPER_CASE for constants, and CamelCase for classes. Python has no real constants; upper case is a promise to readers, not something enforced.
You can assign several names at once with unpacking: x, y = 1, 2, and swap them with x, y = y, x — no temporary variable needed.
Example
count = 3
print(type(count)) # <class 'int'>
count = "three" # same name, new object of another type
print(type(count)) # <class 'str'>
print(isinstance(True, int)) # True (bool is a subclass of int)
print(int("42") + 1) # 43
print(str(42) + "!") # 42!
x, y = 1, 2
x, y = y, x
print(x, y) # 2 1
result = None
print(result is None) # TrueRemember
- Names are labels bound to objects; objects carry the type
- Python won't implicitly mix unrelated types like str and int
- Use
isinstance()for type checks and constructors likeint()to convert
Watch out for
- Shadowing built-ins by naming a variable
list,strorid, which breaks later calls to them.