Ch 2.1 Variable Declaration and Naming Conventions
In Python, a variable is a named container for storing data. Unlike statically typed languages (Java, C++), Python does not require you to declare a variable's type in advance.
1. What Is a Variable? Dynamic Typing
Python is a dynamically typed language. You can assign any type of value to a variable, and you can later reassign it to a value of a different type.
# Assign directly without declaring a type
message = "Hello" # str
count = 42 # int
price = 3.14 # float
is_active = True # bool
# Check the type a variable points to
print(type(message)) # <class 'str'>
print(type(count)) # <class 'int'>
# The same variable can be reassigned to a different type (dynamic typing)
x = 10
print(type(x)) # <class 'int'>
x = "Python"
print(type(x)) # <class 'str'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>
In Python, a variable does not hold the value itself — it is a reference pointing to an object.
x = 10means "refer to the integer object 10 by the name x".
2. Variable Declaration and Reassignment
# Basic assignment
name = "Alice"
age = 30
height = 165.5
# Reassignment
name = "Bob" # same name, different value
age = age + 1 # reassignment using current value
age += 1 # same as above (augmented assignment)
print(f"{name}, age {age}") # Bob, age 32
3. Multiple Assignment
Python provides several ways to assign multiple variables in a single line.
# Assign different values to multiple variables (unpacking)
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Assign the same value to multiple variables
x = y = z = 0
print(x, y, z) # 0 0 0
# Variable swap — no temporary variable needed (a Python specialty!)
a, b = 10, 20
print(f"Before swap: a={a}, b={b}") # a=10, b=20
a, b = b, a
print(f"After swap: a={a}, b={b}") # a=20, b=10
# Extended unpacking (Python 3+)
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
head, *middle, tail = [1, 2, 3, 4, 5]
print(head) # 1
print(middle) # [2, 3, 4]
print(tail) # 5
4. Naming Conventions
The naming rules recommended by the Python PEP 8 style guide.
# snake_case — for variables, functions, and module names
user_name = "alice"
total_price = 29900
max_retry_count = 3
def calculate_total_price(items):
pass
# UPPER_SNAKE_CASE — for constants (defined at module level)
MAX_CONNECTIONS = 100
DATABASE_URL = "postgresql://localhost/mydb"
PI = 3.14159265358979
# PascalCase (UpperCamelCase) — for class names
class UserProfile:
pass
class HttpRequestHandler:
pass
# Bad examples (un-Pythonic)
userName = "alice" # camelCase — Java/JS style
UserName = "alice" # PascalCase — looks like a class
TOTAL_price = 100 # mixed style
Naming Convention Summary
| Target | Style | Example |
|---|---|---|
| Variables, functions | snake_case | user_name, get_data() |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, API_KEY |
| Classes | PascalCase | UserProfile, BaseModel |
| Modules, files | snake_case | user_profile.py |
| Packages | lowercase | mypackage |
5. Reserved Keywords
Python's reserved keywords cannot be used as variable names.
import keyword
# Print all keywords
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
# 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
# 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
# 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
# 'while', 'with', 'yield']
# Check if a word is a keyword
print(keyword.iskeyword("if")) # True
print(keyword.iskeyword("name")) # False
# Soft keywords (Python 3.12+)
print(keyword.softkwlist)
# ['_', 'case', 'match', 'type']
# Resolving keyword conflicts — add a trailing underscore
type_ = "integer" # 'type' conflicts with a built-in function
list_ = [1, 2, 3] # 'list' is a built-in type
id_ = 12345 # 'id' is a built-in function
6. Scope Basics — Global vs Local Variables
# Global variable (defined at the top of the module)
global_var = "global variable"
def my_function():
# Local variable (valid only inside the function)
local_var = "local variable"
print(global_var) # Reading a global variable is allowed
print(local_var)
my_function()
print(global_var) # Allowed
# print(local_var) # NameError: not accessible outside the function
# Modifying a global variable — requires the global keyword
counter = 0
def increment():
global counter # Declare intent to modify the global variable
counter += 1
increment()
increment()
print(counter) # 2
7. Deleting Variables with del
x = 10
y = [1, 2, 3]
# Delete a variable
del x
# print(x) # NameError: name 'x' is not defined
# Delete a list element
del y[0]
print(y) # [2, 3]
# Delete a dictionary key
data = {"a": 1, "b": 2, "c": 3}
del data["b"]
print(data) # {'a': 1, 'c': 3}
Writing meaningful variable names is the most important practice.
# Bad examples
d = 86400
t = d * 7
l = [1, 2, 3, 4, 5]
n = len(l)
# Good examples
seconds_per_day = 86400
seconds_per_week = seconds_per_day * 7
scores = [1, 2, 3, 4, 5]
total_count = len(scores)
Underscore (_) conventions:
# 1. _ (single underscore) — value to ignore
for _ in range(5):
print("Repeat!") # When the loop variable is not needed
_, important = (1, 2) # Ignore the first value
# 2. _ — last result in the REPL
# >>> 3 + 4
# 7
# >>> _ + 1
# 8
# 3. _name (single leading underscore) — internal/private convention
class MyClass:
def __init__(self):
self._internal_data = [] # Not recommended to access directly from outside
self.__private = "truly hidden" # Name mangling
# 4. __name__ (double leading and trailing underscores) — Python special attributes
print(__name__) # '__main__' (when run directly)
# Constants should always be defined at module level (not inside functions)
DATABASE_URL = "postgresql://localhost/db"
MAX_RETRIES = 3
TIMEOUT_SECONDS = 30
You have learned variable declaration and naming conventions. The next chapter takes a closer look at Python's basic data types: int, float, bool, str, and None.