Basic assignment

Variables store values. You don't need to declare types—Python figures it out:

# Assign values:
name = "Alice"
age = 30
height = 5.6
is_student = True

# Use variables:
print(name)  # "Alice"
print(age + 5)  # 35

Variable names

Rules for variable names:

  • Can contain letters, numbers, and underscores
  • Must start with a letter or underscore
  • Case-sensitive (name and Name are different)
  • Cannot use Python keywords (like if, for, def)
# Valid names:
user_name = "Alice"
user_age = 30
_private = "hidden"
name2 = "Bob"

# Invalid names:
# 2name = "Bob"  # Can't start with number
# user-name = "Alice"  # Can't use hyphens
# if = 5  # Can't use keyword

Multiple assignment

# Assign same value to multiple variables:
x = y = z = 0

# Assign different values:
a, b, c = 1, 2, 3

# Swap values:
x, y = 10, 20
x, y = y, x  # Now x=20, y=10

Reassignment

Variables can be reassigned to different types:

x = 10
print(x)  # 10

x = "Hello"
print(x)  # "Hello" (type changed)

Constants

Python doesn't have true constants, but convention uses UPPERCASE:

# Convention: uppercase for constants
PI = 3.14159
MAX_SIZE = 100

# But you can still change them (Python doesn't enforce it)
PI = 3.14  # Works, but not recommended