Your First Variable
第一个变量
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.
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 nameagegets the value18"name = "Alice"→ "the namenamegets the string"Alice""
The name always goes on the left, the value on the right. Reversing them is a syntax error:
Naming rules
A name in Python can use letters, digits, and underscores. There are three rules:
- Must start with a letter or underscore — not a digit.
- No spaces, no hyphens, no
@ # $. - 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).
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.
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.