Course outline · 0% complete

0/27 lessons0%

Course overview →

What a variable is

lesson 3-1 · ~10 min · 8/27

Lesson 2-3 covered what print(int("7") + 3) outputs.

10. int("7") converts the string "7" into the number 7, and 7 + 3 is 10.

Without the int(...) conversion, "7" + 3 would be an error, because Python refuses to add a string and a number. Notably it does not guess, and that refusal is a feature.

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.

nameage"Ada"36two labeled boxes in memory
Variables are labeled boxes: the label is the name you chose, the contents are the current value.

Two variables, printed back

Two assignments, then two lookups.

name = "Ada"
age = 36
print(name)
print(age)

Output

Ada
36

The output shows the stored values, not the names. print(name) looked inside the box labeled name and printed what it found.

Notice that age = 36 has no quotes while name = "Ada" does. That is the type distinction from lesson 2-2 again: age holds a number you could do arithmetic on, and name holds text. A variable does not have a fixed type of its own, it simply holds whatever value you stored.

Using a variable in a calculation

The variable's name stands in for its value anywhere a value is allowed.

favorite_number = 7
print(favorite_number * 3)

Output

21

Reading the pieces

  • Assignment comes first, favorite_number = 7, because Python runs top to bottom and cannot look up a name that has not been stored yet.
  • Then the name goes inside the print, and Python replaces favorite_number with 7 before multiplying.
  • Using the name rather than the digit is the entire point. Change the first line to 9 and the output becomes 27 with no other edit, which is what makes a program adjustable instead of fixed.