← Python lessons

Variables

A variable is a name you assign to a value using =. You can then use that name to refer to the value later.

Creating a variable

score = 10
name = "Alice"
is_ready = True

Put the variable name on the left of = and the value on the right. You do not write a type declaration. The value already has a type: 12 is a number, "12" is text, and True is a Boolean value. Assigning a value does not convert it to another type.

Using a variable

Once a value is stored, use the name anywhere you would use the value:

score = 10
bonus = 5
total = score + bonus
print(total)

Changing a variable

A variable can be reassigned at any time. The name always holds whatever you last stored in it:

score = 10
score = score + 5
print(score)

score = score + 5 reads the old value (10), adds 5, and stores 15 back under the same name.

Naming rules

  • For these exercises, use lowercase letters, digits and underscores, such as total_points or roll_2.
  • Start with a letter or underscore, not a digit.
  • Names are case-sensitive: score and Score are different names.
  • Do not use a Python keyword such as if, for or return as a variable name.

Case-sensitivity catches people out. These are two separate variables:

score = 10
Score = 99
print(score)
print(Score)

See also: Data types and operations, String Formatting.

Your turn

Add two lines: store score + bonus in a new variable called total, then print it.

score = 12
bonus = 3
# add two lines: make a total variable, then print it

Expected output

15

Practise this in the free Python course, where every exercise checks your code instantly.