Variable Names Refer to Objects
In Python, a variable is a name bound to an object. The name is not a typed storage box: assignment can bind it to another object, while other names may still refer to the original object.
When Python executes x = 2, it evaluates the expression and binds the name x to the resulting integer object. Python decides where to store the object and whether to reuse one. Correct code must work with any of those implementation choices.
How Variables and Memory Work
The built-in id() returns an integer that uniquely identifies an object during that object's lifetime. CPython commonly derives it from a memory address, but Python does not promise that interpretation across implementations.
# Creating variable x with value 2
x = 2
print(x) # Output: 2
print(id(x)) # Implementation-specific object identity
# Creating variable y that refers to variable x
y = x
print(y) # Output: 2
print(y is x) # Output: True
# Creating variable z with the same value
z = 2
print(z) # Output: 2
print(z == x) # Output: True
# Never rely on z is x. Object reuse is implementation-specificAssignment y = x guarantees that both names refer to the same object at that moment. Creating another equal value guarantees that the values compare equal. It may create a separate object. Some Python implementations reuse immutable objects, but correct code never depends on that optimization.
Python Variable Characteristics
When you assign a value to a name, remember two things. Python binds the name to an object without a separate declaration. You can later bind the same name to an object of a different type.
No Variable Declaration
Unlike languages that require a separate variable declaration, Python binds a name when an assignment runs. Objects have types, and type(value) reports the type of the object currently bound to a name.
# Python does not require variable declaration
nama = "Budi" # String
umur = 25 # Integer
tinggi = 175.5 # Float
aktif = True # Boolean
# Python determines data type automatically
print(type(nama)) # Output: <class 'str'>
print(type(umur)) # Output: <class 'int'>
print(type(tinggi)) # Output: <class 'float'>
print(type(aktif)) # Output: <class 'bool'>Dynamic Data Types
Python is dynamically typed: each object has a type, while the same name can be rebound to objects of different types as the program runs.
# Variable with dynamic data types
data = 42 # Integer
print(f"Value: {data}, Type: {type(data)}")
data = "Hello World" # String
print(f"Value: {data}, Type: {type(data)}")
data = [1, 2, 3] # List
print(f"Value: {data}, Type: {type(data)}")
data = 3.14 # Float
print(f"Value: {data}, Type: {type(data)}")Variable Naming Rules
Python has strict rules for variable naming that you must follow for code to run correctly. A name may contain letters, digits, and underscores, but it cannot start with a digit, and it cannot be a reserved keyword.
Variable Name Components
An identifier starts with an underscore or a Unicode letter and may continue with identifier letters, underscores, and digits such as . Python accepts many non-ASCII identifiers, but descriptive ASCII snake_case names are often easier to type, search, and share across tools.
# Valid variable names
student_name = "Ahmad" # Using letters and underscore
score1 = 85 # Using letters and numbers
_total = 100 # Starting with underscore
MAX_SIZE = 1000 # All uppercase letters
camelCase = "valid" # camelCase style
snake_case = "valid" # **snake_case style**
print(student_name, score1, _total, MAX_SIZE, camelCase, snake_case)Mandatory Rules
Several mandatory rules that you must follow in Python variable naming. Variable names cannot start with a number. Python will generate a syntax error if you try to create a variable that starts with a number.
# CORRECT variable names
data1 = "valid"
data_2 = "valid"
_data3 = "valid"
# WRONG variable names (will cause error)
# 1data = "invalid" # SyntaxError
# 2nilai = "invalid" # SyntaxError
# 9test = "invalid" # SyntaxError
print(data1, data_2, _data3)Case Sensitivity
Python distinguishes between uppercase and lowercase letters in variable names. This means nama, Nama, and NAMA are three different variables.
# Python distinguishes uppercase and lowercase
nama = "budi"
Nama = "Siti"
NAMA = "Ahmad"
print(f"nama: {nama}") # Output: nama: budi
print(f"Nama: {Nama}") # Output: Nama: Siti
print(f"NAMA: {NAMA}") # Output: NAMA: Ahmad
# These three variables are different from each other
print(nama == Nama) # Output: False
print(Nama == NAMA) # Output: FalseKeywords That Cannot Be Used
Python reserves certain words as part of its syntax, so they cannot be used as variable names. Assigning to one of them raises a SyntaxError before the program starts.
Python Keywords List
These reserved keywords cannot be identifiers. The table groups them by their role in syntax.
| Role | Keywords |
|---|---|
| Logic and values | and, or, not, True, False, None |
| Branches and iteration | if, elif, else, for, while, break, continue, pass |
| Definitions and scope | def, class, lambda, return, yield, global, nonlocal |
| Imports and aliases | import, from, as |
| Errors and context | try, except, finally, raise, assert, with |
| Other operations | async, await, del, in, is |
Soft keywords such as match, case, type, and _ are special only in particular syntax contexts. keyword.iskeyword("match") returns False, while keyword.issoftkeyword("match") returns True.
# Examples of WRONG usage (will cause error)
# if = 10 # SyntaxError: invalid syntax
# for = "hello" # SyntaxError: invalid syntax
# def = 25 # SyntaxError: invalid syntax
# class = "test" # SyntaxError: invalid syntax
# CORRECT way for similar variable names
kondisi_if = 10
loop_for = "hello"
fungsi_def = 25
kelas_class = "test"
print(kondisi_if, loop_for, fungsi_def, kelas_class)Checking Keywords
Python provides the keyword module to check whether a word is a keyword or not.
import keyword
# View all Python keywords
print("Number of keywords:", len(keyword.kwlist))
print("Keyword list:")
for i, kw in enumerate(keyword.kwlist, 1):
print(f"{i:2d}. {kw}")
# Check if a word is a keyword
print(f"\nIs 'if' a keyword? {keyword.iskeyword('if')}")
print(f"Is 'nama' a keyword? {keyword.iskeyword('nama')}")
print(f"Is 'class' a keyword? {keyword.iskeyword('class')}")Variable Naming Best Practices
Python identifiers must follow the syntax rules above. Within those rules, choose names that state what each value represents. A name such as total_price tells the next reader more than tp, and the same habit keeps a longer program readable months later.
Meaningful Names
Use variable names that clearly explain what is stored in the variable. Meaningful names make code easier to understand, both for yourself and others.
# POOR variable names
h = 175
w = 70
a = 25
# GOOD variable names
body_height = 175
body_weight = 70
age = 25
# Calculate BMI with clear variable names
bmi = body_weight / ((body_height / 100) ** 2)
print(f"BMI: {bmi:.2f}")
# Variable names state what each value represents
print(f"Height: {body_height} cm")
print(f"Weight: {body_weight} kg")
print(f"Age: {age} years")Appropriate Name Length
Avoid variable names that are too long as they will make code hard to read. Conversely, names that are too short may not provide enough information.
# Name too long (POOR)
student_height_class_12_science_odd_semester = 175
# Name too short (POOR)
h = 175
# Appropriate name (GOOD)
student_height = 175
height = 175 # If context is already clear
# For counter variables, short names are acceptable
for i in range(10):
print(f"Iteration {i}")
# For more complex data, use clear names
student_count = 30
average_score = 85.5Consistent Writing Style
Python uses snake_case style for variable names, where words are separated by underscores and all letters use lowercase.
# snake_case style (RECOMMENDED for Python)
full_name = "Ahmad Budi"
birth_date = "1995-05-15"
home_address = "Jl. Merdeka No. 123"
# camelCase style (more common in JavaScript/Java)
fullName = "Ahmad Budi" # Valid, though less idiomatic in Python
# PascalCase style (usually for class names)
FullName = "Ahmad Budi" # Not recommended for variables
# Consistency within one program
math_score = 90
physics_score = 85
chemistry_score = 88
average_score = (math_score + physics_score + chemistry_score) / 3
print(f"Average score: {average_score:.2f}")Avoiding Confusion
Avoid using characters that can cause confusion, especially letters that look similar to numbers.
# Confusing characters (AVOID)
# l = 1 # Letter 'l' looks like number '1'
# I = 1 # Letter 'I' looks like number '1'
# O = 0 # Letter 'O' looks like number '0'
# Clearer alternatives
length = 1 # Use clear words
index = 1 # Or more descriptive names
empty = 0 # Names that explain the meaning
# Example usage in clear context
item_count = 10
for number in range(1, item_count + 1):
print(f"Item number {number}")
# Boolean variables with clear names
is_active = True
has_permission = False
can_edit = TrueExample of Variable Usage in Programs
The following program uses variables to calculate the area and perimeter of a rectangle.
import math
# Program to calculate rectangle area and perimeter
print("=== Rectangle Calculator ===")
# User input
length = float(input("Enter length (cm): "))
width = float(input("Enter width (cm): "))
if not (math.isfinite(length) and math.isfinite(width) and length > 0 and width > 0):
raise ValueError("Dimensions must be positive and finite")
# Calculations
area = length * width
perimeter = 2 * (length + width)
# Display results
print(f"\nCalculation Results:")
print(f"Length: {length} cm")
print(f"Width: {width} cm")
print(f"Area: {area} cm²")
print(f"Perimeter: {perimeter} cm")In this program, length and width name the two inputs, while area and perimeter name the calculated results. The check rejects nonpositive or nonfinite dimensions before calculating. Length 5 and width 3 produce area 15.0 cm² and perimeter 16.0 cm. Non-numeric text is rejected by float().
Name binding, identifier rules, and consistent conventions make Python code easier to read. Distinguishing equality, identity, and reassignment also prepares you for mutability, function arguments, and object models.