Variables and types
A program needs to remember things: how many lamps are left, whose turn it is, what the player typed. A variable is a name you give to a value, so you can use it later.
Making a variable
Write a name, an = sign, and a value. From then on, the name stands for that value.
1name = "Wick"2lamps = 33print(name, "has", lamps, "lamps to light")
Wick has 3 lamps to light
Here = does not mean "is equal to". It means store: work out the value on the right, then give it the name on the left. The name has no quotes, because it is not text; it is a label for something.
Changing a value
Assign to the same name again and the old value is replaced. The right side can even use the variable's own current value.
1oil = 102print(oil)3oil = 74print(oil)5oil = oil - 26print(oil)
10 7 5
Read oil = oil - 2 from the right: take the current oil (7), subtract 2, store the result (5) back under oil.
What does this print?
1a = 52b = a3a = 94print(b)
b = a makes b name the same value as a, which is 5. Then a = 9 points a at a new value; b still names 5.
Naming rules
A name can use letters, digits and the underscore _. A few rules, and one habit:
| Rule | Fine | Not allowed |
|---|---|---|
| No spaces | lamp_count | lamp count |
| Cannot start with a digit | house2 | 2house |
Only letters, digits and _ | total_cost | total-cost |
| Not a keyword | class_name | class, if, True |
Names are case-sensitive: lamps, Lamps and LAMPS are three different names. The usual Python style is lowercase words joined by underscores, like lamps_left. Pick names that say what the value is.
1lamp_count = 42print(lamp_count)3print(Lamp_count)
4
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(Lamp_count)
NameError: name 'Lamp_count' is not defined. Did you mean: 'lamp_count'?Using a name before it exists, or with a different capital letter, gives a NameError. Python even suggests the name you probably meant.
Types of values
Every value has a type, which says what kind of thing it is and what you can do with it. These five come up all the time:
| Type | What it holds | Examples |
|---|---|---|
int | a whole number | 3, -12, 2026 |
float | a number with a decimal point | 3.5, 0.1, -2.0 |
str | text (a string) | "Wick", "42", "" |
bool | yes or no | True, False |
None | "nothing here yet" | None |
The built-in type() tells you a value's type:
1print(type(42))2print(type(3.5))3print(type("42"))4print(type(True))5print(type(None))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
Notice that "42" is a str, not an int: in quotes, it is just two characters. True, False and None start with a capital letter and have no quotes. The type of None is called NoneType, and None is its only value.
A variable has no fixed type. It holds whatever you last stored in it:
1thing = 422print(thing, type(thing))3thing = "forty-two"4print(thing, type(thing))
42 <class 'int'> forty-two <class 'str'>
Converting between types
Python will not guess what you mean when types are mixed. Text and a number cannot be added:
1stock = "30"2print(stock + 1)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(stock + 1)
TypeError: can only concatenate str (not "int") to strConvert first. Each type's name works as a function that makes a value of that type:
| Call | Gives | Example |
|---|---|---|
int(x) | a whole number | int("12") is 12; int(3.9) is 3 |
float(x) | a decimal number | float("2.5") is 2.5 |
str(x) | text | str(7) is "7" |
1print(int("30") + 1)2print(float("2.5"))3print(str(7) + " lamps")4print(int(3.9))5print(int("abc"))
31
2.5
7 lamps
3
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(int("abc"))
ValueError: invalid literal for int() with base 10: 'abc'int(3.9) cuts off the decimals; it does not round. And int("abc") fails with a ValueError: the type is right (a string), but there is no number in it.
Tip: TypeError means the kinds of values don't fit together. ValueError means the kind is right but the value itself is wrong.
f-strings
Joining text and numbers with commas works, but an f-string is usually clearer. Put an f before the opening quote, then write any variable or calculation inside { }:
1name = "Wick"2lamps = 33print(f"{name} has {lamps} lamps to light")4print(f"After one more: {lamps + 1}")5print("Without the f: {name}")
Wick has 3 lamps to light
After one more: 4
Without the f: {name}
Python fills in each { } and turns the result into text for you, so there is no need for str(). Forget the f and the curly braces are printed as they are.
Swapping two variables
Sometimes two variables need to trade values. The obvious way does not work:
What does this print?
1a = "red"2b = "blue"3a = b4b = a5print(a, b)
a = b points a at blue, so nothing names red anymore. Then b = a points b at that same blue.
Python has a neat way to do it in one line. The right side is worked out first, then both names are given their new values together:
1a = "red"2b = "blue"3a, b = b, a4print(a, b)
blue red
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Restock
✓The shop has stock lamps, stored as text. Add delivered to it and print the line below.
Lamps in stock: 12
1stock = "8"2delivered = 43print("Lamps in stock:", stock)
A sentence from variables
✓Use an f-string with name and age to print the sentence below.
Ada is 36 years old.
1name = "Ada"2age = 363print(name, age)
Trade places
✓Add one line so that the last line prints the two drinks the other way around.
coffee tea
1first = "tea"2second = "coffee"3# your line here4print(first, second)
What you learned
name = valuestores a value under a name; assigning again replaces it.- Names use letters, digits and
_, cannot start with a digit, and are case-sensitive. - The basic types are
int,float,str,boolandNone;type()tells you which. int(),float()andstr()convert; mixing text and numbers without converting is aTypeError.- An f-string like
f"{name} has {lamps}"puts values into text. a, b = b, aswaps two variables.