Variables and types
A program has to remember things: a score, a price, a name. It does that with variables, names that point to values stored in memory. Step through seven lines of Python and watch each value land in memory, get read back, get replaced, and see why the type of a value decides what + does.
Try it
0/2 exercises passed
Turn text into a number
The value "3" is text. Convert it to an integer before adding 4, so total is the number 7.
Ctrl/Cmd + Enter to run. Tab indents; Escape then Tab leaves the editor.
Run your code to see its output.
- Check your code when you’re ready.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01After these two lines run, what is the value of x? x = 5 then x = x + 2
The right side runs first: Python reads x (5) and adds 2. Then = stores 7 under the same name, replacing the 5.
02What does "3" + "4" give in Python?
Both are strings (text in quotes), and + joins strings end to end, so the result is the text "34".
03What happens when Python runs total = "3" + 4 ?
Python will not guess whether you meant text or a number. Convert first: int("3") + 4 is 7, and "3" + str(4) is "34".
04Which value is a float?
4.2 is a number with a decimal point, so it is a float. 42 is an int, "4.2" (in quotes) is a str, and True is a bool.
05What does reading a variable, as in y = age + 1 , do to age?
Reading only fetches the current value. Only an assignment to age itself (age = ...) changes what age holds.
Glossary
- Variable
- A name that refers to a value stored in memory, such as age referring to 31.
- Assignment
- A line like age = 30: Python works out the right side, then stores the result under the name on the left.
- Reassignment
- Assigning to a name that already exists. The name now refers to the new value; a variable holds one value at a time.
- Type
- The kind of value, which decides what you can do with it. type(x) tells you a value's type.
- int and float
- Whole numbers (30, -2) are int; numbers with a decimal point (2.5) are float.
- str
- A string: text written in quotes, such as "Sam" or "2". + joins two strings.
- bool
- A value that is either True or False.
- TypeError
- The error Python raises when an operation gets a type it cannot work with, such as "2" + 2.
Notes and sources
- The drawing gives each name one box. Strictly, a Python name refers to an object in memory, and reassignment makes the name refer to a new object (31) instead of the old one (30).
- In Python, bool is a subtype of int: True behaves like 1 and False like 0 in arithmetic.
- A float is stored in binary with about 15 to 17 significant decimal digits, so some decimals, such as 0.1, are stored as a very close approximation.
- A Python int has no fixed size limit; it can hold numbers with thousands of digits.
- An error that nothing handles stops the program, so in a script no line after line 7 would run.
Quiz Unlocks after the last step.