SECTION 1
Historical Context & Motivation
Before modern programming languages existed, the earliest computers were programmed by physically rewiring circuits or toggling switches that represented raw numbers stored in memory. Programmers had to remember that memory location 0x3A held the player's score and 0x3B held the number of lives remaining — a nightmare to manage. The idea of giving human-readable names to data emerged as one of the most important breakthroughs in the history of software, transforming programming from a specialist's puzzle into an activity that millions of people can learn.
A variable is simply a name that refers to a piece of data stored in your computer's memory. Instead of saying "put the number 42 into memory address 0x3A," you can write score = 42. This concept did not appear overnight; it evolved through decades of innovation in computer science.
1940s • Machine Code Era
1957 • Fortran Introduces Variables
SPEED and MASS.1972 • C Language & Typed Variables
1991 • Python Is Born
2020s • PEP 8 & Modern Conventions
The central question this lesson addresses is: How do we create, name, and assign values to variables in Python so that our code is both functional and easy to read? Understanding this foundation is essential before tackling any other programming concept.
SECTION 2
Core Principles & Definitions
Before writing any code, you need to understand four foundational ideas that govern how variables work in Python. These principles will guide every program you ever write, from a simple calculator to a complex web application.
Assignment with =
=) stores a value on the right side into the variable name on the left side. It does not mean "equals" in the math sense — it means "make this name point to this value."Dynamic Typing
x = 5 and Python knows x is an integer.Naming Rules
if, for, or class). Names are case-sensitive.Snake_case Convention
player_health or total_score.Reassignment
x = 10 and later x = 20 simply moves the label x from the old value to the new one. The old value may be garbage-collected if nothing else references it.KEY TAKEAWAY
player_score), and it is stuck onto a value (like 100). You can peel the note off and stick it onto a different value any time — that is reassignment. The = sign is the act of sticking the note, not a statement that two things are equal.SECTION 3
Visual Explanation — How Assignment Works in Memory
The diagram below illustrates what happens in memory when you write three assignment statements. Each variable name is a label that points to a value object stored somewhere in your computer's memory. Notice how the arrow goes from the name to the value — the name is not the value itself, it simply references it.
=), and the box on the right is the value object stored in memory. Python automatically detects the type (int, str, bool) based on the assigned value.When you write player_score = 100, Python creates the integer object 100 in memory and then attaches the label player_score to it. If you later write player_score = 200, Python does not change the 100 — it creates a new object 200 and moves the label to point at it instead. This is why we say variables in Python are names bound to objects, not containers that hold values.
SECTION 4
How Assignment & Typing Work Under the Hood
Python does not require you to declare types like some other languages. In C++ or Java, you might write int score = 100; — explicitly telling the compiler the type. In Python, you simply write score = 100, and the interpreter figures out the type at runtime. This is called dynamic typing. Let's break down the exact steps Python follows when it encounters an assignment statement.
The Assignment Process
- Evaluate the right side — Python calculates the expression on the right side of the
=to produce a value object. - Create (or find) the object in memory — If the value doesn't already exist in memory, Python creates a new object. Small integers (−5 to 256) are cached for efficiency.
- Bind the name — Python attaches the variable name on the left side to the newly created object, like placing a label on it.
The General Form of Assignment
ASSIGNMENT SYNTAX
variable_name — a valid Python identifier following naming rules; = — the assignment operator (not mathematical equality); expression — any value, calculation, or function call that produces a result.
MULTIPLE ASSIGNMENT
Python allows you to assign multiple variables in a single line. Each name on the left is paired with the corresponding value on the right. Here, x gets 10, y gets 20, and z gets 30.
AUGMENTED ASSIGNMENT
The += operator is shorthand for adding a value to the current variable and reassigning the result. Other augmented operators include -=, *=, and /=.
Common Misconception
x = x + 1 is not a mathematical contradiction. In Python, it means "take the current value of x, add 1, and store the result back into x." The right side is evaluated first, producing a new value, and then the name x is reassigned to that new value.SECTION 5
Naming Rules & Conventions — A Detailed Breakdown
Choosing good variable names is one of the most underrated skills in programming. A well-named variable makes your code self-documenting — anyone reading it can understand what is happening without additional comments. Python enforces certain hard rules (break them and your code will crash) and strongly recommends certain soft conventions (break them and other programmers will be confused).
| Rule | Valid Example | Invalid Example | Why It Matters |
|---|---|---|---|
| Must start with letter or _ | score, _count | 9lives | Python would confuse a leading digit with a number literal |
| Only letters, digits, underscores | item_2 | item-2, item@2 | Hyphens and special characters are operators or syntax in Python |
| Cannot be a reserved keyword | my_class | class, if, return | Keywords have special meaning; using them as names would create ambiguity |
| Case-sensitive | Score ≠ score | Not an error, but confusing | Mixing cases makes it easy to introduce hard-to-find bugs |
Python's hard rules for variable naming
SECTION 6
Worked Example — Building a Score Tracker
Let's walk through a realistic example. Imagine you're building a simple game score tracker. We will create variables, update them, and observe how assignment and naming conventions work together in practice.
Game Score Tracker
- 1
Step 1 — Create Initial Variables
We start by defining the player's name, initial score, and a boolean indicating whether the game is still running. Notice we use snake_case for all variable names.player_name = "Alex" player_score = 0 is_game_active = True - 2
Step 2 — Award Points (Reassignment)
The player earns 25 points. We use the augmented assignment operator+=to add points to the existing score. After this line,player_scoreis reassigned from 0 to 25.player_score += 25 print(player_score) # Output: 25 - 3
Step 3 — Apply a Bonus Multiplier
The player picks up a bonus multiplier. We create a new variablebonus_multiplierand multiply the score. Notice we define a constantBONUS_MULTIPLIERin UPPER_CASE to signal it should not be changed.BONUS_MULTIPLIER = 2 player_score = player_score * BONUS_MULTIPLIER print(player_score) # Output: 50 - 4
Step 4 — End the Game (Reassignment of Boolean)
The game ends. We reassignis_game_activefromTruetoFalse. The variable's type remainsboolbecause we assigned another boolean.is_game_active = False - 5
Step 5 — Display Final Results
We use an f-string to display the final output, referencing our variables by name. Because we chose descriptive names, the print statement reads almost like English.print(f"{player_name} scored {player_score} points!") # Output: Alex scored 50 points!
Notice the Pattern
player_name holds the player's name, player_score holds the player's score, and is_game_active tells you whether the game is active. This is the core of good naming — your code should explain itself.SECTION 7
Good vs. Bad Naming — Comparison & Impact
Naming conventions might seem like a minor detail, but they have a massive impact on whether code can be understood, maintained, and debugged. Professional developers spend more time reading code than writing it, so good names save everyone time and prevent costly mistakes. The table below compares different naming approaches.
| Poor Name | Better Name | Why It's Better |
|---|---|---|
x | temperature_celsius | Tells the reader what the value represents and its unit |
n | num_students | Eliminates guessing; clearly a count of students |
flag | is_logged_in | Booleans starting with is_, has_, or can_ read like yes/no questions |
data | student_grades | Specifies exactly what kind of data is stored |
temp | temporary_file_path | Avoids ambiguity — does temp mean temperature or temporary? |
Improving variable names for readability
KEY TAKEAWAY
x = 72, nobody (including future you) knows what 72 means. But room_temperature_f = 72 tells the whole story instantly. Good variable names are a gift to your future self.SECTION 8
Connection to Advanced Concepts
The concepts of variables and naming conventions form the foundation for everything you will encounter as you advance in Python. Understanding how assignment works now will make it much easier to grasp more complex topics later. The table below shows how today's ideas connect to what comes next.
| What You Learned Today | Where It Leads | Why It Matters |
|---|---|---|
Simple assignment (x = 5) | Data structures — lists, dictionaries, tuples | Variables can point to complex collections, not just single values |
| Dynamic typing | Type hints and type checking (mypy) | As programs grow, optional type annotations help catch bugs early |
| Naming conventions | Scope & namespaces | Variables inside functions are local; understanding naming helps with debugging scope issues |
| Reassignment | Mutability vs. immutability | Some objects (like lists) can be changed in place; others (like strings) cannot |
| UPPER_CASE constants | OOP class attributes | Constants evolve into class-level configuration in object-oriented programming |
How today's fundamentals connect to future topics
Think of variables as the first rung on a ladder. Without a solid first rung, you cannot climb higher. Every loop, function, class, and module you will encounter in future lessons relies on the ability to create, name, and assign variables correctly. Mastering this now means you will spend less time debugging naming errors and more time solving interesting problems.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
= operator is called the assignment operator. Explain in your own words why = in Python is different from = in mathematics. Use the "sticky note" analogy from this lesson to support your explanation.Show answer
= asserts that two sides are permanently equal — it's a statement of truth. In Python, = is an action: it takes the value on the right side, creates (or locates) that value in memory, and sticks the variable name (the "sticky note") onto it. That's why x = x + 1 makes perfect sense in Python — you peel the sticky note off the old value, compute a new value, and stick the note on the new one — but would be a contradiction in math.Question 2: BASIC CALCULATION
total after each assignment.
total = 10
total += 5
total *= 2
print(total)Show answer
total is 10. After line 2, total += 5 means total = 10 + 5, so total is 15. After line 3, total *= 2 means total = 15 × 2, so total is 30. The program prints 30. Remember, each augmented assignment evaluates the right side first, then reassigns the result to the variable.Question 3: INTERMEDIATE
1st_place = "Alice"
player-score = 95
Class = "Biology"
playerName = "Bob"
for = 10Show answer
1st_place — hard error, starts with a digit. Fix: first_place. Line 2: player-score — hard error, contains a hyphen (Python interprets it as subtraction). Fix: player_score. Line 3: Class — style violation, not a keyword but CamelCase is reserved for class definitions by convention. Fix: class_name. Line 4: playerName — style violation (camelCase instead of snake_case). Fix: player_name. Line 5: for — hard error, it is a reserved keyword. Fix: for_count or loop_limit.Question 4: APPLIED
Show answer
meal_cost = 48.50
tip_percentage = 0.20
tip_amount = meal_cost * tip_percentage
total_bill = meal_cost + tip_amount
print(f"Total bill: ${total_bill:.2f}")
This outputs Total bill: $58.20. Each variable name clearly communicates its purpose. tip_percentage is stored as a decimal (0.20) rather than 20 so it can be directly multiplied. Notice tip_amount is computed using an expression on the right side of =, demonstrating that the right side is evaluated before assignment.Question 5: CRITICAL THINKING
a = 5
b = a
a = 10
print(b)
Predict what print(b) will output. Then, using the concept that variables are "names bound to objects" (not containers), explain step by step why b does NOT change when a is reassigned. How would this differ if variables were truly "containers" that held values?Show answer
a to it. Line 2 binds the name b to the same object that a currently points to — the integer 5. At this moment, both a and b point to 5. Line 3 creates a new integer object 10 and rebinds a to point to 10, but b still points to 5 — reassigning a does not affect b because they are independent labels. If variables were containers, you might imagine b = a as linking the containers, so changing a would also change b. But Python's name-binding model means each name is independent once assigned.SUMMARY
Lesson Summary
Summary
A variable in Python is a name that references a value stored in memory. The assignment operator (=) evaluates the expression on the right and binds the name on the left to the resulting object — it does not mean mathematical equality. Python uses dynamic typing, so you never need to declare a variable's type; Python infers it from the assigned value. Variables can be freely reassigned to new values, and augmented assignment operators like += provide shortcuts for updating values.
Python's naming rules require that variable names start with a letter or underscore, contain only letters, digits, and underscores, and are not reserved keywords. The PEP 8 style guide recommends snake_case for variable names, UPPER_CASE for constants, and descriptive names that make code self-documenting. Mastering these fundamentals ensures that your programs are not only functional but also readable and maintainable as they grow in complexity.