Python Variables
Python Variables: Assignment, Naming Rules, and Unpacking
A Python variable is a named label attached to an object in memory, created the moment you assign a value with =. You never need to declare a variable type in advance because Python tracks the type on the value itself.
Because variables hold references rather than fixed boxes, you can rebind a name to a new value at any time. Keeping variable types consistent inside a function still makes your code far easier to debug.
Creating and Unpacking Variables
You can assign single values, chain one value to multiple names, or unpack a sequence into separate variables on one line.
# Standard assignment
customer_id = 4082
account_active = True
# Tuple unpacking
width, height = 1920, 1080
first_name, last_name = "Nadia", "Karim"
print(customer_id, width, height, first_name)
Unpacking swaps two variables without a temporary variable: a, b = b, a.
Variable Naming Rules and Conventions
Python enforces strict syntax rules for identifier names and adds community style standards in PEP 8:
- Start names with a letter (
a-z,A-Z) or underscore_, never a digit. - Use only letters, numbers, and underscores (
user_age,item2). - Avoid Python reserved keywords such as
class,for,return, orimport. - Use
snake_casefor variables andUPPER_SNAKE_CASEfor module-level constants likeMAX_UPLOAD_MB = 25.
Common Mistakes to Avoid
- Shadowing built-in functions: Naming a variable
list,str,id, orsumoverrides Python's built-in name in that scope. - Misunderstanding shared mutable references: Writing
b = aon a list points both names to the same list, so mutatingbchangesatoo. - Reusing one variable name for unrelated types: Switching
datafrom a raw string to a dictionary mid-function often hides bugs.
Frequently Asked Questions
How do I check a variable's type in Python?
Pass the variable to the built-in type() function, such as type(customer_id), which prints <class 'int'>.
Are Python variables case-sensitive?
Yes. userScore and userscore refer to completely different variables in Python.
How do I delete a variable in Python?
Use the del statement (del temp_cache) to remove the name binding from the current namespace.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.