Ad – 728Γ—90
🌱 Beginner

Python Variables – The Complete Guide

Variables are the foundation of every program. They're how your program remembers information β€” a user's name, a score, a list of items. In Python, creating variables is incredibly simple, yet there's a lot to understand about how they work, best practices for naming them, and the common mistakes beginners make. This lesson covers everything you need to know.

⏱️ 20 min read 🎯 Beginner πŸ“… Updated 2026

What is a Variable?

A variable is a named storage location in your computer's memory that holds a value. Think of it like a labeled box: the label is the variable name, and whatever is inside the box is the value.

Without variables, programs can't remember anything. Every time you need a value, you'd have to type it again. With variables, you store a value once and use it as many times as needed.

In the real world, variables are like:

  • A shopping cart that stores items until checkout
  • A whiteboard where you write temporary calculations
  • A contact name in your phone (the name is the variable, the number is the value)

Creating Variables in Python

In Python, you create a variable with a single line using the assignment operator (=):

Python
# Creating variables
name = "Alice"        # string variable
age = 25              # integer variable
height = 5.7          # float variable
is_student = True     # boolean variable

# Using variables
print(name)
print(age)
print(height)
print(is_student)
β–Ά Output
Alice 25 5.7 True
πŸ’‘
No Type Declaration Needed

Unlike Java or C++, you don't need to specify the type. Python automatically detects it: name = "Alice" is enough β€” no String name = "Alice".

How Assignment Works

The = operator in Python is NOT a math equals sign. It means "assign the value on the right to the name on the left". Think of it as an arrow pointing left: right β†’ left.

Python
# Right side is evaluated FIRST, then assigned
x = 10
x = x + 5  # Take current x (10), add 5, store result (15) back in x
print(x)   # Output: 15

# This is valid Python
score = 0
score = score + 100
score = score * 2
print(score)  # Output: 200
β–Ά Output
15 200

Variable Naming Rules

Python has strict rules about what you can name a variable. Breaking these rules causes a SyntaxError.

RuleValid ExampleInvalid Example
Must start with a letter or underscorename, _value1name, !var
Can contain letters, numbers, underscoresuser_1, value2user-1, value.2
Case-sensitiveName β‰  nameβ€”
Cannot be a Python keywordfor_loopfor, if, class
No spaces allowedfirst_namefirst name
Python
# βœ… Valid variable names
name = "Alice"
user_age = 30
_private = "hidden"
camelCase = "also valid but not recommended"
number1 = 42
MAX_SIZE = 100  # constants use ALL_CAPS by convention

# ❌ Invalid variable names (these cause SyntaxError)
# 2name = "Alice"   β†’ starts with number
# my-var = 10       β†’ hyphen not allowed
# for = "loop"      β†’ 'for' is a keyword
# my var = "test"   β†’ space not allowed

Naming Conventions (Best Practices)

Just because something is valid doesn't mean it's good. Python has community conventions (from PEP 8) about how to name things:

🐍

snake_case

Use for regular variables and functions. Words separated by underscores: first_name, user_age, total_score.

πŸ›οΈ

UPPER_CASE

Use for constants (values that never change): MAX_SIZE = 100, PI = 3.14159, DB_URL = "...".

πŸ—οΈ

PascalCase

Use for class names (covered in OOP): UserProfile, BankAccount, HttpClient.

πŸ”’

_single_underscore

Prefix with underscore to indicate "private" or "internal use": _cache, _temp_value.

Multiple Assignment

Python allows some powerful shorthand for assigning variables:

Python
# Assign multiple variables on one line
x, y, z = 10, 20, 30
print(x, y, z)  # Output: 10 20 30

# Assign the same value to multiple variables
a = b = c = 0
print(a, b, c)  # Output: 0 0 0

# Swap two variables (Python does this elegantly!)
x = 5
y = 10
x, y = y, x  # Swap without a temp variable
print(x, y)  # Output: 10 5

# Unpack a list
coordinates = [100, 200]
x_pos, y_pos = coordinates
print(f"x: {x_pos}, y: {y_pos}")  # Output: x: 100, y: 200
β–Ά Output
10 20 30 0 0 0 10 5 x: 100, y: 200
Ad – 336Γ—280

Dynamic Typing – Variables Can Change Type

In Python, variables are dynamically typed. This means the same variable can hold different types of values at different points in your program. Python doesn't lock you into one type.

Python
x = 10        # x is an integer
print(type(x))  # 

x = "hello"   # Now x is a string
print(type(x))  # 

x = [1, 2, 3] # Now x is a list
print(type(x))  # 

x = 3.14      # Now x is a float
print(type(x))  # 
β–Ά Output
<class 'int'> <class 'str'> <class 'list'> <class 'float'>
⚠️
Dynamic Typing Can Cause Bugs

While convenient, dynamic typing can lead to hard-to-find bugs. If you accidentally overwrite a variable with the wrong type, Python won't warn you. Be intentional about how you use variable names.

Checking Variable Type

Use the built-in type() function to check what type a variable currently holds:

Python
name = "Bob"
score = 99
price = 19.99
active = True

print(type(name))   # 
print(type(score))  # 
print(type(price))  # 
print(type(active)) # 

# Check if a variable is a specific type
print(isinstance(name, str))   # True
print(isinstance(score, int))  # True
print(isinstance(score, str))  # False

Deleting Variables

You can delete a variable using the del keyword. After deletion, trying to use the variable raises a NameError.

Python
temp = "I'm temporary"
print(temp)  # I'm temporary

del temp
# print(temp)  # This would raise: NameError: name 'temp' is not defined

Global vs Local Variables (Preview)

Variables have scope β€” the part of your code where they're accessible. We'll cover scope in depth in the Functions section, but here's a quick preview:

Python
global_var = "I'm global"  # Accessible everywhere

def my_function():
    local_var = "I'm local"   # Only accessible inside this function
    print(global_var)          # Can access global
    print(local_var)           # Can access local

my_function()
print(global_var)   # Works fine
# print(local_var)  # NameError: not accessible here

Common Mistakes with Variables

Mistake 1: Using a Variable Before Defining It

Python
# ❌ Wrong - using before defining
print(score)  # NameError: name 'score' is not defined
score = 100

# βœ… Correct - define first
score = 100
print(score)  # 100

Mistake 2: Confusing = with ==

Python
x = 10       # Assignment (stores value)
x == 10      # Comparison (True/False) β€” doesn't change x!

# Common bug:
if x = 10:   # SyntaxError! Use == for comparison
    print("yes")

if x == 10:  # Correct
    print("yes")

Mistake 3: Accidentally Overwriting Built-in Names

Python
# ❌ Don't do this - overwriting Python built-ins
list = [1, 2, 3]   # Now 'list' no longer refers to the built-in list!
input = "hello"    # Now you can't use input() function!
print = "hi"       # Now you can't use print() function!

# βœ… Use descriptive names instead
my_list = [1, 2, 3]
user_input = "hello"
message = "hi"

Augmented Assignment Operators

Python provides shortcuts for updating a variable's own value:

Python
score = 100

score += 50   # same as: score = score + 50 β†’ 150
score -= 30   # same as: score = score - 30 β†’ 120
score *= 2    # same as: score = score * 2  β†’ 240
score //= 4   # same as: score = score // 4 β†’ 60
score **= 2   # same as: score = score ** 2 β†’ 3600
score %= 100  # same as: score = score % 100β†’ 0

print(score)  # 0

πŸ‹οΈ Practical Exercise

Write a Python program that:

  1. Creates variables for your first name, last name, age, and favorite number.
  2. Prints a sentence combining all four variables using an f-string.
  3. Swaps the values of two numerical variables without using a third variable.
  4. Uses augmented assignment to double your age variable.

πŸ”₯ Challenge Exercise

Create a simple "budget tracker" using variables. Start with a budget of $1000. Create three expense variables (rent, food, entertainment) with realistic values. Subtract all three from the budget and print the remaining balance with a formatted message. Bonus: add a check that prints "Over budget!" if the balance is negative.

Interview Questions on Variables

  • What is a variable in Python? How is it different from a constant?
  • What are Python's variable naming rules?
  • What is dynamic typing? What are its advantages and disadvantages?
  • What is the difference between = and == in Python?
  • How do you swap two variables in Python without a temporary variable?
  • What happens when you use del on a variable?
  • What is the difference between local and global scope?
  • What built-in function is used to check a variable's type?

πŸ“‹ Summary

  • Variables are named storage locations that hold values in memory.
  • Create a variable with variable_name = value β€” no type declaration needed.
  • Names must start with a letter or underscore, can contain letters, numbers, underscores, and are case-sensitive.
  • Python uses snake_case for variables, UPPER_CASE for constants, PascalCase for classes.
  • Python is dynamically typed β€” the same variable can hold different types over time.
  • Use type() to check a variable's current type, and isinstance() to check against a specific type.
  • Augmented assignment operators (+=, -=, etc.) are shorthand for updating variables.

Frequently Asked Questions

Do I need to declare variable types in Python? +

No. Python uses dynamic typing, so you just write x = 10 and Python automatically knows it's an integer. You can optionally add type hints (x: int = 10) for clarity, but they're not enforced at runtime.

Can two variables point to the same value? +

Yes. When you write a = b, both a and b point to the same object in memory. For immutable types (like integers and strings), this is fine. For mutable types (like lists), changes through one variable affect the other. Use copy() to avoid this.

What is the maximum length of a Python variable name? +

Technically unlimited, but PEP 8 recommends keeping names under 79 characters (the line length limit). Practically, you'd never need a name that long. Aim for descriptive but concise names.