Variables

Topic 1 of 5 in Values and variables6 min readBeginnerFree course

Overview

A variable stores a value under a name so you can use it later. Variables are how programs remember things: a score, a user’s name, a running total. They’re the first building block of every program.

Creating variables

Python
name = "Asha"
age = 29
height = 1.68
is_member = True

The = sign is assignment, not “equals” in the maths sense. It means: take the value on the right and attach the name on the left to it. Then you use the name instead of the value:

Python
print(name, "is", age)            # Asha is 29
print("Next year:", age + 1)      # Next year: 30

Names are attached to values

It helps to picture variables correctly from the start. A Python variable isn’t a box that holds a value; it’s a label attached to a value:

Variables are names attached to values. The names score and total both point to the same int object 42, and the name name points to the str object ‘Asha’. Code: score = 42, total = score, name = “Asha” — the = sign attaches a name; it does not copy.

Python
score = 42
total = score     # total now refers to the same 42

For numbers and text this distinction rarely matters, because they can’t be changed in place. It becomes important with lists (Lists), where two names attached to the same list both see changes to it.

Reassigning

Assign again and the name moves to the new value:

Python
mood = "tired"
mood = "happy"
print(mood)     # happy

The right-hand side is evaluated first, so a variable can use its own old value:

Python
score = 10
score = score + 5     # 15

Augmented assignment

That pattern is so common there’s a shortcut:

Python
score += 5      # score = score + 5
lives -= 1      # lives = lives - 1
price *= 1.2    # price = price * 1.2
total /= 2      # total = total / 2

Naming rules and style

Rules (Python enforces them):

  • letters, digits and underscores only: total_price, item2;
  • can’t start with a digit: 2nd_place is an error;
  • case-sensitive: score and Score are different;
  • can’t be a keyword — if, for, class, True, def, return and the other words Python reserves.

Style (the Python convention, from the style guide PEP 8):

  • snake_case: lowercase words joined by underscores — hotel_per_night, not hotelPerNight;
  • descriptive: nights not n, food_per_day not fpd. Short names are fine for tiny loops (i) and well-known maths (x, y);
  • UPPER_CASE for constants that shouldn’t change: VAT_RATE = 0.2.

Avoid reusing names of built-in functions such as list, str, sum or print — sum = 10 works, but then the sum() function is hidden for the rest of your program.

Several at once

Python
x, y, z = 1, 2, 3        # assign several names
a = b = 0                # the same value to several names
a, b = b, a              # swap two variables

The swap works because Python evaluates the whole right-hand side (b, a) first, then assigns.

Dynamic typing

Every value has a type — int for whole numbers, float for decimals, str for text, bool for True/False. You don’t declare types; Python works them out:

Python
>>> type(29)
<class 'int'>
>>> type("Asha")
<class 'str'>
>>> type(1.68)
<class 'float'>

A variable can even be reassigned to a value of a different type. Python allows it, but doing it on purpose usually makes code confusing — keep each variable to one kind of value.

Using a variable before creating it

Python
print(total)
Text
NameError: name 'total' is not defined

A variable exists only after its assignment has run. Check for typos and make sure the assignment comes first.

Good names are half of readable code. If you have to add a comment to explain what a variable holds, try renaming it instead.

Exercise

A trip budget

Write a program for a weekend trip. Create variables for the cost of the train ticket (45), the hotel per night (80), the number of nights (2) and a daily food budget (30). Calculate the total cost of the trip (food is per day, and the trip lasts one day longer than the number of nights). Then the hotel announces a 10 USD discount per night — update the hotel price using an augmented assignment and recalculate. Print both totals with labels, and finally swap two variables a and b in one line.

Python
# 1. Variables for the trip

# 2. Total cost (days = nights + 1)

# 3. Hotel discount of 10 per night, recalculate

# 4. Swap a and b in one line
a = "left"
b = "right"

Summary

  • name = value creates a variable — a name attached to a value — and reassigning moves the name to a new value.
  • Use descriptive snake_case names: letters, digits and underscores, not starting with a digit.
  • Augmented assignment updates a variable: score += 10 means score = score + 10.
  • Several names can refer to the same value; a, b = b, a swaps two variables.
  • Python is dynamically typed: a variable can hold any type, and type(x) tells you which.