👋 Getting Started, lesson 4 of 5
Variables
Store values under a name, reuse them and change them.
10 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
A variable is a name that refers to a value, like a
label on a box. You create one with =, which means
"store the value on the right under the name on the
left".
After that, use the name anywhere you would use the value. Note there are no quotes around a variable name.
Creating variables
Change name and age to your own details and run it again.
Variables can change. Assigning again replaces the
old value. You can even use a variable's current value
to compute its new one: score = score + 10 means
"take the current score, add 10, store the result
back in score".
Updating a variable
Add a line score = score - 5 at the end, then print the score again.
What does this print?
Travel plans
- Set
cityto the name of any city (as text, in quotes). - Set
yearto the number 2030 (no quotes). - Run it to see your plans printed.
Naming rules. Names can contain letters, digits and
underscores, but can't start with a digit or contain
spaces. They are case-sensitive (Age and age are
different). Python style is snake_case: lowercase
words joined by underscores, like high_score.
Every value also has a type. The four basic ones:
str (text), int (whole number), float
(decimal number) and bool (True or False).
Checking types
Notice that "7" in quotes is a str, not an int!
Which of these is a valid variable name?
2nd_place
my-score
high_score
first name
Piggy bank
coins starts at 10. Update it in two steps:
- Add 5 coins.
- Then double the coins.
At the end coins should be 30. Update the
variable itself, don't just print 30.