CodeStride
Getting Started

Variables in Python

Topic 2 of 58 · 7 minFree lesson

A variable is a name for a value. Think of a box with a label on it. The label is the name, and the thing inside is the value.

Variables let your program remember things, like a player's score or a user's name. You can use the value again and again just by writing the name.

Making a variable

Write a name, then =, then the value. Python stores the value under that name.

Example 1
name = "Ada"age = 36print(name)print(age)
Ada36

In Python, = means "store this value". It does not mean "equals" like in math class. Read age = 36 as "age gets 36".

Changing a value

You can put a new value in the box at any time. Python keeps only the latest one.

Example 2
score = 10score = 15print(score)
15

Using variables together

Variables can be used to make new values. Here * means multiply. You'll see all the math signs in the next topic.

Example 3
price = 4quantity = 3total = price * quantityprint(total)
12

To print a label and a value together, separate them with a comma. Python adds a space between them.

Example 4
city = "Lisbon"print("I live in", city)
I live in Lisbon

Naming rules

Variable names follow a few rules:

  • Use letters, numbers and underscores _ only.
  • Don't start with a number. score1 works, but 1score does not.
  • No spaces. Use an underscore instead, like first_name.
  • Capital letters matter. Score and score are two different variables.
Common mistakeUsing a variable before you create it. Python reads from top to bottom, so it hasn't seen the name yet.
Example 5
print(points)points = 5
NameError: name 'points' is not defined

Create the variable first, then use it.

TipPick names that say what's inside. total_price is much easier to understand than tp or x.

Try it yourself

Run the code in the editor and answer 8 practice questions on variables. It's free, you only need an account.