Python • Syntax and Core Types

Variable Assignment & snake_case — Assign variables and follow Python naming conventions (snake_case)

Learn how Python stores data in named variables and why snake_case keeps your code clean and readable.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Every program needs a way to remember information. Early computers in the 1940s and 1950s forced programmers to track data by referencing raw memory addresses — cryptic numbers like 0x7FFF — which made code nearly impossible to read or maintain. The idea of a variable, a human-readable name that stands in for a value stored in memory, was one of the most important breakthroughs in the history of programming. It transformed coding from a mechanical exercise into something closer to writing clear instructions in English.

1957 • FORTRAN Introduces Named Variables

IBM's FORTRAN language let programmers use names like SPEED instead of memory addresses, making programs far more readable.

1972 • C Language Popularizes Assignment with =

The C programming language established the = operator for variable assignment, a convention that Python and most modern languages still follow today.

1991 • Python Is Born

Guido van Rossum released Python with a focus on readability. Variables in Python require no type declaration — just pick a name, use =, and assign a value.

2001 • PEP 8 Establishes snake_case

Python Enhancement Proposal 8 (PEP 8) was published as the official style guide, recommending snake_case for variable and function names to maximize readability.

The core question that variable assignment answers is simple but fundamental: how does a program remember and reuse a piece of data? And the naming convention question that snake_case answers is equally practical: how do we name variables so that every programmer on a team can instantly understand what they mean? Together, assignment and naming conventions form the bedrock of writing clear Python code.

SECTION 2

Core Principles & Definitions

Before you write a single line of Python, you need to understand two foundational ideas. First, variable assignment is the act of binding a name to a value so you can refer to that value later. Second, snake_case is the Python community's agreed-upon way of formatting those names: all lowercase letters with words separated by underscores. Let's break this down into core principles.

1

The = Operator Assigns, Not Equals

In Python, = is the assignment operator. It takes the value on the right side and binds it to the name on the left. It does not mean "is equal to" — that's ==.
2

Names Are Labels, Not Containers

A Python variable is a label (or reference) that points to an object in memory. Think of a sticky note on a box, not the box itself. Multiple names can point to the same object.
3

No Type Declaration Needed

Python is dynamically typed. You don't need to declare a variable's type. Writing age = 16 automatically makes age an integer.
4

snake_case Is the Standard

PEP 8 says variable names should be lowercase with underscores: student_grade, not studentGrade (camelCase) or StudentGrade (PascalCase).
5

Naming Rules vs. Naming Conventions

Rules are enforced by Python (e.g., names can't start with a digit). Conventions like snake_case are enforced by the community. Breaking a rule causes an error; breaking a convention causes confusion.
✦

KEY TAKEAWAY

Think of variable assignment like labeling a shelf in your locker. The label math_textbook tells you (and anyone else who opens your locker) exactly what's on that shelf. If you labeled it mt or MathTextbook, it would still work, but it's harder for others to understand at a glance. The = operator is the act of sticking the label onto the shelf, and snake_case is the agreed-upon handwriting style so everyone can read every label.

SECTION 3

Visual Explanation — How Assignment Works in Memory

Variable Assignment in MemoryPython CodeObjects in Memoryplayer_score=100int object100referencesuser_name="Ada"str object"Ada"referencesis_active=Truebool objectTruereferencesComputer Memory (RAM)
Each variable name on the left side of = is a label that references an object stored in memory on the right. The arrow shows the direction of the reference — from the name to the object.

In the diagram above, notice that the variable names (player_score, user_name, is_active) live on the left and are all written in snake_case. Each name points to a distinct object in memory. The key insight is that the variable is not the value itself — it's a reference to where that value lives. If you later write player_score = 200, the name player_score simply detaches from the old integer object and attaches to a new one.

SECTION 4

How Variable Assignment Works Under the Hood

The Assignment Statement Syntax

ASSIGNMENT SYNTAX

variablename=expressionvariable_name = expression

variable_name — a valid identifier following naming rules; = — the assignment operator (binds the name to the result); expression — any value, calculation, or function call that produces a result.

Python evaluates the right side of the = first, creates or finds the resulting object in memory, and then binds the name on the left to that object. This means expressions like total_points = 50 + 25 are perfectly valid — Python computes 75 first, then binds total_points to that result.

Reassignment and Multiple Assignment

Variables can be reassigned at any time. When you write level = 1 and later write level = 2, the name level now points to the integer 2. The old integer 1 isn't destroyed right away, but if nothing else references it, Python's garbage collector will eventually reclaim that memory. Python also supports multiple assignment on a single line: x, y, z = 1, 2, 3 assigns three names simultaneously.

Augmented Assignment Operators

AUGMENTED ASSIGNMENT

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

The += operator is shorthand. Other augmented operators include -=, *=, /=, and //=.

⚠

Common Beginner Mistake

Don't confuse = (assignment) with == (comparison). Writing if score = 100: will cause a SyntaxError because Python sees assignment where it expects a comparison. You need if score == 100: instead.

SECTION 5

Variable Naming Rules & snake_case Convention

Python enforces strict rules about what constitutes a valid variable name, and the community adds conventions on top of those rules. Understanding the difference between the two is essential. A rule will cause Python to throw an error if broken. A convention won't crash your program, but violating it makes your code harder for others (and your future self) to read.

Variable Naming: Rules vs. ConventionsRULES (Enforced by Python)my_var✓ starts with letter_private✓ starts with underscorecount2✓ digits allowed (not first)2fast✗ starts with digitmy-var✗ hyphens not allowedmy var✗ spaces not allowedclass✗ reserved keywordOnly letters, digits, underscores.Must start with letter or underscore.CONVENTIONS (PEP 8 Style)✓ snake_case (recommended)player_scoremax_health_pointsis_game_over✗ camelCase (Java/JS style)playerScoremaxHealthPoints✗ ALLCAPS (constants only)PLAYERSCORE✗ Single letters (unclear)p, x, n(except in short loops or math)
The left panel shows hard rules that Python enforces — violating them causes errors. The right panel shows PEP 8 conventions — snake_case is the preferred style for variables and functions in Python.
Naming StyleExampleWhen to Use in Python
snake_caseplayer_healthVariables, functions, method names
UPPER_SNAKE_CASEMAX_RETRIESConstants (values that never change)
PascalCasePlayerCharacterClass names only
camelCaseplayerHealthAvoid in Python (common in Java/JavaScript)

Python naming conventions by context

SECTION 6

Worked Example — Building a Student Grade Tracker

Let's walk through a realistic scenario: creating variables to track a student's grades. We'll apply both variable assignment and snake_case naming at every step.

Student Grade Tracker

  1. 1

    Step 1 — Assign the student's name

    We need to store the student's first and last name. Following snake_case, we'll use a descriptive name with underscores. The string value goes on the right side of =.
    student_name = "Maria Garcia"
  2. 2

    Step 2 — Assign individual test scores

    Each test score gets its own variable. Notice how snake_case makes it clear which test each score belongs to. We use integers since these are whole-number scores out of 100.
    test_one_score = 88 test_two_score = 95 test_three_score = 78
  3. 3

    Step 3 — Calculate and assign the average

    The right side of = can be an expression. Python evaluates the entire calculation first and then assigns the result to average_score. We use / for division, which returns a float.
    average_score = (test_one_score + test_two_score + test_three_score) / 3 → Result: 87.0
  4. 4

    Step 4 — Assign a boolean for passing status

    We can assign the result of a comparison directly to a variable. The expression average_score >= 70 evaluates to True or False. The variable name uses the is_ prefix, which is a common snake_case convention for booleans.
    is_passing = average_score >= 70 → Result: True
  5. 5

    Step 5 — Print the results

    Now we use all our named variables in a print statement. Because we chose clear snake_case names, anyone reading the code can understand what each variable represents without any extra comments.
    print(student_name, "average:", average_score, "passing:", is_passing) Output: Maria Garcia average: 87.0 passing: True

SECTION 7

Good Names vs. Bad Names — A Comparison

Choosing good variable names is a skill that improves with practice. The table below compares names that follow Python conventions with common mistakes beginners make. Each "bad" example is technically valid Python (it won't crash), but it makes the code harder to understand and maintain.

Bad NameGood NameWhy It's Better
xplayer_healthDescriptive — you instantly know what data it holds
playerHealthplayer_healthFollows PEP 8 snake_case; camelCase is a Java/JS convention
TEMPtemperature_celsiusALL CAPS suggests a constant; includes unit for clarity
datastudent_gradesSpecific — "data" is too vague to be useful
nnum_attemptsClear abbreviation pattern: num_ prefix is widely understood
myVariableupload_speed_mbpsMeaningful name with units — no "my" prefix needed

Comparison of poor and well-chosen variable names

✦

KEY TAKEAWAY

Writing code is like writing a recipe. If a recipe says "add some of ingredient A to container B," you'd be lost. But "add 2 cups of flour to the mixing bowl" is instantly clear. Good variable names turn your code into a recipe that anyone can follow. Aim for names that are descriptive, consistent (always snake_case), and concise (avoid unnecessarily long names like the_total_number_of_students_in_class).

SECTION 8

Connection to Advanced Topics

Variable assignment and naming conventions are the starting point for much deeper concepts in Python. As you progress, you'll encounter ideas that build directly on what you've learned here. The table below connects today's fundamentals to more advanced topics you'll see in future lessons.

What You Learned TodayAdvanced ExtensionWhy It Matters
x = 5 (simple assignment)Data types & type conversionYou'll learn that 5 is an int, 5.0 is a float, and "5" is a string — and how to convert between them
Naming a variable onceScope & lifetimeVariables inside a function are local — they disappear when the function ends. Global vs. local scope is a critical concept.
snake_case for variablesPascalCase for classesWhen you learn object-oriented programming, class names use PascalCase while their methods and attributes use snake_case.
name = valueMutable vs. immutable objectsLists can be changed in place (mutable), while strings and integers cannot (immutable). This affects how reassignment works.
+= augmented assignmentLoops and accumulatorsYou'll use total += item inside loops to build up running totals.

How today's concepts connect to future Python topics

Think of today's lesson as learning the alphabet before writing essays. Every line of Python you will ever write involves naming things and assigning values. Mastering these basics now means you'll spend less time debugging confusing names later and more time solving the interesting problems.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why = in Python is called the assignment operator rather than the "equals" operator. How does its behavior differ from the = sign you use in math class?
Show answer
In math, x = 5 states a fact: x and 5 are the same value, and you can also write 5 = x. In Python, x = 5 is a command: "take the value 5 and bind the name x to it." The direction matters — the name is always on the left, and the value (or expression) is always on the right. Writing 5 = x in Python would cause a SyntaxError because you can't assign to a literal number. This one-directional behavior is why it's called assignment, not equality.

Question 2: BASIC CALCULATION

Rewrite the following three variable names so they follow proper snake_case convention, then assign each one an appropriate value: firstName MaxScore NUMBEROFPLAYERS
Show answer
The corrected snake_case names and sample assignments are: first_name = "Alex" (camelCase → snake_case by adding an underscore before the capital letter and lowercasing it), max_score = 100 (PascalCase → snake_case by separating words with underscores and lowercasing all letters), and number_of_players = 4 (ALL CAPS with no separators → snake_case by splitting into individual words, lowercasing, and joining with underscores). Note that MAX_SCORE would also be acceptable if it represents a constant that never changes.

Question 3: INTERMEDIATE

Read the following code and predict the final value of balance. Explain what happens at each line. balance = 500 deposit_amount = 150 balance = balance + deposit_amount withdrawal_amount = 200 balance -= withdrawal_amount
Show answer
Line 1 assigns 500 to balance. Line 2 assigns 150 to deposit_amount. Line 3 evaluates the right side first: 500 + 150 = 650, then reassigns balance to 650. Line 4 assigns 200 to withdrawal_amount. Line 5 uses augmented assignment: balance -= 200 is equivalent to balance = balance - 200, so 650 − 200 = 450. The final value of balance is 450.

Question 4: APPLIED

You're building a simple tip calculator. Write Python code that: (1) stores a meal cost of $42.50 in a variable, (2) stores a tip percentage of 18% as a decimal, (3) calculates the tip amount and stores it, and (4) calculates and stores the total bill. Use proper snake_case for every variable name.
Show answer
Here's the solution: meal_cost = 42.50 tip_percentage = 0.18 tip_amount = meal_cost * tip_percentage total_bill = meal_cost + tip_amount Python evaluates 42.50 * 0.18 to get tip_amount = 7.65, then 42.50 + 7.65 to get total_bill = 50.15. Every variable is descriptive and uses snake_case: meal_cost not mc, tip_percentage not tipPct.

Question 5: CRITICAL THINKING

A classmate shows you their code and says it isn't working as expected: temp_fahrenheit = 98.6 temp_celsius = temp_fahrenheit - 32 * 5 / 9 They expected temp_celsius to be 37.0 (normal body temperature in Celsius), but they're getting a different number. (a) What value does temp_celsius actually hold? (b) Why is the result wrong? (c) Fix the code. Make sure all names remain in proper snake_case.
Show answer
(a) Python follows order of operations (PEMDAS). Without parentheses, it evaluates 32 * 5 / 9 first, getting approximately 17.778, then subtracts that from 98.6, giving temp_celsius ≈ 80.822. (b) The formula for Fahrenheit to Celsius is (F − 32) × 5 / 9. The subtraction of 32 must happen before the multiplication. Without parentheses, Python multiplies first. (c) The fix is to add parentheses: temp_celsius = (temp_fahrenheit - 32) * 5 / 9. This evaluates (98.6 − 32) = 66.6 first, then 66.6 × 5 / 9 = 37.0. The variable names were already correct snake_case — the bug was in the expression, not the naming. This shows that assignment binds the name to whatever the right side evaluates to, so getting the expression right is crucial.

SUMMARY

Lesson Summary

Summary

Variable assignment in Python uses the = operator to bind a name on the left to a value (or the result of an expression) on the right. Python evaluates the right side first, creates or locates the resulting object in memory, and then attaches the name to it like a label. Variables can be reassigned at any time, and augmented operators like += provide a shorthand for updating a variable based on its current value.

Python's official style guide, PEP 8, recommends snake_case for variable and function names: all lowercase letters, with words separated by underscores (e.g., player_health). Valid names must start with a letter or underscore, contain only letters, digits, and underscores, and cannot be reserved keywords. Choosing descriptive, consistently formatted names is one of the most impactful habits you can build as a programmer — it makes your code readable, maintainable, and professional.

Varsity Tutors • Python • Variable Assignment & snake_case