</>
Skip to content
Python lessons (6/45)

Python — Variables

What are Variables?

Variables store data values. In Python, you don't need to declare the type — Python figures it out automatically:

name = "Alice"      # string
age = 25            # integer
height = 5.7        # float
is_student = True   # boolean

Creating Variables

# Assignment
x = 10
name = "Bob"
pi = 3.14159

# Multiple assignment
a, b, c = 1, 2, 3

# Same value to multiple variables
x = y = z = 0

# Unpacking a list
coordinates = [10, 20, 30]
x, y, z = coordinates

Naming Rules

# Valid names
first_name = "Alice"    # snake_case (Python convention)
_private = True         # underscore prefix
MAX_SIZE = 100          # UPPER_CASE for constants
count2 = 5              # can contain numbers

# Invalid names
# 2count = 5            # can't start with number
# my-name = "Bob"       # no hyphens
# class = "Math"        # can't use reserved words

Rules:

  • Start with a letter or underscore
  • Letters, numbers, and underscores only
  • Case-sensitive (name ≠ Name)
  • Use snake_case for variables, UPPER_CASE for constants

Dynamic Typing

Python figures out the type automatically:

x = 10          # x is int
x = "hello"     # x is now string (reassigned)
x = [1, 2, 3]  # x is now list

# Check type
type(x)         # <class 'list'>
isinstance(x, list)  # True

Variable Scope

Local Variables

Created inside a function — only accessible there:

def greet():
    message = "Hello!"  # local variable
    print(message)

greet()    # works
# print(message)  # Error: name not defined

Global Variables

Created outside functions — accessible everywhere:

name = "Alice"  # global

def greet():
    print(f"Hello, {name}")  # can read global

greet()  # Hello, Alice

Modifying Global Variables

count = 0

def increment():
    global count  # declare intent to modify
    count += 1

increment()
print(count)  # 1

Variable Reassignment

x = 5
print(x)   # 5

x = 10
print(x)   # 10

# Python variables can change type
x = "hello"
print(x)   # hello

Multiple Assignment Patterns

# Swap values
a, b = 1, 2
a, b = b, a  # a = 2, b = 1

# Unpack strings
first, *rest = "hello"
# first = 'h', rest = ['e', 'l', 'l', 'o']

# Underscore for unused values
_, second, _ = (1, 2, 3)  # second = 2

Type Hints (Optional)

Python supports optional type hints for clarity:

name: str = "Alice"
age: int = 25
height: float = 5.7
active: bool = True

def greet(name: str) -> str:
    return f"Hello, {name}!"

Best Practices

  • Use descriptive names (user_age, not ua)
  • Use snake_case for variables, UPPER_CASE for constants
  • Avoid single-letter names except in loops (i, j, x)
  • Initialize variables before using them
  • Use type hints for function signatures
  • Don't use Python built-in names (list, str, int, type)

Common Mistakes

# Forgetting quotes
# message = Hello    # Error: name not defined
message = "Hello"    # Correct

# Confusing assignment and comparison
# if x = 5:          # Error
if x == 5:           # Correct

# Shadowing built-ins
# list = [1, 2, 3]   # Bad: shadows list()
my_list = [1, 2, 3]  # Good

Mini Practice

  1. Create variables of different types and print them
  2. Swap two variables without a temporary variable
  3. Write a function with type hints
  4. Practice variable scope with local and global variables
  5. Create a simple calculator using variables

Up Next

Next: Data Types →

Related Topics

Frequently Asked Questions about Variables

What is Variables in Python?

Variables is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in Python?

Variables is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.