5 min read
ā¢Question 3 of 41easyVariables in Python
How variables work in Python.
What You'll Learn
- How Python variables differ from other languages
- Variable naming conventions and rules
- Dynamic typing and type inference
- Variable scope and memory management
Understanding Python Variables
In Python, variables are references to objects in memory. Unlike languages like C or Java, Python doesn't require explicit type declarations. When you assign a value to a variable, Python automatically determines the type.
Think of variables as labels or name tags attached to objects, rather than containers that hold values.
Variable Assignment
code.pyPython
# Simple assignment - creates a reference to an object
x = 5
name = "Alice"
is_active = True
# Multiple assignment - assign multiple variables at once
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Tuple unpacking
coordinates = (10, 20)
x, y = coordinates
# Same value to multiple variables
x = y = z = 0
# Swapping values (Python's elegant way)
a, b = b, a # No temp variable needed!Variable Naming Rules
Python has strict rules for variable names:
| Rule | Valid | Invalid |
|---|---|---|
| Start with letter or underscore | name, _private | 2name |
| No special characters | my_var | my-var, my@var |
| No spaces | user_name | user name |
| Case sensitive | Name ā name | - |
| No reserved words | my_class | class, def |
code.pyPython
# Valid variable names
my_var = 1
_private = 2
myVar2 = 3
CamelCase = 4
CONSTANT = 5
# Invalid names (will cause SyntaxError)
# 2myvar = 1 # Can't start with number
# my-var = 1 # Hyphens not allowed
# my var = 1 # Spaces not allowed
# class = 1 # Reserved keywordNaming Conventions (PEP 8)
code.pyPython
# Variables and functions: snake_case
user_name = "john"
total_count = 42
# Constants: UPPERCASE
MAX_SIZE = 100
PI = 3.14159
# Classes: PascalCase
class UserProfile:
pass
# Private variables: leading underscore
_internal_value = "private"
# Dunder (magic) methods: double underscore
__init__, __str__, __repr__Dynamic Typing
Python is dynamically typed - variables can change type at runtime:
code.pyPython
x = 5 # x is int
print(type(x)) # <class 'int'>
x = "hello" # x is now str
print(type(x)) # <class 'str'>
x = [1, 2, 3] # x is now list
print(type(x)) # <class 'list'>
x = {"a": 1} # x is now dict
print(type(x)) # <class 'dict'>Type Checking
code.pyPython
x = 42
# Using type()
print(type(x)) # <class 'int'>
print(type(x) == int) # True
# Using isinstance() - preferred, handles inheritance
print(isinstance(x, int)) # True
print(isinstance(x, (int, float))) # Check multiple typesVariable Scope
code.pyPython
# Global scope
global_var = "I'm global"
def my_function():
# Local scope
local_var = "I'm local"
print(global_var) # Can access global
print(local_var) # Can access local
my_function()
# print(local_var) # Error! Not accessible outside function
# Modifying global inside function
count = 0
def increment():
global count # Declare intent to modify global
count += 1
increment()
print(count) # 1Memory and References
code.pyPython
# Variables are references
a = [1, 2, 3]
b = a # b points to same list
b.append(4)
print(a) # [1, 2, 3, 4] - a is also modified!
# To create a copy instead
a = [1, 2, 3]
b = a.copy() # or b = a[:]
b.append(4)
print(a) # [1, 2, 3] - a unchanged
# Check if same object
print(a is b) # False (different objects)
print(a == b) # May be True (same values)
# id() shows memory address
print(id(a), id(b)) # Different addressesInterview Tip
When asked about Python variables:
- Explain they're references to objects, not containers
- Mention dynamic typing vs static typing
- Discuss naming conventions (PEP 8)
- Explain scope: local, global, nonlocal
- Be ready to explain mutable vs immutable object references