Quiz
Warm-up from lesson 2-3: what does print(int("7") + 3) output?
Giving values a name
Real programs need to keep track of things while they run: the score mid-game, the items in a cart, the user who just logged in. Without a way to hold on to values, a program would have to recompute or re-read everything on every line, and most software simply could not exist. This is the problem variables solve.
So far every value you used vanished the moment its line finished. A variable lets a program remember a value by giving it a name. You create one with =, the assignment operator:
name = "Ada" age = 36
Read = as "store this", not as math equality: store the string "Ada" under the name name. After that, writing name anywhere means "the value stored under name".
print(name) print(age)
No quotes around name here. print(name) prints the stored value Ada, while print("name") would print the literal text name. This is the same quotes rule from lesson 1-2 doing real work.
A good mental picture: a variable is a labeled box in the computer's memory. Assignment puts a value in the box, and using the name looks inside it.
Code exercise · python
Run this program. Then change the values on the first two lines (keep the quotes around the text) and run again.
Code exercise · python
Your turn. Create a variable called favorite_number holding 7, then print favorite_number * 3 (should output 21). Use the variable in the print, not the digit 7.