Definition¶
A variable is a name that refers to a value. It lets you reuse data without rewriting it. Think of it as a label you can assign to an object. You can assign multiple labels to an object, all of them are referencing the same thing.
Why Use Variables?¶
Variables allow programmers to:
Reference and reuse values: Avoid the need to retype values throughout the code.
Make code readable: Meaningful labels like
nameorageclarify the purpose of the data being used.Easily modify references: Change which object a variable points to without affecting other parts of the program.
1) Creating a variable (assignment)¶
You can create a variable by writing a name, an equals sign =, and a value.
In other words, in Python, you assign a value to a variable using the assignment operator (=):
name = "Sam"
age = 25Name:
name,ageValue:
"Sam",25=means assignment, not “mathematically equal.”
The value can also be an output of a function like input().
name = input("What's your name? ")Here:
nameis the variable.input("What's your name? ")captures user input and assigns it to the variablename.
The equal sign (=) in name = input(...) does not mean equality.
It assigns the value on the right to the variable on the left by creating a reference or pointer to the data in memory.
Understanding Variables as References¶
When you assign a value to a variable in Python, you’re creating a reference to an object stored in memory, not directly storing the value itself.
Example:¶
num1 = 42 # 'num1' references the integer object 42
num2 = num1 # 'num2' now references the same integer object as 'x'
print(num1, num2) # Outputs: 42 42
# Modify 'num1'
num1 = 100 # 'num1' now points to a different integer object
print(num1, num2) # Outputs: 100 4242 42
100 42
Here:
Initially,
num1andnum2both reference the same object (42).When
num1is reassigned, it now references a new object (100), leavingnum2unchanged.
Types of Objects Referenced by Variables¶
A variable can name any Python value (object): a number, text, a Boolean value, or more complex things like collections of all those different types of values in structured as a list, or a dictionary (key, value), or table.
When we talk about types, we’re talking about the kind of value the variable currently refers to.
So: Python variables can reference different types of objects, and Python dynamically determines the object type at runtime.
Examples include:
Integer (
int): Whole numbers.
age = 25Floating-point (
float): Numbers with decimals.
height = 5.9 String (
str): Text data.
greeting = "Hello, World!" Boolean (
bool): Logical values (TrueorFalse).
is_active = True Identity and Equality¶
Python provides two operators to clarify the distinction between references and values:
is: Checks if two variables reference the same object in memory.==: Checks if two variables have equal values (object content).
Example:¶
original_list = [1, 2, 3]
referenced_original = original_list
independent_copy = [1, 2, 3]
print(original_list is referenced_original) # True: Both reference the same object
print(original_list == independent_copy) # True: Both have the same content
print(original_list is independent_copy) # False: They reference different objectsTrue
True
False
3) Variable naming rules and conventions¶
Rules (Python will error if you break these)¶
Must start with a letter or underscore:
student_id,_tempCan contain letters, digits, underscores:
user2,street_nameCannot start with a digit:
1st_placeis invalidCannot use reserved words:
if,for,class,import, …
Conventions (humans will thank you)¶
Use meaningful names:
Avoid generic names likex,y, ordata. Instead, use descriptive names such asuser_ageortotal_scoreto make the code self-explanatory.Example:
# Avoid
x = 5
# Better
user_age = 5
Stick to a naming convention:
Use snake_case (lowercase with underscore between parts):
my_favorite_color(preferred in Python).Reserve
UPPERCASEfor constants.
Avoid reserved keywords:
Python has a set of keywords that cannot be used as variable names (e.g.,def,class,if,int,float,str).
You can check them by importing thekeywordmodule:
import keyword
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']
Avoid single-character variables:
Use single-character names likei,j, orksparingly, mainly in contexts like loops.
Dynamic Typing in Action¶
Python variables are not bound to a fixed type, allowing reassignment of values of different types to the same variable:
num = 10 # Integer
print(type(num)) # <class 'int'>
text = "Hello" # Now a string
print(type(text)) # <class 'str'><class 'int'>
<class 'str'>
However, frequent type changes can make code harder to understand, so use this feature judiciously.
Advanced Tip: Multiple Assignments¶
Python supports assigning multiple variables in a single line:
x_coordinate, y_coordinate, z_coordinate = 1, 2, 3 # Assigns values to 3D coordinates
print(x_coordinate, y_coordinate, z_coordinate) # Outputs: 1 2 3
# Assign the same value to multiple variables
initial_value = default_value = shared_value = 42 # Assigns the same value to all
print(initial_value, default_value, shared_value) # Outputs: 42 42 421 2 3
42 42 42
Common Pitfalls to Avoid¶
Unintended mutation: Be cautious when multiple variables reference the same mutable object. Use
.copy()ordeepcopy()to create independent copies if needed.
import copy
lst1 = [1, 2, 3]
lst2 = copy.deepcopy(lst1)
lst1.append(4)
print(lst1, lst2) # Outputs: [1, 2, 3, 4] [1, 2, 3]
[1, 2, 3, 4] [1, 2, 3]
Using
isfor equality checks: Reserveisfor identity checks (e.g., comparing withNone), not value equality.
var1 = None
if var1 is None: # Preferred
print("var1 is None")
var1 is None
Immutable default arguments: Use immutable objects (like
None) for default arguments to avoid unexpected mutations.
def func(lst=None):
if lst is None:
lst = []
lst.append(1)
return lst