Python Variables
Getting Started: Understanding Variables in Python
In programming, we often need to store information that can change while our program is running. This could be something simple like a user's age, a list of items in a game inventory, or a true/false setting for whether a door is locked. Without a way to name and hold onto these pieces of data, our programs couldn't remember things or react to changes.
Variables are the way Python lets us name and store information in the computer's memory so we can use and change it later.
What is a Variable? (Names Pointing to Objects)
A variable is a name you create that points to a piece of information, which Python calls an object. This object (the value) is stored somewhere in the computer's memory.
Think of the variable name (score
) as a label or a tag. You attach this label to an object (like the number 100
). When you use the name score
in your code, Python looks up which object that label is pointing to and gets the value for you.
# The variable name 'score' is created and points to the integer object '0'
score = 0
# The variable name 'game_title' is created and points to the string object "Space Adventure"
game_title = "Space Adventure"
This is different from thinking of a variable as a "box" that contains the value. In Python, the variable is more like a reference or a pointer to the value (the object) that lives elsewhere in memory. This idea of names pointing to objects is important for understanding how Python works.
Creating and Assigning a Value
You create a variable the first time you assign it a value. You do this using the equals sign (=
). This action is called assignment or binding (binding the name to an object).
# The name 'level' is bound to the integer object '1'
level = 1
# The name 'player_name' is bound to the string object "Hero"
player_name = "Hero"
The =
sign does not mean "equals" in the mathematical sense of comparison. It means "make the name on the left point to the object (value) on the right."
Data Types: What Kind of Information Can Be Stored?
The values (objects) that variables point to can be of different kinds, like numbers, text, true/false values, and many other kinds. Each distinct kind is called a data type. The type of an object tells Python how that data is stored and what actions you can perform with it. Python automatically determines the type of an object when it's created from a value you provide.
Understanding Data Types
Understanding data types is important because the type of an object determines the operations you can do with it. You can add numbers, for example, but you can't directly add text in the same way.
You can check the type of any value or variable using the type()
function:
print(type(100)) # Check the type of the value 100
# Output: <class 'int'>
current_score = 250.5
print(type(current_score)) # Check the type of the object 'current_score' points to
# Output: <class 'float'>
Let's look at some of the most common basic data types (objects) in Python.
Numbers
Python has different types for numbers. The two most common are for whole numbers and numbers with decimal points. The int
type is for any whole number (integers), positive, negative, or zero, without a decimal point. Integer objects can be very large.
player_age = 29
total_games = -5 # An integer can be negative
There are no separate types just for positive, negative, or zero numbers; a number's value determines if it's positive or negative, not its type. You can do basic math like adding (+
), subtracting (-
), and multiplying (*
) with integers.
The float
type is for numbers that have a decimal point. Even if the value is a whole number, if you include a decimal point, Python makes it a float object.
item_price = 19.99
game_version = 1.0 # Even with .0, this is a float
Floats also support math operations. Standard division (/
) between any two numbers always results in a float (e.g., 10 / 2
gives 5.0
). Use integer division (//
) to get a whole number result (e.g., 10 // 3
gives 3
). You can round a float number using the round()
function:
pi_value = 3.14159
rounded_pi = round(pi_value, 2) # Round to 2 decimal places
print(rounded_pi) # Output: 3.14
(Python also has types for complex numbers, but these are for more specialized math.)
You can convert an object from one number type to another using functions like int()
, float()
, or complex()
. This is called type conversion or "casting".
float_number = 3.14
whole_number = int(float_number) # Convert float to integer (cuts off decimal part)
print(whole_number) # Output: 3
int_number = 10
decimal_number = float(int_number) # Convert integer to float
print(decimal_number) # Output: 10.0
A full section on converting types comes later.
Text (Strings - str
)
The string type is used for sequences of characters. This includes words, sentences, letters, symbols, and even numbers if they are inside quotes. String objects represent text. You create string objects by putting characters inside single quotes ('...'
), double quotes ("..."
), or triple quotes ('''...'''
or """..."""
). Triple quotes are useful for text that spans multiple lines.
player_name = "Coder123"
status_message = 'Game paused.'
poem_snippet = """Roses are red,
Violets are blue."""
You can combine strings using the +
operator (this is called concatenation) or repeat them using the *
operator:
first_part = "Hello"
second_part = "World"
full_message = first_part + " " + second_part + "!"
print(full_message) # Output: Hello World!
separator = "=" * 10
print(separator) # Output: ==========
String objects also have many built-in methods to perform actions on the text, like changing its case or finding parts of the text. These methods return a new string object because string objects cannot be changed after creation (they are immutable). Methods like .lower()
or .replace()
give you back a modified copy.
player_id = "CoDeR123"
print(player_id.lower()) # Output: coder123 (returns a new string)
print("Hello World".replace("World", "Python")) # Output: Hello Python (returns a new string)
True or False (Booleans - bool
)
This type is simple but very important. It can only have one of two objects: True
or False
.
is_game_running = True
has_scored = False
Boolean objects are crucial for making decisions in your code (like in if
statements, which we'll see soon). In Python, when used in a condition (like in an if
statement), many objects are seen as either True (they are "truthy") or False (they are "falsy"), even if they are not boolean objects themselves. Falsy objects include False
, None
, the number 0
(int or float), empty sequences (like ""
, []
), and empty mappings ({}
). Almost everything else is truthy (non-zero numbers, non-empty strings, non-empty collections, etc.). This allows simple checks like if my_list:
to see if a list is not empty.
No Value (NoneType
- None
)
None
is a special object that represents the absence of a value. It's the only object of the NoneType
type.
current_selection = None # Nothing is selected yet
Use None
to indicate that a variable doesn't currently point to a meaningful value. When checking if something is None
, it's best practice to use is None
or is not None
: if current_selection is None:
.
Other Important Data Types (Collections)
Variables in Python can point to many other types of objects beyond these basics. Some of the most important are collection types, which group multiple items:
- Lists (
list
): Ordered, changeable collections ([]
). - Tuples (
tuple
): Ordered, unchangeable collections (()
). - Dictionaries (
dict
): Unordered collections of Key-Value pairs ({}
). - Sets (
set
): Unordered collections of unique items ({}
orset()
).
These types are essential for storing and managing groups of data and will be covered in detail in dedicated articles later.
Immutability vs. Mutability
An important concept related to data types and how variables work is whether the object a variable points to can be changed after it's created. Objects in Python are either mutable or immutable.
Immutable Objects: These are objects that, once created, cannot be changed. If you want to modify an immutable value, such as changing a number or altering a string, Python doesn't change the original object. Instead, it creates a new object with the new value, and if you've used an assignment (=
), the variable name is then made to point to this brand new object. Data types like integers (int
), floating-point numbers (float
), strings (str
), booleans (bool
), and tuples (tuple
) are examples of immutable types.
Let's look at an integer example:
my_number = 10
# The variable 'my_number' points to the integer object '10'.
# When you do my_number = my_number + 1:
# 1. Python calculates 10 + 1, resulting in the value 11.
# 2. A *new* integer object with the value '11' is created in memory.
# 3. The name 'my_number' is then updated to point to this *new* '11' object.
# The original '10' object is left unchanged (and Python's memory manager might clean it up later if nothing else points to it).
my_number = my_number + 1
print(my_number) # Output: 11
String operations also demonstrate immutability. Methods like .upper()
or .replace()
do not modify the original string object. They calculate a result and return a new string object containing that result.
my_string = "Hello"
# The variable 'my_string' points to the string object "Hello".
# my_string.upper() calculates the new string "HELLO" and returns it.
# The original "Hello" object is NOT changed.
# 'my_string' still points to the original "Hello" object unless you reassign it.
new_string = my_string.upper()
print(my_string) # Output: Hello (original string is unchanged)
print(new_string) # Output: HELLO (this is the new string)
# If you want the variable to point to the new string, you must reassign:
my_string = my_string.upper()
print(my_string) # Output: HELLO (now 'my_string' points to the new object)
Mutable Objects: In contrast, mutable objects can be changed or modified in place after they are created. When you perform an action that changes a mutable object (like adding an item to a list or changing a value in a dictionary), the object itself is directly altered in memory, but the variable name continues to point to the same object. Types like lists (list
), dictionaries (dict
), and sets (set
) are examples of mutable types.
Consider a list:
my_list = [1, 2, 3] # 'my_list' points to a specific list object in memory that contains [1, 2, 3].
print(f"Original list: {my_list}") # Output: Original list: [1, 2, 3]
# my_list.append(4) is an operation that modifies the list object *itself*.
# The list object now contains [1, 2, 3, 4].
# The name 'my_list' still points to the *exact same list object* in memory, it just has different contents now.
my_list.append(4)
print(f"Modified list: {my_list}") # Output: [1, 2, 3, 4]
Understanding the difference between mutable and immutable objects is important. It affects how values behave when you modify them, especially when you have multiple variable names pointing to the same object or when you pass variables into functions.
Displaying and Using Variables
Once a variable points to an object, you use the variable's name to access that object's value.
The most common way to see a variable's value is with the print()
function:
current_lives = 3
print(current_lives) # Output: 3
Use f-strings (formatted string literals) to easily include variables directly inside text. Put an f
before the opening quote, and place the variable name inside curly braces {}
within the string:
player_name = "Bob"
player_level = 5
print(f"Welcome, {player_name}! You are on level {player_level}.")
# Output: Welcome, Bob! You are on level 5.
Variables are used in almost every part of your code: in calculations, in condition checks (if player_score > 100:
), as arguments to functions, etc.
Changing a Variable's Value (Reassigning)
A key feature of variables is that the object they point to can change. You give an existing variable a new value (make it point to a new object) by using the assignment sign (=
) again.
current_level = 1 # 'current_level' points to integer object '1'
print(f"Starting level: {current_level}") # Output: Starting level: 1
current_level = 2 # Now 'current_level' points to integer object '2'. The link to '1' is gone for this name.
print(f"Moving to level: {current_level}") # Output: Moving to level: 2
Modifying a Variable's Value
Often, you want to change a variable's value based on what it was before (like adding to a score) or modify the contents of a mutable object it points to (like adding an item to a list).
If you want to change the value (make the name point to a new object based on the old object's value), you read the current value, do an operation, and assign the result back:
counter = 0
print(f"Counter starts at: {counter}") # Output: Counter starts at: 0
# Read counter's value (0), calculate 0 + 1 = 1, create a new integer object '1',
# then make the name 'counter' point to the new '1' object.
counter = counter + 1
print(f"Counter is now: {counter}") # Output: Counter is now: 1
Python provides convenient shortcut combined assignment operators:
score = 100
# Calculate score + 50 (150), create a new integer object '150',
# then make the name 'score' point to the new '150' object.
score += 50 # Same as score = score + 50
print(f"Score after adding: {score}") # Output: Score after adding: 150
If the variable points to a mutable object, you might modify the object in place without changing what the variable name points to:
my_list = [1, 2] # 'my_list' points to a list object
print(f"Original list: {my_list}") # Output: Original list: [1, 2]
my_list.append(3) # The list object *itself* is changed. 'my_list' still points to the *same* list object.
print(f"Modified list: {my_list}") # Output: Modified list: [1, 2, 3]
Variable Scope: Where Variables "Live"
Variables are not accessible from everywhere in your code. The part of the code where a variable can be used is called its scope. Understanding scope helps prevent names from conflicting and makes your code organized.
The simplest scopes to start with are:
- Global Scope: Variables defined directly in the main body of your Python file (not inside any function or class). They can usually be accessed from anywhere in that file after they are defined.
- Local Scope: Variables defined inside a function. They only "live" and can only be used within that specific function. When the function finishes, the local variables are typically removed.
# This is in the global scope
global_message = "I am global"
def greeting_function():
# This is in the local scope of greeting_function
local_name = "Alice"
print(f"Hello, {local_name}! {global_message}") # Can access global_message inside the function
greeting_function() # Call the function
# print(local_name) # This line would cause an error! 'local_name' only exists inside the function.
# NameError: name 'local_name' is not defined
print(global_message) # Output: I am global (Can still access global variable outside the function)
This is a simplified introduction; scope rules can be more complex with nested functions and classes, which you will learn about later. For now, remember that variables defined inside a function are separate from those outside.
Rules and Good Practices for Naming Variables
Choosing clear and correct names is crucial for readable code.
Required Rules
- A variable name must start with a letter (a-z, A-Z) or an underscore (
_
). - It cannot start with a number.
- It can only contain letters, numbers (0-9), and underscores (
_
). - Names are case-sensitive (
my_var
is different fromMy_Var
). - You cannot use Python keywords as variable names. These are words that have special meaning in Python.
Common Keywords to avoid: if
, for
, while
, class
, def
, import
, True
, False
, None
, and
, or
, not
, is
, in
, return
, print
... (and others)
Good Practices and Conventions
- Descriptive Names: Use names that explain the variable's purpose (e.g.,
user_age
instead ofx
). snake_case
: The standard naming style for variables and functions in Python issnake_case
. This means using lowercase letters and separating words with underscores (e.g.,player_score
,game_is_running
,high_score_limit
).- Constants Convention: For values that you intend to keep constant throughout your program (that should not be changed), the convention is to use names in ALL CAPS with underscores (e.g.,
MAX_LIVES = 3
,SCREEN_WIDTH = 800
,PI = 3.14159
). Python does not strictly prevent you from changing these, but the ALL CAPS name signals to anyone reading your code that it's meant to be a constant.
Declaring Multiple Variables on One Line
You can assign values to multiple variables in a single line. This can make your code more compact when setting up several related variables.
The structure is: variable1, variable2, ... = value1, value2, ...
The number of variables on the left must match the number of values on the right.
x, y, z = 10, 20, 30
print(f"x: {x}, y: {y}, z: {z}")
# Output: x: 10, y: 20, z: 30
first_name, last_name = "John", "Doe"
print(f"Full name: {first_name} {last_name}")
# Output: Full name: John Doe
This syntax is also commonly used for a neat Python trick: swapping the values of two variables easily:
a = 5
b = 10
print(f"Before swap: a={a}, b={b}") # Output: Before swap: a=5, b=10
a, b = b, a # Python evaluates the right side (10, 5) and assigns to the left side (a, b)
print(f"After swap: a={a}, b={b}") # Output: After swap: a=10, b=5
Type Annotations (Indicating Expected Type)
Python is dynamically typed, meaning you don't have to declare a variable's type. However, you can add optional type annotations (type hints) to variables. This adds information about the intended type, which is helpful for readability and code analysis tools.
You add a type annotation after the variable name using a colon :
. You can assign a value at the same time or later.
Syntax: variable_name: Type
or variable_name: Type = value
age: int = 30
user_name: str = "Alice"
is_active: bool = True
items_list: list = [] # Example with a type we'll see later
Adding type annotations does not change how your Python code runs. Python still determines the actual type based on the value. Their main benefits are:
- Readability: Makes your code's intention clearer.
- Tooling: Helps static analysis tools (like MyPy) check your code for potential type-related errors before you run it.
Managing Variables: Deleting a Variable
You can remove a variable name using the del
keyword. After you delete a variable, its name is no longer recognized, and you can't use it unless you create it again with a new assignment.
my_temp_variable = "This exists for a moment"
print(my_temp_variable)
# Output: This exists for a moment
del my_temp_variable # Remove the variable name
# If you try to print it now, you get an error:
# print(my_temp_variable)
# NameError: name 'my_temp_variable' is not defined
Using del
is not very common in day-to-day coding, but it's useful to know about. It can be used to explicitly remove references to objects, potentially allowing Python to free up memory.
Pay Attention to Common Variable Mistakes
When you're new to programming, watch out for these typical errors related to variables:
- Using a variable before assigning a value: You must use the
=
sign to give a variable its first value before you can use that variable's name in any operation. - Typos: Making a small spelling mistake in a variable name creates a completely new variable instead of using the one you intended.
- Forgetting Case Sensitivity: Remember that
myvar
,Myvar
, andmyVar
are all different variable names to Python. - Using a Keyword: Trying to use a reserved Python word like
if
orclass
as a variable name will stop your code from running.
Conclusion
Variables are fundamental: they are names that point to objects (values) in memory. Understanding variables, their types, how they are named, and how their values can change is crucial for writing any Python code.
Key takeaways:
- Variables are names pointing to objects (values).
- Objects have data types (
int
,float
,str
,bool
,None
, plus collections likelist
,dict
, etc.). - Objects can be mutable (changeable in place) or immutable (unchangeable).
- Variables can be reassigned (
=
) to point to different objects. - Variable scope determines where a variable name is recognized.
- Follow naming rules and conventions.
- Type annotations improve code clarity and help tools.
Variables are used everywhere. Understanding them well is the first big step. Practice is key!
Now that you understand how to store and name data using variables and objects of different types, the next step is to learn about the actions you can perform on that data using Operators.