Skip to main content

Lesson 1.2: Create, Set, and Change Variables

A variable is a named place where a program stores a value. The stored value is part of the program's current state. State can change while the program runs.

Use a name that tells what the value means. score, attempts, and playerName are clearer than x when those are the facts being stored.

The set score to 0 block performs an assignment. It stores 0 in score, replacing any earlier value. A change score by 1 block reads the old number, adds 1, and assigns the new number back to the same variable.

Reading a variable does not change it. Printing score only sends its current value to the output.

Trace the state

Create a variable named score. Set it to 5, change it by 2, and print it. Predict the final value before running.

Add another change of -1. Use Step and watch the variables panel after each assignment. Record the sequence of values, not just the final answer. Then move the print block earlier and explain why the output changes.

Loading the block workspace...

Ready to move on?

Only mark complete if you genuinely understand the material. Your progress will be saved in this browser.

Stuck on this lesson?

Ask about anything on this page. It can see which lesson you have open and which part you are reading.