Python Basics · Getting Started · lesson 2 of 12
Variables
about 10 minutes · free · runs in your browser
Step 1 of 2
Giving a value a name
A variable is a name attached to a value. You create one with =:
language = "Python"
year = 1991
Read = as "gets", not as "equals". The name goes on the left, the value on the right.
From then on, writing the name gives you back the value.
Python works out the type for you: language holds a string, year holds an integer.
You never declare types up front.
Names follow a few rules: letters, digits and underscores only, and they cannot start with
a digit. By convention Python uses snake_case — lowercase words joined by underscores,
like first_name — rather than firstName.
Your turn: create a variable called city holding the string "Lisbon", and one
called population holding the number 545000.
You start from this, and edit it in the browser:
# Create the two variables below.
Step 2 of 2
Variables can change
The value behind a name can be replaced at any time, which is what makes them variable:
score = 0
score = score + 10
print(score) # 10
The second line looks odd until you read = as "gets". Python works out the right-hand
side first — score + 10, which is 0 + 10 — and then puts the answer back into
score.
Adding to a variable is so common that Python has a shorthand: score += 10 means
exactly score = score + 10. There is a matching -=, *= and /=.
Your turn: total starts at 100. Add 25 to it, then subtract 5, so it ends up as
120. Leave the final value in total.
You start from this, and edit it in the browser:
total = 100
# Add 25, then subtract 5.