Python Basics


  • Description: Python runtime model, comments, dynamic typing, casts, is vs ==, truthiness, naming, indentation, and the __main__ idiom, anchored against C++
  • My Notion Note ID: K2A-D1-1
  • Created: 2022-02-10
  • Updated: 2026-05-11
  • License: Reuse is very welcome. Please credit Yu Zhang and link back to the original on yuzhang.io

Table of Contents


1. Runtime Model

  • Interpreted, dynamically typed
  • .py → bytecode .pyc on the fly, run by CPython VM
  • No separate compile/link step (unlike C++)
  • REPL: python3 or ipython
  • Script: python3 script.py
  • Shebang: #!/usr/bin/env python3 on line 1 → ./script.py works on Unix
  • Source encoding: UTF-8 by default; legacy # -*- coding: utf-8 -*- no longer needed
  • Python 2 EOL 2020-01-01, all new code is Python 3

2. Hello, World and the __main__ Idiom

def main() -> None:
    print("Hello, World!")

if __name__ == "__main__":
    main()
  • __name__ is "__main__" when run directly; the module's dotted name when imported
  • Guard runs main() only on direct execution, opt-in equivalent of C++ int main()

3. Comments and Docstrings

# Single-line comment.

def add(a: int, b: int) -> int:
    """Return the sum of a and b.

    Triple-quoted string as first statement = docstring;
    accessible via `__doc__` and `help()`.
    """
    return a + b
  • No /* ... */ block comment
  • Use # per line, or a triple-quoted string that the compiler discards

4. Dynamic vs Static Typing

x = 1          # int
x = "hello"    # now str, legal, no warning
x = [1, 2, 3]  # now list
  • C++: variable has a type fixed at declaration
  • Python: name binds to an object that has a type; checked at use
  • Type hints (PEP 484) annotate intent, not enforced at runtime; consumed by mypy, pyright
Aspect C++ Python
Type binding Variable has a type Name binds to an object with a type
Compile-time checks Strict Opt-in via static checkers
Implicit conversions Many (int → double) Few; explicit casts preferred

5. type() and isinstance()

type(x)                       # exact class
type(x) is int                # exact, ignores subclasses
isinstance(x, int)            # includes subclasses (preferred)
isinstance(x, (int, float))   # tuple = "any of"
  • Prefer isinstance over type(x) ==, accepts subclasses (Liskov-substitutable)
  • Closest C++ analog: dynamic_cast for polymorphic hierarchies

6. Casts

int("42")          # 42
int("0x2a", 16)    # 42 with explicit base
int(3.9)           # 3, truncates toward zero, not rounds
float("3.14")      # 3.14
str(42)            # "42"
bool(0)            # False; bool([]) False; bool("0") True!
list("abc")        # ['a', 'b', 'c']
tuple([1, 2])      # (1, 2)
set([1, 1, 2])     # {1, 2}
  • Casts are constructor calls, return new objects
  • No implicit narrowing (unlike C++ int → char)
  • int(s) raises ValueError if unparseable

7. Identity (is) vs Equality (==)

  • == calls __eq__, "do these compare equal?"
  • is compares identity, id(a) == id(b)
a = [1, 2]
b = [1, 2]
a == b   # True , same contents
a is b   # False, different list objects

x = None
x is None  # True, idiomatic; never `x == None`
  • CPython caches small ints (-5..256) and short interned strings, implementation detail, don't rely on it
  • Use is only against singletons: None, True, False

8. Truthiness

Falsy:

  • None
  • False
  • Numeric zero: 0, 0.0, 0j
  • Empty: "", [], (), {}, set()
  • Objects whose __bool__ returns False, or whose __len__ returns 0

Everything else is truthy.

if not items:        # idiomatic: "items is empty"
    return

if user is not None: # explicit None check when 0/empty is valid
    ...

9. Naming Conventions

PEP 8:

Kind Style Example
Variable / function snake_case user_count, parse_url()
Class PascalCase HttpClient
Constant UPPER_SNAKE_CASE MAX_RETRIES
Module / package lowercase, short os, urllib
"Private" leading underscore _internal
Name-mangled double leading __field_ClassName__field
Dunder double on both sides __init__, __len__ (reserved)
  • No private/public keywords, convention only

10. Indentation as Syntax

def f(x):
    if x > 0:
        return x
    else:
        return -x
  • Indentation IS the grammar, no braces
  • 4 spaces, no tabs
  • Mixing tabs and spaces → TabError

11. pip and Virtual Environments

python3 -m venv .venv          # create
source .venv/bin/activate      # activate (Linux/macOS)
pip install requests
pip install -r requirements.txt
pip freeze > requirements.txt
deactivate
  • pip installs from PyPI; venv isolates project dependencies
  • Modern alternatives: poetry, uv, pdm, add lockfiles and faster resolution

12. References