Python 101Free
FOUNDATIONS

Variables and Types

How Python names values and what built-in types you start with.

SECTION 01

The four core types

Most Python programs do their work with four scalar types. int for whole numbers, float for decimals, str for text, bool for true and false. There are more types underneath, but these are the ones you reach for first.

Values have a type, but variables do not. The same name can point at an integer one moment and a string the next. Python figures the type out from whatever object the name currently refers to.

This is why Python feels flexible: you do not declare types up front. The flip side is that a typo can quietly leave a name pointing at the wrong kind of thing. Reading code carefully matters more than it does in a language with type declarations.

python
x = 7          # int
y = 3.14       # float
name = "Ada"   # str
ok = True      # bool

x = "hello"    # rebinding to a different type is fine
SECTION 02

Names point to objects

Assignment in Python does not copy a value into a slot. It binds a name to an object on the heap. Two names can point at the same object, and changing the object through one name changes what the other name sees.

This is the cause of one of the more confusing surprises in Python. If you say b = a and a is a list, then a.append(99) will change b too. They are pointing at the same list.

For immutable values like integers and strings, this never matters. The object cannot change, so there is no shared mutation to worry about. The trap only appears with lists, dicts, sets, and other mutable containers.

python
a = [1, 2]
b = a            # same list, two names
a.append(99)
print(b)         # [1, 2, 99]
SECTION 03

Type conversion and inspection

When you need to change a value's type, you call the type itself as a function. int("42") parses a string into an integer. str(3.14) formats a float into a string. Python does almost no implicit conversion between strings and numbers, which is why beginners hit TypeError early.

To find out what type a value has at runtime, use type(x) or isinstance(x, int). The first is for printing, the second is for branching. Use isinstance whenever you actually need to make a decision based on type.

Most code never needs to ask. If a function is supposed to take an integer, document that fact and trust the caller. Adding type checks everywhere makes Python feel like a more rigid language without giving you any of the benefits of one.

python
int("42")              # 42
str(3.14)              # '3.14'
type(42)               # <class 'int'>
isinstance(42, int)    # True
NEXT →
Operators and Expressions