Python reference
Variables and assignment
Also called: = · name binding · variable · assignment statement
Definition
An assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result.
Picture it
A variable is a label on a value, not a box with a fixed size. x = x + 1 is not an equation; it means 'work out x + 1, then move the label x to that new value'. Good names carry units: speed_mps beats s.
Worked example
What does this print? laps = 3 laps = laps * 2 + 1 print(laps)
- Right side first: 3 * 2 + 1 = 7
- laps now refers to 7
AnswerIt prints 7.
✓ The number in this answer is recomputed from scratch by an automated test.
In Python
distance_m = 12.0
time_s = 4.0
speed_mps = distance_m / time_s
print(speed_mps) # 3.0Common misconceptions
- Misconception: = assigns; == compares.
- Misconception: Assigning a list to a second name does not copy it: both names point at the same list.