Variables
Python · Unit 1: First steps
- Free
- Python
- 12 exercises
A variable stores a value under a name. You create it with =: the name on the left, the value on the right.
To use it, write its name without quotes.
name = "Emma"
age = 17
print(name, "is", age)Prints
Emma is 17
To change the value, use = again: the new one replaces the old one.
You can even use the current value to work out the new one.
points = 10
points = 25
print(points)
points = points + 5
print(points)Prints
25 30
Names go in lowercase and use an underscore instead of spaces: my_age.
They can have numbers, but can't start with one, and they take no dashes.
my_age = 17
total_price = 250
print(my_age, total_price)Prints
17 250
b = a copies into b the value that a has at that moment.
After that they're independent: if you change a, b stays the same.
today = 20
yesterday = today
today = 25
print(yesterday, today)Prints
20 25
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
fruit = "apple" print("fruit") print(fruit)2. Put the lines in order
Order the lines to say hello to Emma.
3. Complete the code
Fill in to create the variable the greeting uses.
___ = "Owen" print("Hello,", name)4. Predict the output
What does this code print?
weather = "sunny" print("Today:", weather) weather = "rainy"5. Complete the code
Noah won 5 more points. Fill in so his score goes up.
points = 20 points = ___ + 5 print(points)6. Find the bug
This program should subtract the discount from the price. Which line has the error?
price = 100 discount = 20 total = price + discount print("Total to pay:", total)7. Multiple choice
Which one is a valid variable name in Python?
8. Find the bug
This program should print Sophie's final grade. Which line has the error?
final grade = 9 print("Grade:", final_grade)9. Predict the output
What does this code print?
x = 5 y = x x = 10 print(y)10. Multiple choice
What happens on the last line?
mug = "tea" glass = "coffee" mug = glass11. Find the bug
Jack had 50 and spent 15. The program should print how much he has left. Which line has the error?
money = 50 before = money money = money - 15 print("Left:", before)12. Predict the output
Follow each variable line by line. What does it print?
a = "red" b = "blue" c = a a = b b = c print(a, b)
It opens in your browser. It is free and you do not need an account to start.