Variables and types
Names point at values. Values have types. Get this right and Python stays predictable.
- Explain what a Python variable actually is (a name bound to a value)
- Identify the core built-in types and when to use each
- Predict the result of mixing types, and read a TypeError
In Python, a variable is a name bound to a value. The name is just a label; the value is the real thing, sitting in memory. Assignment points the label at a value:
message = "hello"
count = 3
count = count + 1 # rebinds `count` to the value 4message doesn't contain the text — it refers to it. This matters the moment
two names refer to the same object, which you'll meet soon with lists.
The core built-in types
Every value has a type that determines what it is and what you can do with it. The ones you'll use constantly:
int— whole numbers:42,-7float— numbers with a decimal point:3.14,2.0str— text, in quotes:"hello",'world'bool—TrueorFalselist— an ordered, changeable collection:[1, 2, 3]dict— key→value pairs:{"name": "Ada", "born": 1815}None— the deliberate absence of a value
You can always ask what something is:
type(3) # <class 'int'>
type(3.0) # <class 'float'>
type("3") # <class 'str'>Dynamic typing, with consequences
Python is dynamically typed: a name can be bound to a value of any type, and the type travels with the value, not the name. This is flexible, but it means Python checks types as it runs, not before:
"price: " + 10 # TypeError: can only concatenate str (not "int") to str
"price: " + str(10) # "price: 10" ✓ convert firstThat error is Python telling you it won't guess what you meant by "add a number
to some text." You have to convert explicitly — turn the int into a str
with str(...), or the str into an int with int(...).
Try it yourself — this runs real Python in your browser. Edit it, break it, fix it:
int and float mix freely (1 + 2.0 is 3.0), because Python knows how to
promote an int to a float. It just refuses to silently guess across less
obvious boundaries like str and int — exactly the kind of ambiguity that
hides bugs.
Truthiness
In a boolean context, every value is either "truthy" or "falsy." Empty things are falsy:
bool(0) # False
bool("") # False
bool([]) # False
bool(None) # False
bool(42) # True
bool("hi") # TrueThis is why if my_list: reads naturally as "if the list has anything in it."
Check your understanding
Knowledge check
- 1.In Python, what is a variable?
- 2.What does "items: " + 5 do?
- 3.Which of these are falsy in Python?
Where to go next
Next: control flow — using these values to make decisions and repeat work
with if, for, and while.