Variables in Python

This introduction will cover the basics of variables, including how to create, assign, and use them, as well as some best practices for working with variables in Python.

What is a Variable?

A variable is a named location in memory that stores a value. This value can be of any data type, such as an integer, float, string, list, etc. Variables provide a way to label and store data so that it can be easily accessed and manipulated later in the program.

Creating and Assigning Variables

In Python, creating and assigning a variable is straightforward. You simply choose a name for the variable and use the assignment operator (=) to assign it a value. Unlike some other programming languages, you do not need to declare the variable’s type explicitly; Python infers the type based on the assigned value.


# Creating and assigning variables
x = 10         # Integer
y = 3.14       # Float
name = "Alice" # String
is_valid = True # Boolean

In this example, x is assigned the integer value 10, y is assigned the float value 3.14, name is assigned the string value "Alice", and is_valid is assigned the boolean value True.

Naming Conventions

When naming variables in Python, it’s important to follow certain conventions to make your code more readable and maintainable:

Use meaningful names: Choose names that clearly describe the variable’s purpose.

score = 100
player_name = "Bob"

Use lowercase letters: Variable names should be written in lowercase letters. Use underscores (_) to separate words.

total_cost = 250.75
is_active = False

Avoid using Python keywords: Keywords are reserved words in Python that have special meaning, such as if, else, while, for, def, etc.

# Incorrect
for = 10

# Correct
loop_count = 10

Start with a letter or underscore: Variable names must start with a letter (a-z, A-Z) or an underscore (_) and can be followed by letters, digits (0-9), or underscores.

_counter = 1
index2 = 5

Variable Scope

The scope of a variable determines where it can be accessed in the program. In Python, variables have either local or global scope.

Local Scope

A variable defined inside a function has local scope and can only be accessed within that function.


def greet():
    message = "Hello, World!"  # Local variable

# print(message)  # This will raise an error because message is not accessible outside the function

Global Scope

A variable defined outside any function has global scope and can be accessed anywhere in the code.


counter = 0  # Global variable

def increment():
    global counter
    counter += 1

print(counter)  # Output: 1

In this example, counter is a global variable, and the global keyword is used inside the function to modify its value.

Variable Reassignment

In Python, variables can be reassigned to new values at any time, even if the new value is of a different type.


x = 10
print(x)  # Output: 10

x = "Python"
print(x)  # Output: Python

x = [1, 2, 3]
print(x)  # Output: [1, 2, 3]

Here, the variable x is first assigned an integer value, then reassigned to a string, and finally reassigned to a list.

Multiple Assignment

Python allows you to assign multiple variables in a single line using multiple assignment.


a, b, c = 1, 2, 3
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

You can also use multiple assignment to swap values between variables without using a temporary variable.


x = 5
y = 10
x, y = y, x
print(x)  # Output: 10
print(y)  # Output: 5


Although Python does not have a built-in constant type, you can indicate that a variable is intended to be a constant by using all uppercase letters in its name. This is a convention and is not enforced by the Python interpreter.


PI = 3.14159

Best Practices for Variables

Use descriptive names: Choose variable names that clearly convey the purpose of the variable.

total_price = 150.75
user_age = 25

Keep it simple: Avoid overly complex or long variable names.

# Too complex
total_amount_of_items_in_the_cart = 5

# Simpler
item_count = 5

Be consistent: Follow naming conventions and be consistent in your code style.

Use comments: When necessary, use comments to explain the purpose of variables.

# The maximum number of allowed attempts
max_attempts = 3


Variables are a core concept in Python, providing a way to store and manipulate data within a program. Understanding how to create, assign, and use variables effectively is essential for writing clear, maintainable, and efficient Python code. By following best practices and conventions, you can make your code more readable and easier to understand for others, as well as for yourself when you return to it in the future.