Python Variables

In Python programming, a variable is a named location in memory that is used to store data. You can think of it as a labeled box in which you can place a value. This allows you to store information that can be referenced and manipulated later in your program.
When you create a variable, you are allocating space in your computer’s RAM (Random Access Memory) to hold a specific value. This means that the variable acts as a pointer to that location in memory, making it easier to manage and utilize data throughout your code.
How to Declare a Variable
Simple Declaration
Declaring a variable in Python is simple. You assign a value to a variable name using the =
operator.
Example of Variable Declaration
# Declaring a variable
age = 25
In this example, we’ve created a variable named age
and assigned it the value 25
. This means that the computer reserves space in RAM for the variable age
, which now holds the integer value 25
.

Assignment
Assignment refers to the process of updating or changing the value of a variable. You can reassign a new value to the same variable at any time.
# Assigning a new value to the variable
age = 30 # Now, age holds the value 30

Types of Variables
Variables in Python can store different types of data, and it’s important to understand these types. The type of a variable defines what kind of data it can hold and how it can be used. Here are the various variable types in Python:
Variable Type | Description | Example |
---|---|---|
Integer | Whole numbers without decimals | x = 10 |
Float | Numbers with decimals | y = 10.5 |
String | Text data enclosed in quotes | name = "Alice" |
Boolean | Represents True or False | is_active = True |
List | Ordered collection of items | items = [1, 2, 3] |
Tuple | Immutable ordered collection | coordinates = (10, 20) |
Dictionary | Key-value pairs | person = {"name": "John", "age": 30} |
Types of Variables
Variables in Python can store different types of data, and it’s important to understand these types. The type of a variable defines what kind of data it can hold and how it can be used. Here are the various variable types in Python:
- Data Management: Different types of variables can be used for different purposes, allowing for efficient data handling.
- Error Prevention: Knowing variable types helps prevent mistakes (e.g., trying to perform arithmetic operations on strings).
- Code Clarity: Clear types make your code easier to read and maintain.
Examples of Variable Types and Type Checking
Let’s declare variables with different types, use the type()
function to check their types, and print both their values and types.
# Different types of variables
age = 25 # Integer
height = 5.9 # Float
name = "Alice" # String
is_student = True # Boolean
hobbies = ["reading", "gaming"] # List
coordinates = (10, 20) # Tuple
profile = {"name": "Bob", "age": 22} # Dictionary
# Print value and type of each variable
print("Value:", age, "| Type:", type(age))
print("Value:", height, "| Type:", type(height))
print("Value:", name, "| Type:", type(name))
print("Value:", is_student, "| Type:", type(is_student))
print("Value:", hobbies, "| Type:", type(hobbies))
print("Value:", coordinates, "| Type:", type(coordinates))
print("Value:", profile, "| Type:", type(profile))
Expected Output:
Value: 25 | Type: <class 'int'>
Value: 5.9 | Type: <class 'float'>
Value: Alice | Type: <class 'str'>
Value: True | Type: <class 'bool'>
Value: ['reading', 'gaming'] | Type: <class 'list'>
Value: (10, 20) | Type: <class 'tuple'>
Value: {'name': 'Bob', 'age': 22} | Type: <class 'dict'>

Naming Rules for Variables
When creating variables in Python, it’s important to follow some basic rules to avoid syntax errors and keep your code readable:
- Start with a letter or an underscore (
_
)- Variable names cannot begin with a number.
- Avoid using special characters or spaces
- Use underscores (
_
) instead of spaces (e.g.,student_age
, notstudent age
).
- Use underscores (
- Be case-sensitive
- Python treats
Name
,name
, andNAME
as three different variables.
- Python treats
- Don’t use reserved words
- Avoid naming your variables with Python keywords like
class
,if
, orreturn
.
- Avoid naming your variables with Python keywords like
Examples of valid variable names:
username = "john_doe"
_totalMarks = 88
isLoggedIn = True
# Print valid variables
print(username) # Output: john_doe
print(_totalMarks) # Output: 88
print(isLoggedIn) # Output: True
Examples of invalid names:
2score = 95 # ✖️ Starts with a number
user name = "Ali" # ✖️ Contains a space
def = "function" # ✖️Uses a reserved keyword
Reassigning Variables in Python
In Python, variables are dynamic meaning you can reassign them at any time, even to a different type of value.
# Initial assignment
status = "active" # String
# Reassigning a new value
status = False # Now it's a Boolean
Deleting Variables
Sometimes, you may want to remove a variable entirely to free up memory or clean up your namespace. You can do this using the del
statement.
score = 100
print(score) # Output: 100
del score # Deletes the variable
print(score) # NameError: name 'score' is not defined
How It Works (Conceptual Understanding)
- Application Level: When you define a variable, you’re creating an identifier that refers to a specific piece of data.
- Python Interpreter: The interpreter allocates a section of memory in RAM for this variable and stores the value you’ve assigned to it.
- Binary/OS Level: At the lowest level, those values are stored in binary format in the allocated memory space, which the operating system uses to run your program efficiently.
Best Practices for Variables
- Use Descriptive Names: Choose variable names that indicate their purpose (e.g.,
student_age
,height_cm
). - Consistency: Follow a consistent naming convention, like
snake_case
orcamelCase
. - Avoid Global Variables: Limit the use of global variables to make your code modular and easier to manage.
Practice Tasks
Task 1: Create Your Own Variables
- Define variables to store your favorite movie title (string), your age (integer), and whether you have a pet (boolean).
- Print out these variables along with their types using the
type()
function.
Task 2: Update Variable Values
- Start with a variable named
books_read
, initialized to5
. - Change its value to
10
later in the code, and print the updated value along with its type.
Guidance
As you work on these tasks, focus on choosing meaningful names for your variables, and try to play around with different types. Observe how changing the type of a variable affects your program.
Motivation
Try the tasks and share your answers in the comments to get appreciated! Happy coding with variables!