L4: Function Fundamentals#

Overview#

This lecture introduces Python functions as the primary tool for organizing code into reusable, modular units. You will learn how to define and call functions, work with different argument types, understand Python’s scope rules (LEGB), explore pass-by-assignment behavior, add type hints for clarity, write Google-style docstrings, and use recursion to solve problems that have a recursive structure.

Learning Objectives

By the end of this lecture, you will be able to:

  • Define and call functions using the def keyword with parameters and return values.

  • Distinguish between positional, default, keyword, *args, and **kwargs arguments.

  • Explain the LEGB scope rule and predict how Python resolves variable names.

  • Describe how pass-by-assignment works with mutable and immutable objects.

  • Annotate functions with type hints including Optional, Union, and Python 3.10+ pipe syntax.

  • Write Google-style docstrings with descriptions, Args, and Returns sections.

  • Implement recursive functions with proper base cases and recursive cases.

Next Steps#

  • In the next lecture, we will cover Advanced Functions:

    • Programming paradigms (procedural, functional, OOP)

    • First-class functions and lambdas

    • Closures and callables

    • Decorators

    • Partial functions

  • Review and experiment with all code snippets and exercises from today’s lecture.

  • Practice writing functions with different argument types and type hints.

  • Read Python Official Tutorial – Section 4.7 (Defining Functions).