Back to Python tutorials
Basic17 min read

Python Fundamentals

Learn Python syntax, dynamic typing, control flow, functions, and string handling—the foundation for every Python project.

Variables and Data Types

Python uses dynamic typing: names bind to objects without explicit type declarations. Core built-in types include int, float, str, bool, list, dict, set, and tuple.

Use type hints optionally for clarity and tooling support. Values are objects; assignment creates references, not copies, unless you explicitly copy collections.

Indentation defines blocks instead of braces. Consistent four-space indentation is the community standard enforced by PEP 8.

  • Use meaningful variable names in snake_case
  • Prefer f-strings for formatting: f"Hello {name}"
  • Check types with isinstance, not type(x) == int for subclasses
name: str = "Ada"
count = 42
prices = [9.99, 14.50, 7.25]
user = {"id": 1, "email": "ada@example.com"}

Control Flow

if/elif/else handles branching. for iterates sequences; while loops until a condition fails. break and continue alter loop behavior.

Truthiness treats empty collections and zero as False. Use in membership tests for readable containment checks.

Comprehensions often replace simple loops for building lists, dicts, and sets concisely.

  • Avoid infinite while True without clear break conditions
  • Use enumerate when you need index and value together
  • Prefer EAFP (try/except) over LBYL for rare error paths when idiomatic
for item in items:
    if item.is_active:
        process(item)
    elif item.retry:
        queue_retry(item)

Functions and Scope

Define functions with def, optional type hints, and default parameter values. Defaults should be immutable—avoid mutable defaults like [] which persist across calls.

Functions are first-class objects passed as arguments and returned from other functions. Nested functions close over enclosing variables forming closures.

Use *args and **kwargs sparingly for wrappers; prefer explicit parameters for public APIs.

  • Document public functions with docstrings
  • Keep functions small and focused on one task
  • Use return type hints on exported APIs
def greet(name: str, prefix: str = "Hello") -> str:
    return f"{prefix}, {name}!"

def apply_twice(fn, value):
    return fn(fn(value))

Strings and Collections

Strings are immutable sequences with rich methods: split, join, strip, replace. Slice notation works on strings and sequences: s[1:4], items[-1].

Lists are ordered mutable arrays; dicts map keys to values with O(1) average lookup; sets store unique hashable elements.

Choose the right collection for the job: dict for lookups, list for ordered data, set for uniqueness tests.

  • Normalize Unicode before comparing user-facing strings
  • Use .get on dicts when keys may be missing
  • Copy mutable collections with list() or .copy() before mutating

Get In Touch


Ready to discuss your next project? Drop me a message.