Python Basics
Python's core syntax and semantics — running code, names and objects, dynamic typing, numbers and strings, control flow, functions, comprehensions, truthiness, exceptions, and the Pythonic style.
Python is a high-level, dynamically typed, garbage-collected language that values readability: indentation defines blocks, and there's usually one obvious way to do something. It dominates data science, ML, scripting and automation, and is widely used for web back ends (Django, FastAPI).
Running Python
python3 script.py # run a file
python3 # interactive REPL
python3 -m venv .venv # create a virtual environment (isolated packages)
source .venv/bin/activate # (Windows: .venv\Scripts\activate)
pip install requests# hello.py
def main() -> None:
name = input("Name? ")
print(f"Hello, {name}!")
if __name__ == "__main__": # run only when executed directly, not when imported
main()Names, objects and dynamic typing
In Python, everything is an object, and variables are names bound to objects — labels, not boxes.
x = [1, 2, 3]
y = x # y is another name for the SAME list
y.append(4)
print(x) # [1, 2, 3, 4]
x = "now a string" # rebinding: names have no fixed type
id(y), type(y) # identity and type belong to the object
a is b # same object? a == b → equal values?Objects are either mutable (list, dict, set, most class instances) or immutable (int, float, str, tuple, frozenset, bytes). Immutable "changes" create new objects.
Numbers
7 / 2 # 3.5 true division always returns float
7 // 2 # 3 floor division
-7 // 2 # -4 (floors toward negative infinity)
7 % 3 # 1; -7 % 3 → 2 (result has the divisor's sign)
2 ** 100 # 1267650600228229401496703205376 — ints are arbitrary precision
0.1 + 0.2 # 0.30000000000000004 — use decimal.Decimal for money
1_000_000 # underscores for readability
int("42"), float("3.5"), round(2.675, 2) # 2.67 — binary floating point againStrings
s = "Python"
s[0], s[-1] # 'P', 'n' (negative indexes count from the end)
s[1:4] # 'yth' slicing: start inclusive, end exclusive
s[::-1] # 'nohtyP' reverse
len(s); s.upper(); s.lower(); s.strip(); s.replace("P", "J")
"a,b,c".split(",") # ['a', 'b', 'c']
"-".join(["a", "b"]) # 'a-b'
"py" in s.lower() # True
f"{s!r} has {len(s)} chars, pi ≈ {3.14159:.2f}" # f-strings with formatting
"""multi
line"""Strings are immutable sequences of Unicode code points; bytes hold raw bytes ("é".encode("utf-8") → b'\xc3\xa9').
Collections at a glance
| Type | Literal | Mutable | Ordered | Notes |
|---|---|---|---|---|
list | [1, 2] | Yes | Yes | Dynamic array |
tuple | (1, 2) | No | Yes | Fixed records, dict keys |
dict | {"a": 1} | Yes | Insertion order | Hash map |
set | {1, 2} | Yes | No | Unique elements |
Details and complexities in Data structures.
Control flow
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
label = "even" if n % 2 == 0 else "odd" # conditional expression
for i in range(5): ... # 0..4
for i, name in enumerate(names, start=1): ...
for a, b in zip(xs, ys): ... # parallel iteration (stops at the shortest)
for key, value in config.items(): ...
while queue:
item = queue.pop()
for n in numbers:
if n < 0:
break
else: # runs only if the loop did NOT break
print("all non-negative")
match command.split(): # structural pattern matching (3.10+)
case ["go", direction]:
move(direction)
case ["quit" | "exit"]:
quit()
case _:
print("unknown")Truthiness
Falsy values: False, None, 0, 0.0, "", [], {}, set(), range(0) (and objects whose __bool__ or __len__ says so). Everything else is truthy.
if items: # idiomatic: "if not empty"
...
if x is None: # compare to None with 'is', not ==
...Functions
def greet(name: str, greeting: str = "Hello", *, punctuation: str = "!") -> str:
"""Return a greeting. Parameters after * are keyword-only."""
return f"{greeting}, {name}{punctuation}"
greet("Ada")
greet("Ada", "Hi", punctuation="?")
def total(*nums: float, **options) -> float: # variadic positional and keyword args
return round(sum(nums), options.get("digits", 2))
square = lambda x: x * x # small anonymous functions
sorted(users, key=lambda u: u.age)More in Functions & decorators.
Comprehensions
Concise, readable construction of collections:
squares = [x * x for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
lengths = {word: len(word) for word in words} # dict comprehension
unique_lower = {w.lower() for w in words} # set comprehension
total = sum(x * x for x in range(10**6)) # generator expression: lazy, no list builtExceptions
try:
value = int(text)
except ValueError as e:
print(f"not a number: {e}")
except (TypeError, KeyError):
...
else:
print("no exception") # runs only if try succeeded
finally:
cleanup() # always runs
raise ValueError("amount must be positive")
class InsufficientFunds(Exception):
def __init__(self, shortfall: int):
super().__init__(f"short by {shortfall}")
self.shortfall = shortfall
with open("data.txt", encoding="utf-8") as f: # context manager closes the file
for line in f:
print(line.rstrip())Python favours EAFP ("easier to ask forgiveness than permission"): try the operation and handle the exception, rather than checking everything first (LBYL).
The Pythonic style
# Unpacking
a, b = b, a # swap
first, *rest = [1, 2, 3, 4] # rest = [2, 3, 4]
x, y = point
# Chained comparisons
if 0 <= index < len(items): ...
# any / all with generators
if any(u.is_admin for u in users): ...
# The walrus operator (3.8+): assign inside an expression
while (line := f.readline()):
process(line)
# Built-ins worth knowing
min(), max(key=...), sorted(key=..., reverse=True), sum(), enumerate(), zip(), reversed(), isinstance()import this prints the Zen of Python: "Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex… Readability counts." Follow PEP 8 for style (snake_case names, 4-space indents) and let a formatter (ruff format, black) handle it.
- Variables are names bound to objects; assignment never copies.
- Know which types are mutable (list, dict, set) and immutable (int, str, tuple).
- / is true division, // floors; ints have unlimited precision.
- Comprehensions and generator expressions build collections concisely.
- Never use mutable default arguments; compare with None using is.
- Use with for resources and EAFP-style exception handling.
QWhat is the difference between is and ==?easy
== compares values by calling eq; is compares identity — whether both names refer to the same object. Use is for singletons like None, True and False. Small integers and some strings are cached by CPython, so is may appear to work for them, but that is an implementation detail.
QIs Python pass-by-value or pass-by-reference?medium
Neither, strictly: it's pass-by-object-reference (call by sharing). The function receives a reference to the same object. Mutating a mutable argument is visible to the caller, but rebinding the parameter name inside the function doesn't affect the caller's variable.