Variables & Data Types

0/4 in this phase0/54 across the roadmap

📖 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

codeTap to expand ⛶
1# ============================================================
2# Variables are references (labels), not boxes
3# ============================================================
4a = [1, 2, 3]
5b = a # b points to the SAME list object
6b.append(4)
7print(a) # [1, 2, 3, 4] — a is also modified!
8print(a is b) # True — same object in memory
9print(id(a), id(b)) # Same memory address
10
11# To make a copy:
12c = a.copy() # Shallow copy — new list, same elements
13c.append(5)
14print(a) # [1, 2, 3, 4] — a is NOT affected
15print(a is c) # False — different objects
16
17# ============================================================
18# Numeric types
19# ============================================================
20# Integers have unlimited precision in Python!
21big_num = 10 ** 100 # No overflow!
22print(big_num) # A googol
23
24# Readable large numbers with underscores
25population = 7_900_000_000
26budget = 1_500_000.50
27
28# Different bases
29hex_val = 0xFF # 255 in hexadecimal
30oct_val = 0o77 # 63 in octal
31bin_val = 0b1010 # 10 in binary
32
33# Float precision gotcha
34print(0.1 + 0.2) # 0.30000000000000004
35print(0.1 + 0.2 == 0.3) # False!
36
37# Use decimal for financial calculations
38from decimal import Decimal
39print(Decimal('0.1') + Decimal('0.2')) # 0.3 (exact)
40print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3')) # True
41
42# ============================================================
43# Boolean values and truthiness
44# ============================================================
45# False values (falsy):
46print(bool(0)) # False
47print(bool(0.0)) # False
48print(bool("")) # False
49print(bool([])) # False
50print(bool({})) # False
51print(bool(None)) # False
52
53# Everything else is truthy:
54print(bool(1)) # True
55print(bool(-1)) # True — any non-zero number
56print(bool("hello")) # True — any non-empty string
57print(bool([0])) # True — non-empty list (even if contains falsy)
58
59# ============================================================
60# String types
61# ============================================================
62single = 'hello'
63double = "hello"
64triple = """Multi-line
65string that preserves
66line breaks"""
67
68# f-strings (Python 3.6+) — the preferred way to format strings
69name = "Alice"
70age = 30
71print(f"Name: {name}, Age: {age}")
72print(f"Next year: {age + 1}") # Expressions in f-strings
73print(f"Name uppercase: {name.upper()}") # Method calls
74print(f"{42:08b}") # Format spec: binary with padding
75
76# Raw strings — no escape processing
77path = r"C:\Users\alice\docs" # Backslashes are literal
78print(path) # C:\Users\alice\docs
79
80# ============================================================
81# NonePython's null
82# ============================================================
83result = None
84print(result is None) # True — always use 'is' for None checks
85print(result is not None) # False
86print(type(result)) # <class 'NoneType'>
87
88# BAD: if result == None (works but not Pythonic)
89# GOOD: if result is None (identity check, faster and correct)
90
91# ============================================================
92# Type checking and conversion
93# ============================================================
94x = "42"
95print(type(x)) # <class 'str'>
96print(isinstance(x, str)) # True
97
98# Type conversion
99num = int("42") # str -> int
100flt = float("3.14") # str -> float
101s = str(42) # int -> str
102b = bool(1) # int -> bool
103
104# Multiple assignment
105a, b, c = 1, 2, 3
106x = y = z = 0 # All point to same object
107
108# Swap variables (Pythonic way)
109a, b = b, a # No temp variable needed!

🏋️ Practice Exercise

Exercises:

  1. Create variables of every built-in type (int, float, complex, bool, str, None, list, tuple, dict, set). Print each with type() and id().

  2. Demonstrate the difference between mutable and immutable types: create a list and a tuple, try to modify both, and explain the behavior.

  3. 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.

  4. Explore float precision: demonstrate why 0.1 + 0.2 != 0.3 and show two different ways to handle this (using decimal.Decimal and math.isclose).

  5. Write a function describe_value(x) that prints the type, truthiness (bool(x)), and whether it's mutable or immutable for any given value.

  6. 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 of is to check for None. Always use x is None or x is not None — it's faster and semantically correct (identity vs equality).

  • Forgetting that 0.1 + 0.2 != 0.3 due to floating-point representation. Use decimal.Decimal for financial calculations or math.isclose() for comparisons.

  • Thinking a = b copies the value for mutable types. It creates another reference to the same object. Use .copy(), list(), or copy.deepcopy() for actual copies.

  • Using mutable default arguments in functions: def f(x=[]) — the default list is shared across all calls. Use def f(x=None): x = x or [] instead.

  • Not knowing about Python's integer caching: a = 256; b = 256; a is b is True (cached), but a = 257; b = 257; a is b may be False (not cached). Always use == for value comparison.

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Variables & Data Types