VariablesΒΆ
- One of the most powerful features of a programming language is the ability to manipulate variables.
- A variable is a name that refers to a value.
Assignment statements create new variables and also give them values to refer to.
message = "What's up, Doc?"
n = 17
pi = 3.14159
This example makes three assignments.
The assignment token, =
, should not be confused with equality (we will see later that equality uses the
==
token). The assignment statement links a name, on the left hand
side of the operator, with a value, on the right hand side. This is why you
will get an error if you enter:
17 = n
Tip
When reading or writing code, say to yourself “n is assigned 17” or “n gets the value 17” or “n is a reference to the object 17” or “n refers to the object 17”. Don’t say “n equals 17”.
If you ask Python to evaluate a variable, it will produce the value that is currently linked to the variable. In other words, evaluating a variable will give you the value that is referred to by the variable.
(ch02_9)
In each case the result is the value of the variable. To see this in even more detail, we can run the program using codelens.
(ch02_9_codelens)
Now, as you step through the statements, you can see the variables and the values they reference as those references are created.
Variables also have types; again, we can ask the interpreter what they are.
(ch02_10)
The type of a variable is the type of the object it currently refers to.
- We use variables in a program to “remember” things, like the current score at the football game.
- But variables are variable. This means they can change over time, just like the scoreboard at a football game.
- You can assign a value to a variable, and later assign a different value to the same variable.
To see this, read and then run the following program.
(ch02_11)