W3docs

Understanding Python Variables: A Comprehensive Guide

Learn how Python variables work: assignment, dynamic typing, multiple assignment, augmented operators, None, del, and scope basics with clear examples.

A variable is a named label that points to a value stored in memory. Variables are the primary way you hold, pass, and transform data in any Python program. Unlike some languages, Python does not require you to declare a type — you simply assign a value and Python figures out the type for you.

This page covers:

  • How to create and assign variables
  • Dynamic typing — what it means in practice
  • Multiple assignment and tuple unpacking
  • Augmented assignment operators
  • Checking a variable's type with type()
  • The special value None
  • Deleting variables with del
  • Variable scope basics

Related chapters: Variable Names · Output Variables · Assign Multiple Values · Python Data Types · Global Variables · Python Scope

Creating a Variable

To create a variable, write a name, then =, then the value. Python creates the variable and binds it to that value immediately.

Assign a string and print it

python— editable, runs on the server
John Doe

Here name is the variable name and "John Doe" is the value. The = sign is the assignment operator — it is not a test for equality (that is ==).

Variable names follow a few rules:

  • Must start with a letter or an underscore (_), never a digit.
  • Can contain letters, digits, and underscores.
  • Are case-sensitivescore, Score, and SCORE are three different variables.
  • Cannot be a Python keyword such as if, for, while, or class.

Python style (PEP 8) recommends snake_case for variable names: lowercase words joined by underscores, like first_name or total_price. For naming best practices, see Variable Names.

Dynamic Typing

Python is dynamically typed: a variable has no fixed type. The type is determined by the value currently assigned to it and can change when you reassign it.

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

x = "hello"
print(type(x))   # <class 'str'>

x = 3.14
print(type(x))   # <class 'float'>
<class 'int'>
<class 'str'>
<class 'float'>

This flexibility is convenient but also a common source of bugs: if you accidentally overwrite a variable with a value of the wrong type, Python will not warn you — only a TypeError (or wrong result) at runtime will. Type hints (e.g. x: int = 10) are a way to document intent and catch such mistakes early with a type checker. See Python Type Hints for details.

Checking a Variable's Type

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

name = "Alice"
age = 30
price = 9.99
active = True

print(type(name))    # <class 'str'>
print(type(age))     # <class 'int'>
print(type(price))   # <class 'float'>
print(type(active))  # <class 'bool'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

type() is especially useful when debugging — when a variable contains an unexpected type, print(type(x)) is the fastest way to confirm what it actually holds.

Variables for Every Data Type

Python has a rich set of built-in types. Here is a single block that creates one variable of each common type so you can see the naming pattern at a glance:

Assign variables of different types

integer_val  = 10                          # int
float_val    = 10.5                        # float
complex_val  = 10 + 5j                     # complex
string_val   = "Hello, World!"             # str
bool_val     = True                        # bool
list_val     = [1, 2, 3, 4, 5]            # list  (mutable, ordered)
tuple_val    = (1, 2, 3, 4, 5)            # tuple (immutable, ordered)
dict_val     = {"key1": "value1"}          # dict  (key-value pairs)
set_val      = {1, 2, 3, 4, 5}            # set   (unique, unordered)
none_val     = None                        # NoneType

For a deep dive into when to choose each type, see Python Data Types.

Multiple Assignment

Assigning the Same Value to Several Variables

You can chain = to assign the same value to multiple variables in one line:

a = b = c = 0
print(a, b, c)
0 0 0

This is useful for initializing counters or flags, but be careful with mutable objects — a = b = c = [] makes all three names point to the same list, so modifying one changes all three.

Tuple Unpacking

Assign different values to multiple variables on one line by separating them with commas:

x, y, z = 1, 2, 3
print(x, y, z)
1 2 3

Python matches the right-hand values to the left-hand names in order. The number of names must equal the number of values, or you get a ValueError. For starred (*) and nested unpacking, see Assign Multiple Values.

Augmented Assignment Operators

An augmented assignment combines an operation with assignment in a single step. Instead of writing count = count + 1, you write count += 1:

count = 0
count += 1    # same as count = count + 1
print(count)  # 1

total = 100
total -= 25   # same as total = total - 25
print(total)  # 75

price = 10.0
price *= 1.2  # same as price = price * 1.2
print(price)  # 12.0
1
75
12.0

The full set of augmented assignment operators is +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, and <<=. They work on any type that supports the underlying operator — for example, += on a string concatenates:

message = "Hello"
message += ", World!"
print(message)
Hello, World!

Arithmetic with Variables

Variables holding numbers can be used in arithmetic expressions. Python evaluates the expression and returns a new value:

Math with variables

a = 10
b = 20

print(a + b)   # addition       → 30
print(b - a)   # subtraction    → 10
print(a * b)   # multiplication → 200
print(b / a)   # division       → 2.0  (always float in Python 3)
print(b // a)  # floor division → 2
print(b % a)   # modulo         → 0
30
10
200
2.0
2
0

Notice that / always returns a float in Python 3, even when the result is a whole number. Use // when you need an integer quotient.

For the complete list of operators (bitwise, comparison, logical, membership, identity), see Python Operators.

The Special Value None

None is Python's way of representing "no value" or "nothing". It is the only value of the type NoneType:

result = None
print(result)         # None
print(type(result))   # <class 'NoneType'>
print(result is None) # True
None
<class 'NoneType'>
True

Always test for None with is None (identity check), not == None (equality check). Functions that do not explicitly return a value return None by default.

Deleting a Variable

Use the del statement to remove a variable name from the current scope. After deletion, referencing the name raises a NameError:

temp = "temporary value"
print(temp)  # temporary value

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

del is most often used to free memory explicitly (e.g. after processing a large dataset) or to clean up local state. It removes the name binding, not necessarily the underlying object — Python's garbage collector reclaims the object's memory when no names point to it.

Variable Scope Basics

Where a variable is accessible depends on where it is defined. The two most common scopes are:

  • Local scope — a variable created inside a function exists only for the lifetime of that function call.
  • Global scope — a variable created at the top level of a module is accessible from anywhere in that module.
message = "I am global"   # global variable

def greet():
    greeting = "Hello"    # local variable — not accessible outside
    print(greeting)
    print(message)        # can read global variable

greet()
# print(greeting)  # NameError — greeting does not exist here
Hello
I am global

Modifying a global variable from inside a function requires the global keyword. See Global Variables and Python Scope for the full LEGB rule.

Practice

Practice
In Python, which of the following is true about variables?
In Python, which of the following is true about variables?
Was this page helpful?