1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Updating values

Changing a variable based on itself is so common that it has shortcuts:

score = 10
score += 5    # same as score = score + 5  -> 15
score -= 3    # 12
score *= 2    # 24
score /= 4    # 6.0

Order of operations is the usual maths order: **, then * / // %, then + -. Brackets go first.

Step through it with Next and watch the score box: 10, 15, 12, 24, then 6.0 (/= always gives a float).

See it run

steps = 10
steps += 5
steps = steps + 5
steps *= 2

Each row of the table is one change to steps. Read the rows top to bottom.

Practice updating values

Exercise 1

Start with balance = 100. Deposit 50 with +=, withdraw 30 with -=, then double it with *=. It should end at 240.

Exercise 2

A game character starts with xp = 0. - They win 3 battles worth 40 xp each: add it in one line with += and *. - A trap costs 25 xp (-=). - A bonus weekend triples what is left (*=). xp should end at 285.

Exercise 3

This cafe bill in the code editor below has a bug. It should be the food (2 coffees at 3.5, 1 cake at 4.25) plus a 10% tip, so the whole food cost gets multiplied by 1.1.

  • Fix the line with brackets so bill is 12.375.
  • Then split it between 3 friends with /= (each pays 4.125).

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest