Computer Programming 1 (Python) • Python Fundamentals

Variables & Naming Conventions — I can create variables using Python naming conventions and explain assignment at my level.

Learn how Python stores and labels data so your programs can remember, reuse, and transform information.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 8 figures

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

Programmers referenced raw memory addresses (like 0x3A) by number. There were no named variables — only numbered slots in memory.

1957 • Fortran Introduces Variables

IBM's Fortran became the first widely used language that let programmers assign descriptive names to data, replacing cryptic memory addresses with readable labels like SPEED and MASS.

1972 • C Language & Typed Variables

The C programming language required programmers to declare a variable's type (int, float, char) before using it, enforcing strict rules about what data a variable could hold.

1991 • Python Is Born

Guido van Rossum released Python, which introduced dynamic typing. Variables no longer needed explicit type declarations — Python figures out the type automatically when you assign a value.

2020s • PEP 8 & Modern Conventions

Python's PEP 8 style guide is now the gold standard for naming conventions, encouraging snake_case variable names and readable, self-documenting code used by millions of developers worldwide.

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.

1

Assignment with =

The assignment operator (=) 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."
2

Dynamic Typing

Python uses dynamic typing, meaning you never declare a variable's type. Python infers it from the value you assign. Write x = 5 and Python knows x is an integer.
3

Naming Rules

Variable names must start with a letter or underscore, contain only letters, digits, and underscores, and cannot be a Python reserved keyword (like if, for, or class). Names are case-sensitive.
4

Snake_case Convention

Python's PEP 8 style guide recommends snake_case for variable names: all lowercase letters with words separated by underscores, such as player_health or total_score.
5

Reassignment

Variables can be reassigned at any time. Writing 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

Think of a variable like a labeled sticky note stuck onto a value. The sticky note has a name (like 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.

Python Variable Assignment in MemoryVARIABLE NAMESVALUE OBJECTS IN MEMORYplayer_score100intuser_name"Ada"stris_activeTrueboolThe = operator creates an arrow (reference) from the name on the left to the value object on the right.
Each colored box on the left is a variable name. The arrow represents the assignment operator (=), 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

  1. Evaluate the right side — Python calculates the expression on the right side of the = to produce a value object.
  2. 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.
  3. 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

variablename=expressionvariable_name = expression

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

x,y,z=10,20,30x, y, z = 10, 20, 30

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

score+=10→score=score+10score += 10 → score = score + 10

The += operator is shorthand for adding a value to the current variable and reassigning the result. Other augmented operators include -=, *=, and /=.

⚠

Common Misconception

The statement 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).

Python Variable Naming: Valid vs. Invalid✓ VALID NAMESplayer_scoresnake_case ✓_private_varstarts with _ ✓total_items_2digits OK (not first) ✓xsingle letter ✓MAX_SPEEDconstant convention ✓is_game_overdescriptive boolean ✓Conventions (PEP 8):• Use snake_case for variables• Use UPPER_CASE for constants• Be descriptive but concise• Avoid single letters except loops• Use CamelCase only for classes✗ INVALID NAMES2faststarts with digit ✗player-scorehyphen not allowed ✗my variablespaces not allowed ✗classreserved keyword ✗total$special character ✗forreserved keyword ✗Style Warnings (bad but legal):playerScorecamelCase — not Pythonicameaningless namellooks like 1 (ambiguous)datatoo vague
The left column (green border) shows valid and well-named variables following PEP 8. The right column (red border) shows names that will cause errors, along with names in amber that are technically legal but considered poor practice.
RuleValid ExampleInvalid ExampleWhy It Matters
Must start with letter or _score, _count9livesPython would confuse a leading digit with a number literal
Only letters, digits, underscoresitem_2item-2, item@2Hyphens and special characters are operators or syntax in Python
Cannot be a reserved keywordmy_classclass, if, returnKeywords have special meaning; using them as names would create ambiguity
Case-sensitiveScore ≠ scoreNot an error, but confusingMixing 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. 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. 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_score is reassigned from 0 to 25.
    player_score += 25 print(player_score) # Output: 25
  3. 3

    Step 3 — Apply a Bonus Multiplier

    The player picks up a bonus multiplier. We create a new variable bonus_multiplier and multiply the score. Notice we define a constant BONUS_MULTIPLIER in UPPER_CASE to signal it should not be changed.
    BONUS_MULTIPLIER = 2 player_score = player_score * BONUS_MULTIPLIER print(player_score) # Output: 50
  4. 4

    Step 4 — End the Game (Reassignment of Boolean)

    The game ends. We reassign is_game_active from True to False. The variable's type remains bool because we assigned another boolean.
    is_game_active = False
  5. 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

Every variable name in this example describes exactly what it holds: 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 NameBetter NameWhy It's Better
xtemperature_celsiusTells the reader what the value represents and its unit
nnum_studentsEliminates guessing; clearly a count of students
flagis_logged_inBooleans starting with is_, has_, or can_ read like yes/no questions
datastudent_gradesSpecifies exactly what kind of data is stored
temptemporary_file_pathAvoids ambiguity — does temp mean temperature or temporary?

Improving variable names for readability

✦

KEY TAKEAWAY

Imagine you are writing a text message that someone will read six months from now with no context. If you write 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 TodayWhere It LeadsWhy It Matters
Simple assignment (x = 5)Data structures — lists, dictionaries, tuplesVariables can point to complex collections, not just single values
Dynamic typingType hints and type checking (mypy)As programs grow, optional type annotations help catch bugs early
Naming conventionsScope & namespacesVariables inside functions are local; understanding naming helps with debugging scope issues
ReassignmentMutability vs. immutabilitySome objects (like lists) can be changed in place; others (like strings) cannot
UPPER_CASE constantsOOP class attributesConstants 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

In Python, the = 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
In mathematics, = 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

What will the following code print? Trace through each line and show the value of total after each assignment. total = 10 total += 5 total *= 2 print(total)
Show answer
After line 1, 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

Identify all the naming errors and style violations in the following code. For each issue, state whether it is a hard error (Python will crash) or a style violation (legal but against PEP 8), and provide the corrected name. 1st_place = "Alice" player-score = 95 Class = "Biology" playerName = "Bob" for = 10
Show answer
Line 1: 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

You are building a tip calculator. The user provides the meal cost and tip percentage. Write Python code that creates well-named variables for: (1) the meal cost ($48.50), (2) the tip percentage (20%), (3) the calculated tip amount, (4) the total bill. Use proper PEP 8 naming conventions and include a print statement showing the total.
Show answer
A well-written solution follows snake_case naming and uses descriptive names: 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

Consider this code: 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
The output is 5. Here's the trace: Line 1 creates the integer object 5 and binds the name 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.

Varsity Tutors • Computer Programming 1 (Python) • Variables & Naming Conventions