Browse Python Topics ▼
Pick a Web Framework

Variables

📂 Variables & Data Types 📘 Lesson 6 of 57

Master Python variables, memory references, assignment mechanics, naming standards, and augmented operators through clear visual mental models.

In everyday life, we use names to refer to things: people, places, phone numbers, and addresses. If you had to memorize the GPS coordinates of your favorite restaurant every time you wanted to eat, you would quickly become exhausted. Instead, you give that location a simple name: “Home” or “The Coffee Shop”.

In programming, variables serve the exact same purpose. A variable is a human-friendly name that refers to a piece of data stored in your computer’s memory.


The Mental Model: Sticky Notes, Not Boxes

In traditional programming languages like C or Java, instructors often teach that a variable is a “box that holds a value”.

In Python, that box analogy is misleading. The most accurate mental model for Python is the Sticky Note model:

  1. When you write age = 25, Python creates an integer object 25 somewhere in your computer’s RAM.
  2. It then writes the name "age" on a sticky note and slaps that note onto the number 25.
  3. The single equals sign (=) is the assignment operator. It binds the name on the left to the value on the right.
       Assignment: score = 100

       +--------------+
       | Name Tag:    |
       |  "score"     |----binds to---->  [ Integer Object: 100 ]
       +--------------+                    (Residing in RAM)

Look at what happens when you assign one variable to another:

x = 10
y = x

Python does not create a second copy of the number 10. Instead, it creates a second sticky note labeled "y" and attaches it to the exact same number 10 in memory:

       x -----\
               +---> [ Integer: 10 ]
       y -----/

If you later change x:

x = 20

Python creates a new object 20 and moves the "x" sticky note over to it. The "y" note stays firmly attached to 10:

x = 10
y = x
x = 20

print("x is:", x)  # 20
print("y is:", y)  # 10

You can even verify this using Python’s built-in id() function, which reveals the unique memory address of an object:

score_a = 500
score_b = score_a

# Both variables point to the exact same memory address!
print(id(score_a) == id(score_b))  # True

Assignment and Reassignment

The = operator in programming is very different from the = sign in algebra:

  • In math, $x = y$ states that $x$ and $y$ are eternally balanced and equal.
  • In programming, x = y is an active command: “Evaluate whatever is on the right-hand side first, and assign that result to the variable on the left.”

Because Python reads from right to left, you can update a variable using its own existing value:

player_score = 100

# Read current score (100), add 25 to get 125, then reassign to player_score
player_score = player_score + 25

print("Updated Score:", player_score)  # 125

Augmented Assignment Operators (Shortcuts)

Because updating a variable by adding, subtracting, or multiplying is so common, Python provides convenient shortcuts called augmented assignment operators:

Long SyntaxAugmented ShortcutWhat It Does
count = count + 1count += 1Add and reassign
health = health - 10health -= 10Subtract and reassign
price = price * 2price *= 2Multiply and reassign
total = total / 4total /= 4Divide and reassign
lives = 3
lives -= 1
print("Remaining lives:", lives)  # 2

Multiple Assignment and Idiomatic Swapping

Python allows you to define multiple variables simultaneously on a single line:

# Assign distinct values to distinct variables
width, height, depth = 100, 200, 50

print(f"Dimensions: {width} x {height} x {depth}")

You can also assign the same initial value across multiple names:

# All three players start with 0 points
player_1 = player_2 = player_3 = 0

Swapping Two Variables

In almost every other language, swapping the values of two variables requires creating a temporary third variable:

# The cumbersome, old-fashioned way:
temp = a
a = b
b = temp

In Python, you can swap values in a single, elegant statement using tuple packing:

a = "Coffee"
b = "Tea"

# The Pythonic Swap:
a, b = b, a

print("a is now:", a)  # Tea
print("b is now:", b)  # Coffee

Python enforces strict grammatical rules on what characters you can use in a variable name:

  1. Can only contain: Letters (a-z, A-Z), numbers (0-9), and underscores (_).
  2. Must begin with: A letter or an underscore. It can never begin with a number.
  3. No spaces allowed: Use underscores to separate words.
  4. No special characters: Characters like @, $, %, -, !, or . will trigger a SyntaxError.
  5. Cannot use reserved keywords: You cannot name a variable after Python’s reserved language keywords (such as if, def, class, import, while, for, return).
# VALID variable names:
user_age = 21
_system_status = "OK"
player1_score = 950
total_price_usd = 49.99

# INVALID variable names (will crash with SyntaxError):
# 1st_player = "Alex"    <- Error: Cannot begin with a number
# user-age = 21          <- Error: Hyphen is treated as a minus operator
# total price = 50       <- Error: Cannot have spaces
# class = "Math"         <- Error: 'class' is a reserved Python keyword

PEP 8 Naming Conventions: Best Practices

Just because a variable name is legal does not mean it is good code. Python engineers follow the official PEP 8 style guide for readability:

1. Use Descriptive Names

Code is read far more often than it is written. Avoid single-letter variable names outside of quick math loops:

# Cryptic and confusing:
d = 86400
u = "admin@site.com"
t = p * q

# Self-documenting and professional:
seconds_in_day = 86400
user_email = "admin@site.com"
total_price = unit_price * quantity

2. Follow the snake_case Standard

In Python, standard variables and functions are always written in snake_case—all lowercase letters, with words separated by underscores:

  • Good: account_balance, is_user_logged_in, customer_shipping_address
  • Discouraged in Python: accountBalance (camelCase is for JavaScript/Java), AccountBalance (PascalCase is reserved for classes)

Dynamic Typing: Variables Can Change Types

In statically typed languages like C++ or Java, when you declare int age = 25, that variable is permanently locked to integers. Trying to store "twenty-five" later results in a compilation error.

Python is dynamically typed. A variable is simply a name tag, and it can point to any data type at any moment during execution:

# Starts as an integer
data = 42
print(data, type(data))  # 42 <class 'int'>

# Rebound to text (string)
data = "Now I am text!"
print(data, type(data))  # Now I am text! <class 'str'>

While Python permits this flexibility, experienced engineers avoid changing the underlying type of a variable in the middle of a program because it confuses teammates and leads to subtle bugs.


Summary Checklist

  • Mental Model: Variables are named sticky notes pointing to objects in memory, not physical boxes.
  • Assignment: = evaluates the right side first and assigns the result to the left side.
  • Augmented Shortcuts: Use +=, -=, *=, and /= for clean updates.
  • Swapping: Use a, b = b, a for instant, idiomatic variable swapping.
  • Naming: Always use descriptive snake_case names and avoid reserved keywords.

Now that you know how to name and store data, continue to types to discover the different kinds of data Python can store—including integers, floating-point decimals, text strings, and booleans.

Test your understanding of Variables

Quick interactive practice questions with instant feedback.

Take Quiz →