Variables
A variable is a name tag stuck onto a value. Create one with = (read it as "gets"):
food = "pizza" slices = 3
Use the name instead of the value. You can also point the tag at a new value. The right side is worked out first:
slices = slices + 2 # take 3, add 2, store 5
+ adds numbers; - subtracts them. To print several values on one line, separate them with commas: print("Slices left:", slices) adds a space between them.
slices box change from 3 to 5 when the update line runs.See it run
slices = 3 saved = slices slices = slices + 2 print(slices, saved)
Watch the Variables box: each name appears when its line runs.
Practice variables
Exercise 1
- Create
foodholding your favourite food (any text). - Create
slicesholding3. - On a new line, add 2 to
slicesusingslicesitself (so it becomes 5). - Print
food, then printslices.
Exercise 2
A library has available = 12 books. Three are borrowed. Update available using its old value, then print 9.
Exercise 3
A concert starts with tickets = 40. Sell 6, then receive 2 returns. Update tickets in that order using its current value each time. Print Tickets left: 36 with print's comma-separated arguments.
Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.