Last modified: May 29, 2026

Python Variables: A Complete Guide

Variables are essential in Python. They store data for your program. Think of them as labeled boxes. You put data inside. You use the label to get it back. This guide covers different variables in Python. It is for beginners and experts alike.

Python is dynamic. You do not need to declare a variable's type. The interpreter figures it out. This makes coding fast. But it also requires care. Let's explore how variables work.

What is a Variable in Python?

A variable is a name that refers to a value. You assign a value using the = sign. For example:


# Assigning a value to a variable
name = "Alice"
age = 25
pi = 3.14

Here, name, age, and pi are variables. They hold a string, an integer, and a float. Python knows their types automatically.

Variables can change. You can reassign them to a new value. Even to a different type. This is called dynamic typing.

Variable Naming Rules

Python has strict rules for variable names. Follow them to avoid errors.

  • Names must start with a letter or underscore. Not a number.
  • They can only contain letters, numbers, and underscores.
  • Names are case-sensitive. age and Age are different.
  • You cannot use Python keywords like if, for, or while.

Good names make code readable. Use user_age instead of ua. Use total_price instead of tp.


# Good variable names
first_name = "Bob"
student_count = 30
is_active = True

# Bad variable names
1st_name = "Bob"   # SyntaxError
my-var = 10        # SyntaxError

Types of Variables in Python

Python has many data types. Each type is a class. Variables are instances of these classes. Here are the common ones.

Numeric Types

Numbers are everywhere. Python supports integers, floats, and complex numbers.


# Integer
count = 10

# Float
price = 19.99

# Complex
z = 2 + 3j

Integers are whole numbers. Floats have decimals. Complex numbers have real and imaginary parts. Use them for math and science.

String Type

Strings hold text. Use single or double quotes.


greeting = "Hello"
name = 'World'
message = f"{greeting}, {name}!"

Strings support many methods. You can join, split, and format them. They are immutable. You cannot change them after creation.

Boolean Type

Booleans represent truth values. They are True or False.


is_ready = True
is_done = False

if is_ready:
    print("Let's go!")

Booleans are used in conditions. They control program flow. They come from comparisons like 5 > 3.

List Type

Lists hold multiple items. They are ordered and mutable. You can change them.


fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

Lists use square brackets. They can hold different types. They are great for collections.

Tuple Type

Tuples are like lists but immutable. You cannot change them after creation.


coordinates = (10, 20)
print(coordinates[0])  # Output: 10
# coordinates[0] = 15  # This would raise an error

Tuples use parentheses. They are faster than lists. Use them for fixed data.

Dictionary Type

Dictionaries store key-value pairs. They are unordered and mutable.


person = {"name": "Alice", "age": 30}
print(person["name"])  # Output: Alice
person["city"] = "New York"

Dictionaries use curly braces. Keys must be unique. They are great for structured data.

Set Type

Sets hold unique items. They are unordered and mutable.


unique_numbers = {1, 2, 3, 3, 2}
print(unique_numbers)  # Output: {1, 2, 3}

Sets remove duplicates. They support math operations like union and intersection.

Variable Assignment and Reassignment

You assign a value once. You can reassign it later. This changes the variable's value and type.


x = 10        # x is an integer
x = "hello"   # x is now a string
print(x)      # Output: hello

This is powerful. But be careful. It can lead to bugs if you expect a specific type. Use type hints to clarify.

Multiple Assignment

Python lets you assign multiple variables in one line. It saves time.


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

You can also swap values easily.


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

This is clean and readable. It avoids temporary variables.

Variable Scope

Scope determines where a variable is accessible. Python has local and global scope.

Local variables exist inside functions. Global variables exist at the top level.


global_var = "I am global"

def my_function():
    local_var = "I am local"
    print(global_var)  # Accessible
    print(local_var)   # Accessible

print(global_var)      # Accessible
# print(local_var)     # This would raise an error

Use global keyword to modify a global variable inside a function. But avoid it. It makes code hard to debug.

Type Conversion

Sometimes you need to change a variable's type. Python provides built-in functions for this.


num_str = "123"
num_int = int(num_str)
print(num_int + 1)  # Output: 124

pi_str = "3.14"
pi_float = float(pi_str)
print(pi_float * 2)  # Output: 6.28

Common conversion functions are int(), float(), str(), and bool(). Use them carefully. Invalid conversions raise errors.

Best Practices for Variables

Follow these tips for clean code.

  • Use descriptive names. user_count is better than uc.
  • Use snake_case for multi-word names. Python style guide recommends it.
  • Avoid single-letter names except in loops. i is fine for a loop counter.
  • Keep variables in the smallest scope possible. Avoid global variables.
  • Initialize variables before use. This prevents NameError.

Good habits make your code easier to read and maintain.

Common Errors with Variables

Beginners often make mistakes. Here are some and how to fix them.

  • NameError: You used a variable that doesn't exist. Check spelling and scope.
  • TypeError: You tried an operation on the wrong type. Convert types first.
  • SyntaxError: You broke a naming rule. Use only letters, numbers, and underscores.

Debugging is part of learning. Read error messages carefully. They tell you what's wrong.

Conclusion

Variables are the foundation of Python programming. They store data and make your code dynamic. You learned about different types, naming rules, and scope. You also saw how to assign and convert values.

Practice using variables in small programs. Experiment with different types. Soon, they will feel natural. For more on variables in other languages, check our guide on JavaScript Variables Guide. If you want to compare with JavaScript, see Types of JavaScript Variables. And for practical examples, visit JavaScript Variables Examples.

Keep coding. Keep learning. Python variables are your first step to mastery.