Variables are the foundation of every Python program. They let you name values so you can reuse, transform, and reason about them. Because Python is dynamically typed, you don’t declare a variable’s type up front—names are bound to objects at runtime. This guide walks you through creation, assignment patterns, data types, naming rules, type checking and casting, references, scope (LEGB), deletion, practical patterns, comparisons with other languages, and hands‑on exercises.
Introduction to Python Variables
A variable in Python is a label (identifier) that refers to an object held somewhere in memory. You don’t allocate memory or specify types explicitly; instead, Python creates the object when you run the assignment and binds the name on the left to the object on the right. This makes rapid prototyping and expressive code natural, especially for data work and scripting.
Why Use Variables?
Variables eliminate duplication and magic numbers/strings, make code readable, and enable incremental changes. You can compute values once, store them under meaningful names, and reuse or update them later—critical for maintainability and performance.
Creating and Assigning Variables
Python creates variables when it first sees an assignment using the = operator. The right‑hand side is evaluated to an object; the left‑hand side is a name that will refer to that object. No declarations are needed.
Basic Assignment
Use = to bind a name to a value:
x = 5
name = "Alice"You can check the results immediately with print(x, name) or a debugger/REPL.
Reassigning Values
Names can be rebound to objects of any type at runtime. This flexibility is part of Python’s dynamic typing:
x = 10 # x refers to an int
x = "Hello" # now x refers to a strMultiple and Parallel Assignments
Python supports binding multiple names in one statement—great for concise code and tuple unpacking:
a = b = c = 100 # all names refer to the same int object
x, y, z = 1, 2.5, "Python" # parallel assignmentAdvanced Assignments
Iterable unpacking lets you split sequences into names, and the walrus operator (:=) assigns within expressions:
x, y = [10, 20] # unpack a list
if (n := len([1, 2, 3])) > 2:
print(n) # prints 3Data Types in Python Variables
A variable can reference any Python object. Common categories include numbers, strings, booleans/specials, and collections.
Numeric Types
- int: arbitrary‑precision integers.
- float: double‑precision floating points (IEEE 754).
- complex: complex numbers with real and imaginary parts.
x = 5 # int
y = 3.14 # float
z = 2 + 3j # complexString Variables
Strings are sequences of Unicode characters, defined with single or double quotes. They support escaping and formatting (f‑strings):
text = "Hello"
quote = 'Don't worry'
multiline = """Line 1
Line 2"""
name = "Alice"
greeting = f"Hi, {name}!"Boolean and Special Literals
True and False represent Boolean values; None represents “no value” or the absence of a result. Truthiness applies in conditions—empty containers are falsey, non‑empty are truthy.
is_active = True
result = None
if not result:
print("No result yet")Collections
Python offers flexible containers for grouping values:
nums = [1, 2, 3] # list (mutable)
coords = (10.0, 20.0) # tuple (immutable)
unique = {1, 2, 2, 3} # set (unique elements)
info = {"name": "John", "age": 30} # dict (key/value pairs)Naming Variables in Python
Good names communicate intent and reduce bugs. Python identifiers are case‑sensitive and typically follow PEP 8 conventions.
Rules for Naming
- Must start with a letter or underscore.
- Cannot begin with a number or special character.
- Case‑sensitive identifiers.
- Avoid reserved keywords (e.g.,
for,class,def).
Naming Conventions
- snake_case for variables and functions:
student_name,total_count - PascalCase for classes:
StudentName camelCaseis uncommon in Python but appears in some APIs.
student_name = "Iris"
class StudentRecord: ...Best Practices
Use descriptive, pronounceable names. Prefer total_revenue over tr. Avoid shadowing built‑ins (e.g., don’t name a variable list or id). Reserve single letters for short‑lived counters in tight loops.
Checking and Casting Variables
You can introspect types and explicitly convert between them when appropriate.
Get Variable Type
type() shows the object’s type, while isinstance() is preferred when checking against an inheritance hierarchy:
type(42) # <class 'int'>
type("Hello") # <class 'str'>
isinstance(True, bool) # TrueCasting Variables
Use constructors to convert between types. Beware of invalid conversions (they raise ValueError):
x = str(3) # "3"
y = float(10) # 10.0
z = int(5.5) # 5
flag = bool("") # False (empty string is falsey)Understanding Object References
In Python, a variable does not hold raw data; it holds a reference to an object. Multiple names can reference the same object, which matters for mutable objects.
a = [1, 2, 3]
b = a # both names reference the same list
b.append(4)
print(a) # [1, 2, 3, 4]
print(id(a) == id(b)) # TrueTo avoid unintentional aliasing, copy explicitly:
shallow = a[:] # or list(a) or a.copy()
import copy
deep = copy.deepcopy(a)Understanding references also explains Python’s memory management and garbage collection: when an object’s reference count drops to zero, it can be reclaimed.
Variable Scope in Python
Scope determines where a name is visible. Python follows the LEGB rule: Local, Enclosing, Global, Built‑in.
Local vs Global Variables
A name assigned inside a function is local by default and shadows names from outer scopes:
x = "global"
def func():
x = "local" # shadows global x
return xUsing the global Keyword
Use global to rebind a module‑level name from inside a function:
x = 0
def increment():
global x
x += 1Nonlocal Variables
nonlocal lets an inner function rebind a variable from its nearest enclosing (non‑global) scope—useful for closures:
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
inner()
return x # "inner"Class and Instance Variables
Class attributes are shared across instances; instance attributes belong to each object:
class Counter:
default_step = 1 # class variable
def __init__(self):
self.value = 0 # instance variableDeleting Variables
Use del name to remove a name binding; the object may be garbage‑collected if nothing else references it.
x = 10
del x
# print(x) # NameError: name 'x' is not defineddel also works on container items/slices (e.g., del my_list[0], del my_dict["key"]).
Practical Use Cases of Variables
Variables drive everyday patterns like counting, accumulating, flagging states, and temporary storage.
Counters & Accumulators
total = 0
for num in [1, 2, 3]:
total += num # accumulator
count = 0
for _ in range(5):
count += 1 # counterBoolean Flags
found = False
for item in ["a", "b", "c"]:
if item == "b":
found = True
breakTemporary Variables
a, b = 1, 2
# traditional
temp = a
a = b
b = temp
# pythonic swap
a, b = b, aComparison with Other Languages
Unlike C or Java, Python doesn’t require type declarations for variables, and names are bound to objects at runtime. Memory management is automatic via reference counting and garbage collection—no malloc/free or new/delete. Assignment binds names to objects (not raw memory locations), and function arguments are passed by object reference (sometimes described as “call by sharing”), meaning functions receive references to the same objects the caller holds.
Exercises and Practice
- Create variables and print their types:
mystring = "hello"
myfloat = 10.0
myint = 20
print(type(mystring), type(myfloat), type(myint))- Swap two variables both ways—using a temporary variable and tuple unpacking.
- Write a function that uses a
nonlocalcounter to track how many times it has been called. - Given a list of numbers as strings (e.g.,
["10", "20", "30"]), cast them to integers and sum them safely.
Conclusion
Python variables are flexible references to objects, created by assignment and governed by clear naming rules and scope (LEGB). Understanding data types, references vs copies, and when to cast empowers you to write code that’s both concise and correct. Master these fundamentals and you’ll be faster and safer across everything from quick scripts to production systems.
FAQs
What are the 4 types of variables in Python?
Local, Global, Instance, and Class variables.
Are Python variables dynamically typed?
Yes. A name can be rebound to objects of different types at runtime.
How do I check a variable’s type?
Use type(obj) for a direct check or isinstance(obj, ExpectedType) for inheritance‑aware checks.
How to make a variable constant in Python?
Python has no true constants. By convention use uppercase names, e.g., PI = 3.14159, and treat them as read‑only.
