W WolfCode · CSC 141

Your First Variable

第一个变量

≈ 10 min · python-variables · Open in WolfCode

A variable is a name you give a value so you can refer to it later. That is the whole idea — but everything else in this course is built on it.

Why we need variables

A computer can compute 3 + 4 just fine. The trouble starts when the same number shows up in five different places. If you change one of them and forget the others, the program breaks. A variable is a name that holds onto a value for you, so you only have to write the value once.

Without a variable · don't do this
With variables · this is the move

The assignment statement

The single most important symbol in this lesson is =. In Python it is the assignment operator. It does not mean "equals" in the math sense — read it as "gets":

  • age = 18  →  "the name age gets the value 18"
  • name = "Alice"  →  "the name name gets the string "Alice""

The name always goes on the left, the value on the right. Reversing them is a syntax error:

Try running this — and read the error carefully

Naming rules

A name in Python can use letters, digits, and underscores. There are three rules:

  1. Must start with a letter or underscore — not a digit.
  2. No spaces, no hyphens, no @ # $.
  3. Cannot be a Python keyword like if, for, class, return.

By convention in Python, names use snake_case: first_name, total_cents, is_logged_in. Not firstName (that's Java/JavaScript), not FirstName (Python reserves that for class names).

Which of these names are legal?

Variables can be reassigned

The "variable" part of the word is literal: the value behind a name can change. The new value simply replaces the old one.

Python · runnable

Check yourself

x = 10 then x = 20 then print(x)

After this code runs, what does `print(x)` show?

Now you try

Open this lesson in WolfCode: the file 01-first-variable.py has age = ? waiting for a value. Assign your own age, then run the lesson with Ctrl+Enter.