Python Variables
Satellite · Data Types
Python Variables
Variables are labels pointing to objects. Understand assignment semantics so you never accidentally overwrite shared data.
Assignment
count = 10
name = "Ada"
- Variables don't have types; the objects they reference do.
- Multiple assignment works:
x = y = [](be careful with mutables).
Unpacking
lat, lon = location
a, *rest = [1, 2, 3, 4]
Naming conventions
- snake_case for variables/functions
- UPPER_SNAKE_CASE for constants (
MAX_RETRIES) - Avoid single-letter names except for temporary loops
Scope
| Scope | Description |
|---|---|
| Local | Inside current function |
| Enclosing | Parent function scopes |
| Global | Module-level |
| Builtins | Provided by Python |
Use global and nonlocal sparingly; prefer passing values explicitly.
Mutability reminders
config = {"debug": True}
alias = config
alias["debug"] = False
# config now shows debug False, too
Copy mutable objects when you need isolation: copy = config.copy().
Next up in your learning path
Frequently Asked Questions
Is there block scope in Python?
No. Variables defined inside loops or if statements leak into the surrounding scope. Only functions define new scopes.
How do I declare constants?
Python has no true constant keyword. Use naming conventions (UPPER_SNAKE_CASE) and keep them at module level. Tools like mypy can flag reassignment if you annotate with `Final`.
Why does `x is y` sometimes return True for small integers?
CPython caches small integers and strings, so identities may match. Always use `==` for value comparison.