What is a variable?
A variable is a named container for data. It has a name and a value. In the example below, sweets is the variable name and 8 is its value:
sweets = 8
print(sweets)
Variables let programs remember information and change it over time.
Naming rules & basics
- Names can’t include spaces and must begin with a letter or underscore.
- Assign a value before you use a variable.
- Names are case sensitive:
sweets≠Sweets. - Print a variable by using its name (no quotes) to show its current value.
Values can change as the program runs:
sweets = 8
print(sweets) # Outputs: 8
sweets = 7
print(sweets) # Now outputs: 7
Task 1 – Age & Pets
Create a variable named age with your age and print it. On the next line, create a variable called pets with how many pets you have and print it.
Example solution:
age = 14
print(age)
pets = 2
print(pets)
Variables with strings
A string is text (characters). Use quotes when assigning strings:
pokemon = "Pikachu"
print(pokemon)
Numbers and variable names don’t use quotes. A variable holds one value at a time, but you can reassign it later.
Task 2 – Superhero & Colour
Create superhero with the name of a superhero and colour with an associated colour. Print both.
Example solutions:
superhero = "Spider-Man"
print(superhero)
colour = "Red"
print(colour)