← Intro to programming with Python

Changing variables and naming them well

Update a value, use += and follow the naming rules.

Start this lesson

Variables can change, which is why they are called variables. Storing a new value replaces the old one. A line like steps = steps + 100 looks odd in math, but in Python the RIGHT side is worked out first (take the current steps, add 100) and then the answer is stored back under the name steps. Because this is so common, there is a shortcut: steps += 100. Names can use letters, digits and underscores, but cannot start with a digit or contain spaces.

coins = 5
coins = coins + 3   # now 8
coins += 2          # now 10
coins -= 4          # now 6
print(coins)

Each line updates the same jar. The program shows 6. There are also *= and /= for multiplying and dividing.

Common mistake: Python is case-sensitive, so Score and score are two different variables. Pick one spelling and keep it.

Names with spaces like my score give a SyntaxError. Use an underscore: my_score.

Avoid using names Python already uses, like print or list, as variable names. It can break those tools later in your program.