Python Foundations·Lesson 2 of 67·beginner
Variables and types
Bind names to values, learn the five types you will use constantly, and see why Python cares about the difference between "28" and 28.
In this lesson · 12 min
- →Assign values to names and reuse them
- →Recognise str, int, float, bool and None
- →Convert between types deliberately, and know when Python refuses to guess
A variable is a name pointing at a value. You create one with =, which does not mean
“equals” here — it means “make this name refer to this value”.
The name on the left, the value on the right. Reassigning just re-points the name; nothing is “overwritten” in place.
The types you will use every day
Text — str
Single and double quotes are interchangeable. Pick whichever avoids escaping.
Triple quotes hold text that spans lines, newlines and all:
Whole numbers — int, and decimals — float
An int is a whole number of unlimited size. A float is a decimal, and it is approximate —
this trips up everyone once:
That is not a Python bug. Floats are binary fractions, and 0.1 has no exact binary
representation, exactly as 1/3 has no exact decimal one. Compare floats with a tolerance
rather than ==.
True or false — bool
Nothing at all — None
None is Python’s way of saying “no value here”. It is not 0, and it is not "".
You will meet None constantly: it is what a function returns when it returns nothing, and
what an optional field holds when it wasn’t provided.
Checking a type
type() tells you what you actually have — invaluable when a value came from somewhere you
don’t control.
Python will not guess for you
Many languages quietly convert a number to text when you add it to a string. Python refuses:
TypeError: can only concatenate str (not "int") to str. The fix is to convert explicitly:
The f before the quote makes it an f-string: anything inside {} is evaluated as Python
and inserted. It is the clearest of the three and the one you should reach for by default.
Conversion works in both directions, and fails loudly when it can’t:
Try it yourself
Given a name and a score as strings, print exactly: Ada scored 92%. The score must be rounded to a whole number from the string value.
Create a variable total holding the sum of the three values below, as a float.
Check yourself
What does type(3.0) report?
Recap
=binds a name to a value; rebinding just re-points the name.- The core types are
str,int,float,boolandNone. - Floats are approximate — never compare them with
==. - Python never converts types silently. Use
int(),float(),str()yourself. - f-strings (
f"{value}") are the clearest way to build text from values.