Python course · Part 1: Starting out · lab 1 of 7
Python from zero
What a value is, what a name is, the one number trap that costs people money, and how to read an error message instead of fearing it. Real Python, running in your browser.
By the end you can
- Tell Python's kinds of value apart, including the one that pretends to be a number
- Divide, round and take percentages without losing cedis
- Build readable text from values with f-strings
- Read a traceback and say what went wrong and where
step 1 of 4
Values and names
Python has values: a number, a piece of text, a list of things, a yes-or-no, and nothing-at-all. A name is a label you stick on a value, and the equals sign sticks it on.
Think of names as luggage tags. The tag is not the suitcase. Moving the tag to another suitcase does not change either suitcase.
Every value has a type, and Python will tell you: type(5) is int, type("5") is str. Those two are not the same thing, and the difference is behind a large share of beginner errors. "5" + "5" is "55".
One oddity to know now rather than discover painfully later: in Python, True and False really are numbers. True == 1 is true, and isinstance(True, int) is true. So if you check for a number before you check for a true-or-false, every True will be reported as a number.
Write three small functions. The first one is where that oddity bites.
type(5) # int
type("5") # str
type([1, 2]) # list
type(True) # bool — and also, surprisingly, a kind of int
type(None) # NoneTypeWhat these words mean
- int
- A whole number: 5, -2, 1800.
- float
- A number with a decimal point: 4.5.
- str
- Text, in quotes: "hello".
- bool
- True or False. Also counts as a number.
- None
- Nothing. The absence of a value.
- isinstance(x, int)
- Asks whether x is that kind of value.
Easy to get wrong
Checking isinstance(value, int) before isinstance(value, bool)
Checking bool first
True is an int as far as Python is concerned, so the number branch catches it and your true-or-false branch never runs. Order matters, and only here.
int(text) on anything a visitor typed
Converting inside try/except, or checking first
int("abc") raises ValueError and takes the whole request down. Anything from outside has to be treated as possibly wrong.
What we check
- Numbers are called numbers
- Text is called text
- True is not reported as a number, which is the trap
- Lists and nothing are told apart
- Text that is a number converts
- Text that is not a number gives 0.0 instead of raising
- The result is a float, so decimals survive
- The greeting is built correctly
- It printed the greeting
Nothing printed yet. Run your code.