All lessons

Hello, Python · step 2 of 22

Declaring variables

8 minGive a value a name so you can use it again later.

A variable is a labelled box

You store a value in a variable so you can name it, reuse it and change it later.

score = 10
name = "Ada"

The = sign means "put this value in this box" — it is not a question. Using a variable that does not exist yet gives a NameError.

Variables can change

score = 10
score = score + 5   # the right side runs first, then goes back in the box
print(score)        # 15

That is the whole trick of programming: store a value, change it, use it again.

Naming rules

Letters, numbers and underscores only. A name cannot start with a number, cannot contain a space, and Python cares about capitals — total and Total are two different variables. Python code conventionally uses snake_case, like tip_amount.

Remember this

  • = stores a value under a name
  • A variable can be reassigned at any time
  • Names are case sensitive and use snake_case

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What does total = 5 do?

  2. 2. After x = 3 and then x = x + 2, what is x?

  3. 3. Which name is valid in Python?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

Create a variable named `language` holding the string `"Python"`, then print it.

practice_1.py
2

Practice 2

Store 10 in a variable called `points`, then change it to 25 and print it.

practice_2.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.