Names Refer to Values
Return to the temperature report and explain what its names do. Trace assignment and reassignment, then choose valid names that make each value's role clear.
The first program used names before we stopped to explain them:
total, count, and mean are names. A name lets a later instruction
refer to a value calculated earlier.
Read an Assignment
An assignment has a name on the left of = and an expression on the right:
count = 4
Python first evaluates the right side. It then makes count refer to the
result, 4. The equals sign here means assign this value to this name. It is
not a claim that the two sides will remain equal forever.
The four readings can have names too:
The longer program repeats information, but it makes the role of each number visible. Later we will replace the four reading names with a sequence.
Q1. Follow the name
What value does total refer to after these instructions run?
Select one choice, then check.
HintRead the right side first
reading_1 refers to 18 and reading_2 refers to 21.
Solutiontotal refers to 39
Python evaluates 18 + 21, then makes total refer to the result, 39.
Reassignment Changes the Current Value
A later assignment can make the same name refer to a new value:
For the second line, Python reads the old value of count first. It calculates
4 + 1, then makes count refer to 5. The instruction is a sequence of work,
not an algebraic equation.
| Step | Instruction | Value of count after the step |
|---|---|---|
| 1 | count = 4 | 4 |
| 2 | count = count + 1 | 5 |
Q2. Trace a reassignment
What does this program display?
Select one choice, then check.
HintKeep only the current value
After the second line, reading no longer refers to 18.
SolutionThe output is 21
The second line reads 18, adds 3, and reassigns reading to 21. Only the
final line displays a value.
Choose Names a Reader Can Follow
An ordinary Python name may contain letters, digits, and underscores, but it
cannot begin with a digit. Python treats uppercase and lowercase letters as
different, so Count and count are different names.
Use lowercase words joined with underscores for names such as
reading_count. Prefer a name that states the value's role over a short name
that saves a few keystrokes.
Q3. Choose a useful valid name
Which name best describes the number of temperature readings?
Select one choice, then check.
HintCheck validity and meaning
A name cannot begin with a digit, and x does not explain what is counted.
SolutionUse reading_count
reading_count follows the ordinary lowercase-with-underscores style and
tells the reader what the value represents.
Assignment makes a name refer to a value, and reassignment changes that reference only after Python has evaluated the right side. The report now has named inputs; next we will calculate with their numerical values.