Python Variables
Variables in Python are containers for storing data values. Unlike many other languages, Python has no command for declaring a variable — a variable is created the moment you first assign a value to it.
Creating Variables
# Variables are created on assignment
name = "Alice"
age = 25
height = 5.7
is_active = True
print(name) # Alice
print(age) # 25
print(height) # 5.7
print(is_active) # TruePython automatically determines the type based on the value assigned. No int, str, or other type keywords are needed.
Variable Assignment
Basic Assignment
x = 10
message = "Hello"
pi = 3.14159Multiple Assignment
# Assign the same value to multiple variables
a = b = c = 100
print(a, b, c) # 100 100 100
# Assign different values in one line
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# Swap variables (no temp variable needed!)
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10Unpacking Collections
# Unpack a list
colors = ["red", "green", "blue"]
r, g, b = colors
print(r) # red
# Unpack with * (catch remaining items)
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # [2, 3, 4]Variable Types
Python variables can hold any type, and can change types during execution:
x = 10 # int
x = "hello" # now it's a str
x = [1, 2, 3] # now it's a list
print(type(x)) # <class 'list'>Common Types
| Type | Example | Description |
|---|---|---|
int | x = 10 | Whole numbers |
float | x = 3.14 | Decimal numbers |
str | x = "hello" | Text strings |
bool | x = True | Boolean values |
list | x = [1, 2, 3] | Ordered, mutable collection |
tuple | x = (1, 2, 3) | Ordered, immutable collection |
dict | x = {"a": 1} | Key-value pairs |
set | x = {1, 2, 3} | Unordered, unique elements |
NoneType | x = None | Represents absence of value |
Type Casting
Convert between types using built-in functions:
# String to integer
age = int("25")
print(age + 5) # 30
# Integer to string
num = str(100)
print("Score: " + num) # Score: 100
# String to float
price = float("19.99")
print(price) # 19.99
# Float to integer (truncates)
x = int(3.99)
print(x) # 3
# To boolean
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("text")) # True
print(bool([])) # False
print(bool([1])) # TrueFalsy values in Python: 0, 0.0, "", [], (), {}, set(), None, False
Variable Scope
Local Variables
Variables created inside a function are local to that function:
def greet():
message = "Hello!" # Local variable
print(message)
greet() # Hello!
# print(message) # NameError: name 'message' is not definedGlobal Variables
Variables created outside functions are global:
name = "Alice" # Global variable
def greet():
print(f"Hello, {name}") # Can read global variables
greet() # Hello, AliceThe global Keyword
To modify a global variable inside a function:
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter) # 2The nonlocal Keyword
To modify a variable in an enclosing (non-global) scope:
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
inner()
print(count) # 2
outer()Constants
Python doesn't have true constants, but by convention, use UPPER_CASE names:
# Constants (by convention)
MAX_SIZE = 100
PI = 3.14159
DATABASE_URL = "postgresql://localhost/mydb"
API_KEY = "abc123"
# These CAN be changed (Python won't prevent it)
# but developers know they SHOULDN'T be changedConvention: Never modify a variable written in UPPER_SNAKE_CASE — treat it as a constant.
Deleting Variables
Use del to delete a variable:
x = 10
print(x) # 10
del x
# print(x) # NameError: name 'x' is not definedVariable Memory and Identity
Every object in Python has a unique ID. Use id() to see it:
a = 10
b = 10
print(id(a)) # e.g., 140234567890
print(id(b)) # Same as above! (Python caches small integers)
print(a is b) # True (same object)
c = [1, 2, 3]
d = [1, 2, 3]
print(c == d) # True (same value)
print(c is d) # False (different objects)
print(id(c) == id(d)) # FalseTip: Use == to compare values and is to compare identity (whether two variables point to the same object).
Complete Example
"""
Demonstrates Python variable concepts.
"""
# Constants
TAX_RATE = 0.08
STORE_NAME = "Python Shop"
def calculate_total(price, quantity):
"""Calculate total with tax."""
subtotal = price * quantity
tax = subtotal * TAX_RATE
total = subtotal + tax
return total, subtotal, tax
# Multiple assignment
item_name, item_price, item_qty = "Widget", 29.99, 3
# Unpacking return values
total, subtotal, tax = calculate_total(item_price, item_qty)
# Formatted output
print(f"{'=' * 30}")
print(f" {STORE_NAME}")
print(f"{'=' * 30}")
print(f" Item: {item_name}")
print(f" Price: ${item_price:.2f}")
print(f" Quantity: {item_qty}")
print(f" Subtotal: ${subtotal:.2f}")
print(f" Tax: ${tax:.2f}")
print(f" Total: ${total:.2f}")
print(f"{'=' * 30}")Output:
==============================
Python Shop
==============================
Item: Widget
Price: $29.99
Quantity: 3
Subtotal: $89.97
Tax: $7.20
Total: $97.17
==============================Summary
- Variables are created on assignment — no type declaration needed
- Python supports multiple assignment and unpacking
- Variables are dynamically typed — they can change type at any time
- Use type casting functions (
int(),str(),float(),bool()) to convert between types - Variables have scope: local, global, and nonlocal
- Use
UPPER_CASEfor constants (convention only, not enforced) - Use
==for value comparison andisfor identity comparison - Use
delto delete variables
Next, we'll explore Python's data types in detail.