6.1 Introduction to Variables
What a variable really is underneath the syntax, why that matters for memory behavior, and a map of the deeper reference, memory, and scope topics this chapter covers.
The topics this chapter covers, once the basic syntax of declaring and naming variables is already familiar.
What Is a Variable, Really?
What Is It?
Syntactically, a variable is just a name bound with = — that part is covered in 4.8 Variables. Underneath that syntax, a variable is a name bound to an object living in memory, not a container holding a value directly.
Why Does It Matter?
Whether a variable “contains” a value or merely points at one changes how assignment, function calls, and copying behave — this is the single idea the rest of this chapter builds on.
>>> server_name = "web01"
>>> print(server_name)
web01
How Is It Used?
Assign with =, then refer to the name anywhere afterward in the same scope — the mechanics of where it’s visible are covered in 6.8 Variable Scope.
Already Covered Elsewhere
This chapter assumes the basics are familiar and doesn’t re-teach them. If any of the following are new, read these first:
- Declaring, assigning, and dynamically typing variables — 4.8 Variables
- Naming rules and PEP 8 conventions — 4.7 Identifiers
- The
UPPER_SNAKE_CASEconstant convention — 4.9 Constants - Every value being an object with identity/type/value — 5.2 Python Object Model
Real-World Examples
current_user = "alice"— tracking who’s logged inretry_count = 0— tracking state across a loopresponse = requests.get(url)— holding a result for later use
Variables in DevOps Scripts
DevOps scripts lean on variables constantly to avoid hardcoding values that change per environment (expanded on in 6.11 Variables in DevOps):
region = "us-east-1"
instance_type = "t3.medium"
max_retries = 3
print(f"Launching {instance_type} in {region}")
Quick Interview Answer
“Syntactically a variable is a name bound with
=, but underneath, it’s a label pointing at an object living in memory — not a box holding a value. That distinction is why assignment copies a reference rather than data, why mutable and immutable arguments behave differently in functions, and why copying a list needscopy/deepcopyinstead of plain assignment.”
Common Mistakes
- Treating a variable as a box that “holds” a value, then being surprised that
b = ashares one object instead of duplicating it (see 6.2 Objects and Variable References). - Assuming this chapter re-explains naming rules or basic assignment — that groundwork lives in Chapter 4: Python Syntax.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form