Python Basics

Python Variables

Learn how variables work in Python, including assignment, multiple assignment, type casting, scope, and best practices.

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

python
# 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) # True

Python automatically determines the type based on the value assigned. No int, str, or other type keywords are needed.


Variable Assignment

Basic Assignment

python
x = 10
message = "Hello"
pi = 3.14159

Multiple Assignment

python
# 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 10

Unpacking Collections

python
# 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:

python
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

TypeExampleDescription
intx = 10Whole numbers
floatx = 3.14Decimal numbers
strx = "hello"Text strings
boolx = TrueBoolean values
listx = [1, 2, 3]Ordered, mutable collection
tuplex = (1, 2, 3)Ordered, immutable collection
dictx = {"a": 1}Key-value pairs
setx = {1, 2, 3}Unordered, unique elements
NoneTypex = NoneRepresents absence of value

Type Casting

Convert between types using built-in functions:

python
# 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]))    # True

Falsy values in Python: 0, 0.0, "", [], (), {}, set(), None, False


Variable Scope

Local Variables

Variables created inside a function are local to that function:

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

greet()        # Hello!
# print(message)  # NameError: name 'message' is not defined

Global Variables

Variables created outside functions are global:

python
name = "Alice"  # Global variable

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

greet()  # Hello, Alice

The global Keyword

To modify a global variable inside a function:

python
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)  # 2

The nonlocal Keyword

To modify a variable in an enclosing (non-global) scope:

python
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:

python
# 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 changed

Convention: Never modify a variable written in UPPER_SNAKE_CASE — treat it as a constant.


Deleting Variables

Use del to delete a variable:

python
x = 10
print(x)  # 10

del x
# print(x)  # NameError: name 'x' is not defined

Variable Memory and Identity

Every object in Python has a unique ID. Use id() to see it:

python
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))  # False

Tip: Use == to compare values and is to compare identity (whether two variables point to the same object).


Complete Example

python
"""
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_CASE for constants (convention only, not enforced)
  • Use == for value comparison and is for identity comparison
  • Use del to delete variables

Next, we'll explore Python's data types in detail.