Skip to main content

Variables and Assignment in Python: Complete Guide

Variables are named storage locations that hold data values in Python. A variable is a labeled container where you store information that your program can use and modify throughout its execution—learn how to create, name, and manage variables correctly, and understand Python's dynamic typing system that automatically infers data types at runtime.


Prerequisites

A basic understanding of Python syntax and how to run a Python script.


What Are Variables in Python?

In programming, a variable is a named reference to a value stored in memory. Think of it as a labeled box: you give the box a name, put something inside, and later you can open the box by name to read or change what's inside. Variables allow you to store data (numbers, text, boolean values) that your program can use and modify.

Every modern programming language uses variables. The difference lies in how you declare them and manage their types. In Python, creating a variable is simple: just assign a value to a name using the = operator.

# Creating variables with the assignment operator
name = "Alice"
age = 30
is_student = True

When Python executes these lines, it stores the string "Alice" in a location in memory and labels it name. Similarly, it stores the integer 30 as age and the boolean value True as is_student. You can then retrieve or modify these values by referencing the variable name.


How to Create Variables and Assign Values

The assignment operator (=) is the fundamental tool for creating variables in Python. The syntax is simple:

variable_name = value

The left side is the variable name (what you call it), and the right side is the value you're assigning. Let's look at practical examples:

# Assigning different data types
name = "Alice" # String (text)
age = 30 # Integer (whole number)
height = 5.7 # Float (decimal number)
is_student = True # Boolean (True or False)
favorite_colors = ["red", "blue"] # List (collection)

Once created, you can use these variables in operations:

# Using variables
print(name) # Output: Alice
print(age + 5) # Output: 35
print(name.upper()) # Output: ALICE

You can also reassign a variable—give it a new value—at any time:

age = 30
age = 31 # Reassign the variable
print(age) # Output: 31

This flexibility makes Python ideal for beginners: you don't need to plan your data types ahead of time.


Understanding Python's Dynamic Typing

Python uses dynamic typing, meaning the interpreter automatically determines a variable's data type based on the value assigned to it. You don't declare types explicitly (unlike Java or C++). This is one of Python's greatest strengths for rapid development.

When you assign a value, Python infers the type:

x = 10
print(type(x)) # Output: <class 'int'>

You can check a variable's type using the built-in type() function. The output <class 'int'> tells you that x is an integer.

One powerful feature of dynamic typing is that you can reassign a variable to a completely different type:

x = 10
print(type(x)) # Output: <class 'int'>

x = "Hello"
print(type(x)) # Output: <class 'str'>

x = 3.14
print(type(x)) # Output: <class 'float'>

Python allows this flexibility because each variable is just a label pointing to an object in memory. When you reassign x, you're simply moving that label to a new object. This flexibility is useful but also means you should be careful: reassigning variables carelessly can lead to bugs.


Best Practices for Naming Variables (PEP 8)

PEP 8 is Python's official style guide, a set of recommendations for writing readable, consistent code. Variable naming is a critical part of code readability—descriptive names make code self-documenting and easier to maintain.

PEP 8 Variable Naming Rules

  1. Use lowercase letters and underscores (snake_case)

    • Good: user_name, email_address, total_count
    • Bad: UserName, emailAddress, totalCount (camelCase)
  2. Start with a letter or underscore, never a number

    • Good: user_id, _private_value
    • Bad: 2user_id (syntax error)
  3. Use only letters, numbers, and underscores

    • Good: user_name_123
    • Bad: user-name, user$name (invalid characters)
  4. Be descriptive and concise

    • Good: total_sales, customer_email
    • Bad: x, temp, data (too vague)
  5. Avoid Python keywords and built-in names

    • Avoid: if, for, while, list, dict, str as variable names
    • These are reserved for Python's syntax and built-in functions
  6. Variables are case-sensitive

    • name and Name are two different variables
    • Mixing cases accidentally is a common source of bugs

Example: Good vs. Bad Naming

# Bad naming
a = "john"
b = 25
c = True
x = a + " is " + str(b) + " years old"

# Good naming (PEP 8)
user_name = "john"
user_age = 25
is_active = True
profile_message = user_name + " is " + str(user_age) + " years old"

The second version is immediately clear about what each variable represents. When you revisit this code in six months—or when a teammate reads it—descriptive names save time and prevent errors.


Key Takeaways

  • Variables are named storage locations for values that your program can use and modify.
  • Use the assignment operator (=) to create a variable and give it a value: name = value.
  • Python uses dynamic typing: the interpreter automatically determines a variable's type based on its value; you can reassign a variable to a different type.
  • Follow PEP 8 naming conventions: use lowercase with underscores (snake_case), start with a letter, avoid keywords, and choose descriptive names.
  • Use type() to inspect a variable's type at any point in your code.
  • Reassignment is allowed: you can change a variable's value (and type) at any time.

Frequently Asked Questions

What's the difference between a variable name and the value it stores?

A variable name is a label or reference; the value is the actual data. When you write name = "Alice", you create a label called name that points to the string "Alice" in memory. Multiple variables can hold the same value (x = 5 and y = 5), but each variable name is unique in its scope.

Can I use uppercase letters in variable names?

Yes, you can, but PEP 8 recommends lowercase with underscores for regular variables. Uppercase is reserved for constants (values that never change): MAX_USERS = 100 or PI = 3.14159. Mixed-case names (like UserName) are discouraged in Python; use user_name instead.

What happens if I use a Python keyword as a variable name?

Python will raise a SyntaxError. Keywords like if, for, while, import, and class are reserved for the language's syntax. Try to use one as a variable name, and your script will not run. Use descriptive alternatives instead: instead of if_condition, just call it condition.

Does Python really have no variable type restrictions?

Correct—no static type restrictions. However, Python now supports optional type hints (annotations) for documentation and IDE support: name: str = "Alice". Type hints don't enforce types at runtime; they're hints for developers and tools like mypy (a type checker). This is useful for large codebases.

Why do I need to follow naming conventions if Python doesn't enforce them?

Readability and teamwork. Consistent naming makes code easier to understand. When you follow PEP 8, other Python developers immediately understand your intent. It also reduces bugs: user_email is instantly clear; ue or email1 is not. Convention is a form of discipline that pays dividends in long-term maintenance.


Further Reading