Notifications

No notifications

/Phase 1

Variables & Data Types

Variables & Data Types in Python

A variable is a name that refers to a value stored in memory. Python is dynamically typed β€” you don't declare types explicitly; the interpreter infers them at runtime.

Creating Variables

name = "Alice"     # str
age = 25           # int
height = 5.7       # float
is_student = True  # bool
nothing = None     # NoneType

Core Data Types

TypeExampleDescription
int42, -7, 0Whole numbers (unlimited precision)
float3.14, -0.5, 1e10Decimal numbers (64-bit IEEE 754)
str"hello", 'world'Text β€” immutable sequence of characters
boolTrue, FalseLogical values (subclass of int)
NoneTypeNoneRepresents absence of a value

Type Checking & Conversion

type(42)         # <class 'int'>
isinstance(42, int)  # True

int("10") # 10 float("3.14") # 3.14 str(100) # "100" bool(0) # False

Dynamic Typing

x = 10       # x is int
x = "hello"  # x is now str β€” no error!

Multiple Assignment

a, b, c = 1, 2, 3
x = y = z = 0        # All set to 0
a, b = b, a           # Swap values!

Variable Naming Rules

RuleValidInvalid
Start with letter or __count, name2name
No spaces or special charsmy_varmy-var, my var
Case-sensitiveName β‰  nameβ€”
No reserved keywordsscoreclass, if, for

On this page

Detailed Theory

Variables are how you give names to data. In Python this is unusually flexible β€” no type declarations, no var / let, just name = value and you're off. Underneath, Python is doing something more interesting than other languages: variables are *labels* attached to *objects*, not boxes that hold values.

What a Variable Actually Is

x = 42

This creates an integer object 42 somewhere in memory and binds the name x to it. Reassign x = "hi" and x now points to a string object β€” the original 42 is unchanged (and may be garbage-collected if nothing else references it).

The Core Built-in Types

TypeExampleNotes
int42, -7arbitrary precision (no overflow)
float3.1464-bit IEEE 754
str"hi", 'a'unicode by default
boolTrue, Falsea subclass of int (True == 1)
NoneTypeNonethe "no value" singleton
list[1, 2, 3]ordered, mutable
tuple(1, 2)ordered, immutable
dict{"a": 1}key→value, mutable
set{1, 2, 3}unique values, mutable

Naming Rules & Conventions

  • Letters, digits, underscores; can't start with a digit.
  • Case-sensitive: age and Age are different.
  • Convention: snake_case for variables/functions, UPPER_SNAKE for constants, PascalCase for classes.
  • Avoid built-in names: don't call a variable list, dict, type, id, sum.

Type Conversion (Casting)

int("42")        # 42
int(3.9)          # 3   (truncates, doesn't round)
float("3.14")     # 3.14
str(42)            # "42"
bool(0), bool(1), bool(""), bool("a")  # False, True, False, True

Key rule: Python won't auto-convert between strings and numbers β€” "3" + 4 raises TypeError. Convert explicitly.

Beginner Mistakes to Skip

1. Comparing floats with ==. 0.1 + 0.2 == 0.3 is False. Use math.isclose or Decimal for money. 2. Mutable default arguments. def f(items=[]): shares the list across calls β€” horrifying bug. Use items=None and assign inside. 3. is vs ==. is checks *identity* (same object), == checks *equality*. Use is only for None, True, False. 4. Shadowing built-ins. list = [1,2] breaks every later list(...) call. 5. int("3.5"). Crashes β€” strings with decimals aren't ints. Go through float first. 6. Confusing assignment with equality. = assigns; == compares. if x = 5 is a syntax error in Python (small mercy).

Intermediate: Everything Is an Object

x = 42
x.bit_length()   # 6 β€” ints have methods
type(x)            # <class 'int'>
id(x)              # memory address

Even None, True, and integers are objects with attributes and methods. This uniformity is why Python feels consistent.

Intermediate: Mutable vs Immutable

  • Immutable: int, float, str, bool, tuple, frozenset, bytes. Reassignment makes a *new* object.
  • Mutable: list, dict, set, custom classes. You can change them in place.
Why it matters:

a = [1, 2, 3]
b = a            # same list, two names
b.append(4)
print(a)         # [1, 2, 3, 4]  β€” surprise!

Use b = a.copy() (or a[:] / list(a)) when you want an independent copy.

Intermediate: Truthiness

Every value can act as a boolean. Falsy values: False, None, 0, 0.0, "", [], {}, set(). Everything else is truthy.

name = ""
if name:       # idiomatic; same as: if len(name) > 0
    greet(name)

Intermediate: None and Sentinels

None is the standard "absence of value". Always test with is / is not:

if result is None:
    ...
if user is not None:
    ...

Advanced: Integer Caching & Identity

CPython caches small ints (-5 to 256). So a = 5; b = 5; a is b is True β€” but a = 1000; b = 1000; a is b is *implementation-defined* and may be False. Don't rely on is for value comparison; use ==.

Similarly, short strings that look like identifiers are *interned* and share memory. Useful trivia, never rely on it.

age: int = 25
name: str = "Alice"
tags: list[str] = []

def greet(user: str, count: int = 1) -> str: return f"hi {user}" * count

Type hints are *not enforced at runtime*. They're documentation that mypy / pyright check statically, and your IDE uses them for autocomplete and error squiggles. On any project >100 lines, turn them on.

Advanced: Decimals, Fractions & Money

from decimal import Decimal
Decimal("0.1") + Decimal("0.2")   # Decimal('0.3')  β€” exact

For financial code, use Decimal. For exact rational math, fractions.Fraction. Floats are fine for science, deadly for accounting.

Advanced: Memory & Garbage Collection

Python uses reference counting + a cyclic garbage collector. When the last name pointing to an object is gone, memory is freed automatically. del x removes the binding (and if it was the last, frees the object). Tools: sys.getrefcount, gc module, tracemalloc for leak hunting.

Practice Path

1. Predict the type and value: bool([]), int("007"), str(True), float("3.14e2"). Run them, confirm. 2. Demonstrate the mutable-default-argument bug, then fix it with the None pattern. 3. Add type hints to a small function and run mypy file.py (or rely on Pylance) to confirm there are no warnings. 4. Compare a is b vs a == b for a, b = 5, 5 and a, b = 1000, 1000 β€” explain the difference.