0%

Values and Variables · practice

Variables Can Change

A name can refer to a different later in the program. That ability to change is the reason we call it a variable.

Run this example:

Try it

The same variable is assigned twice. The second replaces the value currently attached to status.

Python prints both words because the first print instruction runs before the value changes:

waiting
ready

Follow the program one line at a time

Imagine Python keeping a small note for the current value of status:

After this lineCurrent value of status
status = "waiting""waiting"
print(status)still "waiting"
status = "ready""ready"
print(status)still "ready"

The Step view makes this table visible in the actual program. In the exercise editor, move forward one instruction at a time and keep an eye on status in the Locals panel. It changes only when Python runs an assignment. The output changes only when Python runs a print instruction. Move backward once or twice to see both states return to an earlier point.

The variable does not automatically keep a history of its old values. It refers to the most recently assigned value.

This is another reason that reading code from top to bottom matters. The value of a variable depends on which assignments Python has already carried out.

What will this program print?

score = 5
print(score)
score = 8
print(score)

Assignment is an action

In mathematics, an equals sign describes equality. In Python assignment, it performs an action.

color = "blue"
color = "green"

Python is not claiming that blue and green are equal. It first assigns one value, then assigns another.

Later, you will learn how Python asks whether two values are equal. That uses two equals signs: ==. For now, remember that one equals sign assigns a value.

Add one more change

The starter program prints two stages:

waiting
still waiting

Under the existing code:

  1. Assign the "ready" to status.

  2. Print status again.

The complete output must be:

waiting
still waiting
ready

Use the same variable for all three stages. Do not create status2 or print the word ready directly.

If the final line still says still waiting, check whether the new assignment appears before the final print instruction.

Task

Add a third stage to the starter program. "ready" to the existing status , then print status again.

The complete output must be:

waiting
still waiting
ready

After adding the third stage, press Step in the editor toolbar. Watch status change from "waiting" to "still waiting" and finally to "ready" in the Locals panel, while each printed line appears at the matching moment.