Python Basics
- Description: Python runtime model, comments, dynamic typing, casts,
isvs==, 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
- 2. Hello, World and the
__main__Idiom - 3. Comments and Docstrings
- 4. Dynamic vs Static Typing
- 5.
type()andisinstance() - 6. Casts
- 7. Identity (
is) vs Equality (==) - 8. Truthiness
- 9. Naming Conventions
- 10. Indentation as Syntax
- 11.
pipand Virtual Environments - 12. References
1. Runtime Model
- Interpreted, dynamically typed
.py→ bytecode.pycon the fly, run by CPython VM- No separate compile/link step (unlike C++)
- REPL:
python3oripython - Script:
python3 script.py - Shebang:
#!/usr/bin/env python3on line 1 →./script.pyworks 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
isinstanceovertype(x) ==, accepts subclasses (Liskov-substitutable) - Closest C++ analog:
dynamic_castfor 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)raisesValueErrorif unparseable
7. Identity (is) vs Equality (==)
==calls__eq__, "do these compare equal?"iscompares 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
isonly against singletons:None,True,False
8. Truthiness
Falsy:
NoneFalse- Numeric zero:
0,0.0,0j - Empty:
"",[],(),{},set() - Objects whose
__bool__returnsFalse, or whose__len__returns0
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/publickeywords, 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
pipinstalls from PyPI;venvisolates project dependencies- Modern alternatives:
poetry,uv,pdm, add lockfiles and faster resolution