Variables & Data Types
📖 Concept
In Python, everything is an object. Variables are simply names that reference objects in memory — they don't "contain" values like boxes; they're more like labels or sticky notes pointing to objects.
Variable assignment:
x = 42 # x points to an int object with value 42
y = x # y points to the SAME object (not a copy)
x = "hello" # x now points to a new str object; y still points to 42
Naming conventions (PEP 8):
| Style | Used For | Example |
|---|---|---|
snake_case |
Variables, functions, methods | user_name, get_total() |
PascalCase |
Classes | UserProfile, HttpClient |
UPPER_SNAKE |
Constants | MAX_RETRIES, API_KEY |
_leading_underscore |
Internal/private | _helper(), _cache |
__dunder__ |
Magic methods | __init__, __str__ |
Built-in data types:
| Type | Category | Example | Mutable? |
|---|---|---|---|
int |
Numeric | 42, 0xFF, 1_000_000 |
No |
float |
Numeric | 3.14, 1e-5, float('inf') |
No |
complex |
Numeric | 3+4j |
No |
bool |
Boolean | True, False |
No |
str |
Text | "hello", 'world' |
No |
NoneType |
Null | None |
No |
list |
Sequence | [1, 2, 3] |
Yes |
tuple |
Sequence | (1, 2, 3) |
No |
dict |
Mapping | {"a": 1} |
Yes |
set |
Set | {1, 2, 3} |
Yes |
Mutability is a critical concept: immutable objects (int, str, tuple) cannot be changed after creation. Mutable objects (list, dict, set) can be modified in-place.
💻 Code Example
1# ============================================================2# Variables are references (labels), not boxes3# ============================================================4a = [1, 2, 3]5b = a # b points to the SAME list object6b.append(4)7print(a) # [1, 2, 3, 4] — a is also modified!8print(a is b) # True — same object in memory9print(id(a), id(b)) # Same memory address1011# To make a copy:12c = a.copy() # Shallow copy — new list, same elements13c.append(5)14print(a) # [1, 2, 3, 4] — a is NOT affected15print(a is c) # False — different objects1617# ============================================================18# Numeric types19# ============================================================20# Integers have unlimited precision in Python!21big_num = 10 ** 100 # No overflow!22print(big_num) # A googol2324# Readable large numbers with underscores25population = 7_900_000_00026budget = 1_500_000.502728# Different bases29hex_val = 0xFF # 255 in hexadecimal30oct_val = 0o77 # 63 in octal31bin_val = 0b1010 # 10 in binary3233# Float precision gotcha34print(0.1 + 0.2) # 0.3000000000000000435print(0.1 + 0.2 == 0.3) # False!3637# Use decimal for financial calculations38from decimal import Decimal39print(Decimal('0.1') + Decimal('0.2')) # 0.3 (exact)40print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3')) # True4142# ============================================================43# Boolean values and truthiness44# ============================================================45# False values (falsy):46print(bool(0)) # False47print(bool(0.0)) # False48print(bool("")) # False49print(bool([])) # False50print(bool({})) # False51print(bool(None)) # False5253# Everything else is truthy:54print(bool(1)) # True55print(bool(-1)) # True — any non-zero number56print(bool("hello")) # True — any non-empty string57print(bool([0])) # True — non-empty list (even if contains falsy)5859# ============================================================60# String types61# ============================================================62single = 'hello'63double = "hello"64triple = """Multi-line65string that preserves66line breaks"""6768# f-strings (Python 3.6+) — the preferred way to format strings69name = "Alice"70age = 3071print(f"Name: {name}, Age: {age}")72print(f"Next year: {age + 1}") # Expressions in f-strings73print(f"Name uppercase: {name.upper()}") # Method calls74print(f"{42:08b}") # Format spec: binary with padding7576# Raw strings — no escape processing77path = r"C:\Users\alice\docs" # Backslashes are literal78print(path) # C:\Users\alice\docs7980# ============================================================81# None — Python's null82# ============================================================83result = None84print(result is None) # True — always use 'is' for None checks85print(result is not None) # False86print(type(result)) # <class 'NoneType'>8788# BAD: if result == None (works but not Pythonic)89# GOOD: if result is None (identity check, faster and correct)9091# ============================================================92# Type checking and conversion93# ============================================================94x = "42"95print(type(x)) # <class 'str'>96print(isinstance(x, str)) # True9798# Type conversion99num = int("42") # str -> int100flt = float("3.14") # str -> float101s = str(42) # int -> str102b = bool(1) # int -> bool103104# Multiple assignment105a, b, c = 1, 2, 3106x = y = z = 0 # All point to same object107108# Swap variables (Pythonic way)109a, b = b, a # No temp variable needed!
🏋️ Practice Exercise
Exercises:
Create variables of every built-in type (int, float, complex, bool, str, None, list, tuple, dict, set). Print each with
type()andid().Demonstrate the difference between mutable and immutable types: create a list and a tuple, try to modify both, and explain the behavior.
Write code that shows the "variable as label" concept: assign a list to two variables, modify through one, and show the effect on the other. Then show how to properly copy.
Explore float precision: demonstrate why
0.1 + 0.2 != 0.3and show two different ways to handle this (usingdecimal.Decimalandmath.isclose).Write a function
describe_value(x)that prints the type, truthiness (bool(x)), and whether it's mutable or immutable for any given value.Practice f-string formatting: display a number as currency (
$1,234.56), as a percentage (85.5%), in scientific notation, and right-aligned in a 20-character field.
⚠️ Common Mistakes
Using
==instead ofisto check forNone. Always usex is Noneorx is not None— it's faster and semantically correct (identity vs equality).Forgetting that
0.1 + 0.2 != 0.3due to floating-point representation. Usedecimal.Decimalfor financial calculations ormath.isclose()for comparisons.Thinking
a = bcopies the value for mutable types. It creates another reference to the same object. Use.copy(),list(), orcopy.deepcopy()for actual copies.Using mutable default arguments in functions:
def f(x=[])— the default list is shared across all calls. Usedef f(x=None): x = x or []instead.Not knowing about Python's integer caching:
a = 256; b = 256; a is bis True (cached), buta = 257; b = 257; a is bmay be False (not cached). Always use==for value comparison.
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Variables & Data Types