How to define a variable in Python

Learn how to define variables in Python. This guide covers various methods, tips, real-world examples, and how to debug common errors.

How to define a variable in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Variable definition is a fundamental skill in Python. It allows you to store and manage data within your code, making your programs dynamic and much easier to read and maintain.

In this article, we'll cover the essential techniques to define variables. You'll also find practical tips, see real-world applications, and get straightforward advice to debug common errors effectively.

Basic variable assignment

name = "John"
age = 30
print(f"Name: {name}, Age: {age}")--OUTPUT--Name: John, Age: 30

In Python, you assign values to variables using the equals sign (=). The example assigns the string "John" to the variable name and the integer 30 to age. Notice you don't have to declare the variable's type beforehand—Python infers it automatically. This is known as dynamic typing.

This approach keeps your code clean and flexible. Once defined, you can use these variables throughout your program, like in the print() function, which uses an f-string to display their stored values.

Basic variable definition techniques

Simple assignment is a great start, but you can write cleaner code by using different data types, assigning multiple variables, and following clear naming conventions.

Using different data types

integer_var = 10
float_var = 3.14
string_var = "Hello"
boolean_var = True
print(type(integer_var), type(float_var), type(string_var), type(boolean_var))--OUTPUT--<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

Python handles various data types, each serving a specific purpose. The code demonstrates four fundamental types, and you can use the built-in type() function to inspect a variable and confirm its type—a handy trick for debugging. For more complex data structures, you might need to learn about creating dictionaries in Python.

  • int: For whole numbers like 10.
  • float: For decimal numbers like 3.14.
  • str: For text enclosed in quotes, such as "Hello".
  • bool: For truth values, represented by True or False.

Multiple variable assignment

x, y, z = 1, 2.5, "Python"
a = b = c = 100
print(f"x={x}, y={y}, z={z}")
print(f"a={a}, b={b}, c={c}")--OUTPUT--x=1, y=2.5, z=Python
a=100, b=100, c=100

Python provides concise ways to assign multiple variables at once, which can make your code cleaner and more readable. These techniques are especially useful for initializing several variables without clutter.

  • Unpacking values: You can assign different values to multiple variables in a single line, like x, y, z = 1, 2.5, "Python". Python matches each variable to its corresponding value in the sequence.
  • Chained assignment: To give multiple variables the exact same value, you can chain them together. The line a = b = c = 100 assigns the integer 100 to all three variables.

Variable naming conventions

user_name = "alice" # snake_case (recommended)
UserAge = 25 # PascalCase
isActive = True # camelCase
_private_var = "secret" # starting with underscore
print(user_name, UserAge, isActive, _private_var)--OUTPUT--alice 25 True secret

Choosing a consistent naming style is crucial for readable code. While Python allows various formats, the official style guide recommends snake_case for variables and functions, which is why user_name is the preferred approach.

  • PascalCase is typically used for class names, not variables.
  • camelCase, while valid, is less common in the Python community.
  • A single leading underscore, like in _private_var, is a convention that tells other developers a variable is intended for internal use.

Advanced variable concepts

Now that you have the fundamentals down, you can write more robust code by using type hints, managing variable scope, and defining constants.

Type hinting with variables

from typing import List, Dict, Union

name: str = "Alice"
age: int = 30
scores: List[int] = [95, 87, 92]
user: Dict[str, Union[str, int]] = {"name": "Bob", "age": 25}
print(f"{name}: {age}, Scores: {scores}")--OUTPUT--Alice: 30, Scores: [95, 87, 92]

While Python is dynamically typed, you can add optional type hints to improve code clarity. These hints don't change how your code runs, but they help static analysis tools and other developers understand what kind of data a variable should hold. You can hint basic types like name: str or more complex ones from the typing module. For rapid prototyping where you want to focus on logic rather than syntax details, vibe coding can help you build applications using natural language descriptions.

  • List[int] specifies a list containing only integers.
  • Dict[str, Union[str, int]] defines a dictionary with string keys and values that can be either a string or an integer.

Using global and local variables

global_var = "I'm global"

def show_variables():
local_var = "I'm local"
print(global_var)
print(local_var)

show_variables()
print(global_var)--OUTPUT--I'm global
I'm local
I'm global

A variable's scope determines where it can be accessed. The variable global_var is defined outside the function, making it accessible everywhere. In contrast, local_var is created inside show_variables() and only exists within that function's scope. For comprehensive guidance on defining global variables in Python, you can learn about proper usage patterns and scope management.

  • Global variables: Defined in the main body of a script, you can read them from any scope, including inside functions.
  • Local variables: Defined inside a function, they are only accessible within that function and are destroyed once it finishes running.

Using constants and immutable variables

import enum

PI = 3.14159 # Convention for constants (uppercase)

class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3

print(f"PI: {PI}, Red value: {Color.RED.value}")--OUTPUT--PI: 3.14159, Red value: 1

Python doesn't have true constants, but you can signal that a variable's value shouldn't change by naming it in all uppercase, like PI. This is a widely followed convention that helps keep your code predictable. For more detailed guidance on defining constants in Python, you can explore additional approaches and best practices. For a more robust approach, you can use enumerations.

  • The enum module lets you create groups of related, unchangeable names, such as Color.RED.
  • Unlike the uppercase convention, Enum members are truly immutable and cannot be reassigned, which prevents accidental modifications.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you focus on building, not just learning isolated techniques.

With Agent 4, you can go from an idea to a working product much faster. Describe what you want to build, and the Agent handles the code, databases, APIs, and deployment. Instead of just practicing with variables, you could build:

  • A simple metric converter that takes a numerical value and its unit to convert it to another system.
  • A user profile generator that organizes a person's name, age, and active status into a structured dictionary.
  • A data dashboard that reads a list of sales figures and calculates key statistics like the total and average.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with the basics down, you might run into a few common pitfalls when defining and using variables in Python.

You can read a global variable from within a function, but trying to modify it without the right keyword will cause an UnboundLocalError. This happens because any assignment inside a function creates a new local variable by default, shadowing the global one. To avoid this, declare the variable with the global keyword at the start of your function to signal your intent to modify the one in the global scope.

Using a mutable object like a list as a default argument is a classic trap. Python evaluates default arguments only once—when the function is defined—so any modifications persist across calls. The best practice is to use None as the default and create a new object inside the function if needed, ensuring each call starts fresh.

When you assign a list to a new variable with new_list = old_list, you're not making a copy; you're just creating another name for the same list. Modifying one will change the other, which can cause unexpected behavior. To create a truly independent copy, use the .copy() method or a full slice like original_list[:].

Forgetting to use global when modifying variables

It's a common mistake to modify a global variable inside a function without explicitly telling Python your intent. When you use an operator like +=, Python tries to create a new local variable, which leads to an error. See what happens in this example.

counter = 0

def increment_counter():
counter += 1 # This will cause an UnboundLocalError
return counter

print(increment_counter())

The += operator tries to both read from and assign to counter. Since the assignment happens inside the increment_counter() function, Python assumes counter is a local variable and raises an error because it’s read before being assigned. The corrected code below shows how to fix this.

counter = 0

def increment_counter():
global counter
counter += 1
return counter

print(increment_counter())

By adding global counter at the start of the increment_counter() function, you explicitly tell Python to modify the variable from the global scope. This prevents it from creating a new local variable, which was the source of the UnboundLocalError.

You'll need to do this whenever you change a global variable's value from inside a function, especially with operators like += that both read and write data. It's common when managing state that lives outside a function, like a simple counter or a configuration flag.

Using mutable objects as default arguments

Using a mutable object like a list as a default argument can cause tricky bugs. Python creates the default list only once, so each function call modifies the same object instead of creating a new one. The code below demonstrates this problem.

def add_item(item, inventory=[]):
inventory.append(item)
return inventory

print(add_item("sword"))
print(add_item("shield")) # Both items end up in the same inventory

The add_item function reuses the same default inventory list. This is why the second call adds "shield" to the list that already contains "sword." The corrected code below shows how to prevent this behavior.

def add_item(item, inventory=None):
if inventory is None:
inventory = []
inventory.append(item)
return inventory

print(add_item("sword"))
print(add_item("shield")) # Creates separate inventories

The corrected add_item function solves the problem by setting the default argument to None. Inside the function, a check—if inventory is None—creates a new empty list only when needed. This simple pattern guarantees that each function call operates on a separate list, preventing shared state bugs. You should always use this approach when a function's default argument is a mutable type like a list or dictionary. Proper memory management practices like this help prevent larger issues in production applications.

Modifying lists through multiple references

Assigning a list to another variable with = doesn't create a copy; it just creates a second name for the same list. This means a change made through one variable will affect the other, which can be surprising. See this in action below.

original = [1, 2, 3]
duplicate = original
duplicate.append(4)
print(f"Original: {original}, Duplicate: {duplicate}")

The assignment operator (=) makes duplicate a reference, not a copy. Modifying it affects the original list because they point to the same data. The corrected code below shows how to create an independent copy.

original = [1, 2, 3]
duplicate = original.copy()
duplicate.append(4)
print(f"Original: {original}, Duplicate: {duplicate}")

The corrected code uses the .copy() method to create a shallow copy of the original list. This ensures that duplicate is a completely new list, not just another reference. Now, when you append an item to duplicate, the original list remains unchanged. You should use this technique whenever you need to modify a list while preserving the original data, such as when filtering or transforming data sets. For more comprehensive guidance on copying lists in Python, you can explore different copying methods and their use cases.

Real-world applications

With the theory and common errors covered, you can now see how these concepts translate into practical, real-world applications.

Calculating inventory value with the * operator

You can perform arithmetic operations directly on variables, such as using the multiplication operator (*) to calculate the total value of an inventory item from its price and stock quantity.

product_name = "Laptop"
stock_quantity = 15
price = 899.99
inventory_value = stock_quantity * price
print(f"Product: {product_name}")
print(f"Total inventory value: ${inventory_value:.2f}")

This example demonstrates how variables work together to produce meaningful results. Notice how Python handles the operation between an integer, stock_quantity, and a float, price, without any issues.

  • The result is stored in a new variable, inventory_value.
  • The final output uses an f-string with the format specifier :.2f to present the total as a currency value, neatly rounded to two decimal places. This is a practical way to manage financial data.

Processing user data with dictionary variables

You can combine dictionaries into a list to manage collections of structured records, such as user data, and then easily process them to extract insights.

users = [
{"name": "Alice", "age": 28, "premium": True},
{"name": "Bob", "age": 35, "premium": False},
{"name": "Charlie", "age": 22, "premium": True}
]

total_age = 0
premium_count = 0
for user in users:
total_age += user["age"]
if user["premium"]:
premium_count += 1

avg_age = total_age / len(users)
print(f"Average user age: {avg_age:.1f}")
print(f"Number of premium users: {premium_count}")

This code processes a list of user dictionaries to gather key metrics. It starts by setting up two variables, total_age and premium_count, to act as counters.

  • The for loop iterates through each user, pulling the value from user["age"] to update the total age.
  • It also checks if the premium key is True and, if so, increments the premium_count. For more detailed techniques on accessing dictionary data in Python, you can explore different methods and best practices.

Once the loop finishes, it calculates the average age by dividing the total by the list length, found with len(users), before printing the results.

Get started with Replit

Put your knowledge into practice by building a real tool. Just tell Replit Agent: "Build a tip calculator" or "Create a script that organizes user data into dictionaries."

The Agent translates your instructions into code, tests for bugs, and deploys the app for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.