Python Basics · Lesson 2 of 12

Variables

A variable is a name for a value. Once a value has a name, you can use it as often as you like.

score = 10
print(score)

The = sign puts the value on the right into the name on the left. Read it as "becomes", not "equals". Python creates the variable the first time you assign to it. There is no special keyword.

Assign again to change it:

score = 10
score = 15
print(score)   # 15

A variable can hold any kind of value: a number, a string, and other kinds you will meet later.

city = "Lisbon"
temperature = 21.5

Names

  • Names can contain letters, digits and underscores, and cannot start with a digit.
  • Names are case sensitive: score and Score are different variables.
  • When a name has several words, Python programmers join them with underscores: high_score, first_name. This style is called snake_case.

Choose names that say what the value means. price is better than p.

Using a variable that does not exist

If you misspell a name, Python stops with a NameError and tells you the line. It is one of the most common errors, and one of the easiest to fix.

Your Task

  1. Create a variable city that holds the name of a city as a string.
  2. Create a variable visitors that starts at 100.
  3. On a later line, change visitors to 250.
  4. Print both with one print, the city first.
  • city holds a string
  • visitors starts at 100
  • visitors is changed to 250 afterwards
  • One print shows the city and then 250