3 - Functions, Comprehensions, and Functional Patterns

Defining Functions

Introduction

A function is a named block of code that you define once and reuse whenever you need it. In Python, you create one with the def statement: you give the function a name, list any parameters in parentheses, and indent the body beneath the colon. When the function finishes, a return statement can hand a value back to the code that called it — and if you omit return, Python quietly returns None. Calling the function by name, with parentheses and any required arguments, is what actually runs that code.

This matters because almost everything that follows in the course is built on functions. Parameter styles, scope rules, recursion, and the functional patterns later in this module all assume you are comfortable with the basic def/return/call cycle. Good habits start here too: descriptive names in lowercase_with_underscores, and a docstring — a triple-quoted string on the first line of the body — that explains what the function does, what it expects, and what it gives back.

As you watch, keep three questions in mind. First, what is the difference between a function that returns a value and one that only prints something — can you use the result in an expression afterward? Second, where does execution go when a return runs, and what happens to any code after it? Third, what does the function need from the caller, and what does the caller get back? Try pausing and predicting the output before the narrator reveals it.

Video 1: LEARN FUNCTIONS in PYTHON: def, pass, syntax, None, return vs print, arguments, scope and more

BitBoss · 16:13 · 377,158 views · 2y ago · captions — Watch on YouTube

About this video

A comprehensive single-video walkthrough of Python functions, covering the def statement and its syntax, the pass placeholder for empty function bodies, arguments, the None value, and variable scope. The title also highlights the frequently confused distinction between return and print, which is one of the most common stumbling blocks for beginners. At roughly sixteen minutes it is the longest of the three and serves as the main overview for this topic.

Why this video

It touches nearly every subtopic here — defining with def, calling with arguments, and returning values — in one continuous explanation, and its direct treatment of return versus print addresses the error students most often make when writing their first functions.

Video 2: Python functions 📞

Bro Code · 9:15 · 49,520 views · 5y ago · captions — Watch on YouTube

About this video

Bro Code's concise introduction defines a function as a block of code that executes only when it is called, then demonstrates writing one with def and invoking it by name. Expect short, typed-along examples that show parameters being passed in and the function body running on demand. The pacing is quick and the examples are deliberately simple.

Why this video

It is a clean, beginner-friendly treatment of the def statement and of calling a function, from a channel widely used for its clear, no-filler coding demonstrations — a good first watch or a quick review before the longer video.

Video 3: Python return statement 🔙

Bro Code · 3:31 · 130,674 views · 5y ago · captions — Watch on YouTube

About this video

A short, focused lesson on the return statement: how a function sends a value or object back to the caller so the result can be stored in a variable or used in a larger expression. In about three and a half minutes it isolates the single concept rather than mixing it with other function topics.

Why this video

Because return is the subtopic students most often misunderstand, a dedicated short video is valuable; it reinforces that a returned value is reusable data, not screen output, which is the key idea behind building functions that compose.

How These Videos Support the Learning Outcomes

Together these videos build the foundation for MO1: the BitBoss overview and the Bro Code introduction demonstrate constructing functions with def and passing arguments, while the dedicated return video reinforces writing explicit return statements that produce usable results. The scope discussion in the BitBoss video previews the LEGB reasoning developed in MO2, and the habit of writing small, well-named, documented functions established here is what later outcomes depend on — recursion in MO3 requires a function that returns a value from both its base and recursive cases, and the comprehension and lambda comparisons in MO4 and MO5 only make sense once you can read a standard def-based function fluently. Supplement the videos with the course material on docstrings, since documentation is part of MO1 but receives limited attention in these clips.

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.

Parameters and Arguments

Introduction

When you define a function, the names listed in the parentheses of the def line are its parameters. When you call that function, the values you supply are its arguments. Keeping those two words straight makes it far easier to read error messages, documentation, and your own code, so this topic starts there and then builds outward to the different ways arguments can be matched to parameters.

Python gives you several options. Positional arguments are matched in order, left to right, so the order you write them matters. Keyword arguments are matched by name, which makes calls more readable and lets you skip the order entirely. Default parameter values let you declare a fallback in the function definition so callers can leave some arguments out, which is how most real-world library functions offer optional behavior.

As you watch these videos, pay attention to three things: the exact rule for where positional arguments must appear relative to keyword arguments, what happens when you pass too few or too many arguments, and how a default value changes which arguments are required. Try retyping each example in your own editor and then deliberately break it — swap the order, misspell a keyword, omit a required argument — so you learn to recognize the resulting TypeError messages.

Video 1: Function Arguments in Python | Python Tutorial - Day #21

CodeWithHarry · 13:50 · 930,979 views · 3y ago · captions — Watch on YouTube

About this video

A full-length tutorial lesson devoted to function arguments in Python, part of CodeWithHarry's day-by-day Python course. Based on its length and placement in the series, it should work through how arguments are passed to functions and cover the main argument styles, including positional and keyword arguments and parameters that carry default values, with live coding examples. Expect worked demonstrations rather than a quick definition-only overview.

Why this video

At nearly fourteen minutes it is the most thorough of the three and functions as the main lecture-style treatment for this topic, covering the several argument styles in one place from a widely used, beginner-oriented Python channel.

Video 2: Positional vs keyword function arguments in Python

Python Morsels · 3:06 · 1,485 views · 3y ago · captions — Watch on YouTube

About this video

A focused three-minute screencast contrasting positional arguments, where position determines which parameter receives a value, with keyword (named) arguments, where the argument name is what matters. The description signals that the central idea is name-versus-position matching, so expect short call examples that show the same function invoked both ways.

Why this video

It targets the single distinction students most often confuse, and Python Morsels is a well-regarded source for precise, carefully worded explanations of exactly this kind of language detail.

Video 3: Python keyword arguments 🔑

Bro Code · 3:01 · 14,632 views · 5y ago · captions — Watch on YouTube

About this video

A short, fast demonstration of keyword arguments in Python from the Bro Code channel, framed as arguments identified by name rather than by position. Expect a compact code example showing a function called with named arguments and a note on the readability and ordering benefits this provides.

Why this video

It is a concise reinforcement of the keyword-argument subtopic and makes a good second pass or quick review after the longer lecture, with minimal time cost.

How These Videos Support the Learning Outcomes

These videos directly support MO1 by building the vocabulary and mechanics you need to construct functions with appropriate parameter types. Together they establish the parameter-versus-argument distinction, demonstrate positional matching, explain keyword arguments by name, and introduce default parameter values that make arguments optional. That foundation is a prerequisite for the later *args and **kwargs material in this module, and the habit of reading a def line carefully also carries into tracing scope (MO2) and writing the small, single-purpose functions used in recursion and functional patterns (MO3, MO5).

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.

Scope and Variable Visibility

Introduction

Every time Python encounters a variable name, it has to decide which value that name refers to. The answer depends on where the name is used. Python searches for names in a fixed order known as the LEGB rule: Local (inside the current function), Enclosing (inside any outer function that wraps it), Global (at the top level of the module), and finally Built-in (names like len and print that Python provides automatically). The first match wins, and if no match is found you get a NameError.

Scope matters in this course because you are now writing functions, and functions are the main way Python creates new scopes. Assigning to a name inside a function creates a local variable by default, even if a variable with the same name already exists outside the function. When you genuinely need a function to change a variable that lives elsewhere, Python requires you to say so explicitly with the global keyword (for module-level names) or the nonlocal keyword (for names in an enclosing function). Understanding this prevents a whole category of confusing bugs, such as a function that seems to update a counter but leaves the original unchanged, or an UnboundLocalError on a name you thought was global.

As you watch, keep three questions in mind for every example: where is this name first assigned, which scope does Python search first, and does this code read a variable or rebind it? Try predicting the output before the narrator reveals it, then pause and check. Pay particular attention to the difference between mutating an object (such as appending to a list) and reassigning a name, since only the latter triggers the need for global or nonlocal.

Video 1: Local vs Global Variables in Python| Python Tutorial - Day #48

CodeWithHarry · 10:37 · 316,123 views · 3y ago · captions — Watch on YouTube

About this video

A beginner-oriented walkthrough of the distinction between local and global variables in Python, likely using small function examples to show what happens when a name is defined inside a function versus at module level. Based on the title and description, it should also demonstrate when and why you would reach for the global keyword to modify a module-level variable from inside a function.

Why this video

CodeWithHarry's tutorial series is a well-known, slow-paced introduction, making this a good first pass at the Local and Global layers of LEGB and at the global keyword subtopic before you tackle nested functions.

Video 2: Functions within functions, closures, and variable scopes in Python

mCoding · 18:44 · 73,833 views · 3y ago · captions — Watch on YouTube

About this video

This video covers defining functions inside other functions, how closures capture variables from an enclosing scope, and how Python resolves variable names across those nested levels. Given the title and the channel's style, expect precise explanations of why an inner function can read an outer function's variables, and where nonlocal becomes necessary to rebind them.

Why this video

mCoding is produced by a professional Python developer known for technically accurate, detail-focused explanations, and this is the one video of the three that directly addresses the Enclosing layer of LEGB and the nonlocal keyword.

Video 3: Local and global variables in Python

Python Morsels · 4:17 · 1,986 views · 3y ago · captions — Watch on YouTube

About this video

A short, focused explanation of the key asymmetry in Python scoping: inside a function you can read global variables freely, but assigning to a name makes it local unless you declare otherwise. The description suggests it works through what happens within each function call and why the read/write distinction trips people up.

Why this video

Python Morsels produces concise, carefully worded lessons, and at just over four minutes this is an efficient review or reinforcement of the local-versus-global rule and the exact behavior that motivates the global keyword.

How These Videos Support the Learning Outcomes

These three videos together support MO2, the ability to trace Python's LEGB scope rule and predict which value a name resolves to. The CodeWithHarry and Python Morsels videos build the Local and Global layers and the assignment-makes-it-local rule that underlies the global keyword, with the Python Morsels clip offering a compact restatement for review. The mCoding video extends the picture to the Enclosing layer through nested functions and closures, which is where nonlocal applies. Because scope is a property of functions, the examples also reinforce MO1 by showing how def creates a new namespace each time a function runs, and the mental model of per-call local scopes will be useful later when you trace recursive calls for MO3.

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.

Recursion

Introduction

Recursion is a problem-solving technique in which a function calls itself on a smaller version of the same problem. Instead of writing a loop that repeats work, you describe the problem in terms of itself: a factorial of n is n times the factorial of n-1, the nth Fibonacci number is the sum of the two before it, and so on. Every correct recursive function needs two parts: a base case that stops the chain of calls and returns a direct answer, and a recursive case that moves the input closer to that base case.

This topic matters in EGN3214 because recursion is a natural fit for problems with nested or self-similar structure, and because writing it forces you to think carefully about what a function returns and how parameters change between calls. It also connects to how Python actually runs your code: each call occupies a frame on the call stack, so recursion that never reaches a base case, or that goes too deep, raises a RecursionError rather than running forever.

As you watch, keep three questions in mind for every example: What is the base case? How does the recursive case shrink the input? What would happen if the base case were missing or wrong? It is also worth noting where the videos compare recursion to an iterative loop, since in Python an equivalent loop is often faster and uses less memory even when recursion reads more clearly.

Video 1: Recursion Simply Explained with Code Examples - Python for Beginners

Python Simplified · 9:07 · 251,262 views · 4y ago · captions — Watch on YouTube

About this video

A beginner-oriented walkthrough of recursion in Python that builds up from the basic idea of a function calling itself to coded examples, including a recursive Fibonacci implementation and an iterative version of the same problem. The timestamps indicate it also discusses whether recursion is faster than iteration in Python.

Why this video

It covers the core subtopics (what recursion is, base case, recursive case) with runnable code, and the recursion-versus-iteration comparison gives you an honest picture of recursion's practical costs.

Video 2: Recursion in Python | Python Tutorial - Day #30

CodeWithHarry · 10:01 · 643,229 views · 3y ago · captions — Watch on YouTube

About this video

A tutorial-series episode devoted to recursion in Python, presenting the concept and working through recursive function examples step by step as part of a structured beginner course. Expect standard introductory examples such as factorial or similar self-referential problems, with attention to how the calls unwind.

Why this video

It offers a second explanation of the same ideas in a different teaching style, which is useful if the first presentation does not click; CodeWithHarry's day-by-day format keeps the focus tightly on the single topic.

Video 3: 17: Python RecursionError Explained | Maximum Recursion Depth & Call Stack

Amulya's Academy · 3:28 · 158 views · 1mo ago · captions — Watch on YouTube

About this video

A short, focused video on what happens when a recursive function has no base case: Python raises RecursionError: maximum recursion depth exceeded. It explains the call stack behind that error and why Python imposes a depth limit at all.

Why this video

This directly addresses the recursion depth and limitations subtopic, which the broader introductory videos treat only briefly, and it teaches you to read and diagnose an error message you will almost certainly produce yourself.

How These Videos Support the Learning Outcomes

Together these videos support MO3 most directly: the first two show how to identify and code a base case and a recursive case for concrete problems like factorial and Fibonacci, while the third shows what goes wrong when the base case is missing or unreachable. Because recursive functions are still ordinary functions, the examples also reinforce MO1 by exercising def, parameters, and explicit return statements, and tracing the sequence of calls and their local variables reinforces the scope reasoning in MO2. The recursion-versus-iteration discussion additionally builds the habit of judgment behind MO5 — choosing an approach based on readability and practical constraints rather than novelty.

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.

Comprehensions

Introduction

A comprehension is a compact way to build a new collection from an existing iterable. Instead of creating an empty list, writing a for loop, and calling append on each pass, you express the whole transformation in a single line: the expression you want to produce, the loop that supplies the values, and an optional condition that filters which values are kept. Python supports this pattern for lists, dictionaries, and sets, and the syntax is nearly identical in each case — only the brackets and the shape of the output expression change.

This matters in EGN3214 because engineering data work is mostly transformation: converting units across a list of measurements, pulling the sensor readings above a threshold, building a lookup table from names to values, or collecting the unique materials in a parts list. Comprehensions make these operations short and readable, and they appear constantly in real Python code, so you need to be able to both write them and read someone else's. They also set up the next topic, where you compare comprehensions against lambda, map(), and filter().

As you watch, keep a mental template in view: output expression, then for variable in iterable, then optional if condition. Notice where the filter clause goes and how it differs from an if-else placed before the for. Pay attention to the dictionary form, which needs a key-value pair separated by a colon, and to nested comprehensions, where the order of the for clauses matches the order you would write them in a normal nested loop. If a comprehension ever becomes hard to read, that is a signal to write it back out as a loop.

Video 1: List Comprehension - BEST Python feature !!! Fast and Efficient

Python Simplified · 14:51 · 216,985 views · 4y ago · captions — Watch on YouTube

About this video

A thorough, beginner-friendly walkthrough of list comprehension syntax, starting from ordinary for loops and building up to the compact one-line form. At roughly fifteen minutes it has room to work through several examples, including conditional logic inside comprehensions and the readability and efficiency arguments for using them.

Why this video

Python Simplified is a well-regarded Python teaching channel, and this is the most complete treatment of the core subtopic — list comprehensions and filtering — with enough worked examples to make the syntax stick before you move to the dict and set variants.

Video 2: List Comprehensions | Set Comprehension | Dict Comprehension | Python Tutorials Ep. 32

Ridwanray · 6:07 · 447 views · 2y ago · captions — Watch on YouTube

About this video

A short, focused tutorial that covers all three comprehension forms in sequence: list, set, and dictionary. It demonstrates the syntactic differences between them — square brackets versus curly braces, and the key-value expression required by dictionary comprehensions — and shows typical use cases for each.

Why this video

This is the one video in the set that explicitly covers dictionary and set comprehensions alongside lists, so it rounds out subtopics that a list-only tutorial would leave untouched, and it does so in six minutes.

Video 3: Turning a for loop into a list comprehension

Python Morsels · 4:29 · 770 views · 3y ago · captions — Watch on YouTube

About this video

A concise screencast that demonstrates a mechanical, step-by-step method for converting an existing for loop into an equivalent comprehension, moving pieces of the loop into place rather than rewriting from scratch. The description recommends copy-pasting your way from loop to comprehension as a way to anchor the new syntax to something you already understand.

Why this video

Python Morsels is produced by a professional Python trainer, and this translation technique is the fastest way to stop guessing at comprehension syntax — it is especially useful for getting the filter clause and nested for clauses in the right order.

How These Videos Support the Learning Outcomes

Together these videos target MO4 directly. The Python Simplified tutorial establishes list comprehension syntax and conditional filtering in depth; the Ridwanray tutorial extends that same pattern to dictionary and set comprehensions so you can produce all three required forms; and the Python Morsels screencast gives you a reliable loop-to-comprehension translation procedure that generalizes to nested iteration, where clause order is the usual stumbling block. Watching all three also prepares you for MO5, since recognizing when a comprehension stays readable is the basis for later deciding between comprehensions and map(), filter(), or lambda expressions.

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.

Lambda Functions and Functional Patterns

Introduction

So far in this module you have written functions with def, given them names, and called them by those names. Python also lets you create small, unnamed functions on the fly using the lambda keyword. A lambda is limited to a single expression, and its value is the result of that expression, which makes it useful whenever a function is needed only briefly — most often as an argument passed to another function.

That pattern of passing functions as arguments is the heart of functional programming in Python. The built-ins map() and filter() each take a function plus an iterable: map() applies the function to every item and produces the transformed results, while filter() keeps only the items for which the function returns a truthy value. Combining them lets you transform and select in one pipeline. Because these tools return lazy iterators rather than lists, you will usually wrap them in list() or loop over them to see the results.

The practical question for this course is not whether you can write map() and filter(), but when you should. Comprehensions often express the same logic more readably, and a named def function is clearer than a complicated lambda. As you watch, pay attention to the syntax rules (what a lambda can and cannot contain), to how each video converts the result of map() or filter() into a visible list, and especially to any guidance on readability — that judgment is what you will be assessed on.

Video 1: Lambda functions in Python | Python Tutorial - Day #52

CodeWithHarry · 9:18 · 402,382 views · 3y ago · captions — Watch on YouTube

About this video

A focused introduction to lambda (anonymous) functions in Python, covering the lambda syntax, how arguments and the single return expression work, and how a lambda compares to an equivalent function defined with def. As part of a day-by-day beginner tutorial series, it is likely to walk through small live-coded examples you can retype yourself.

Why this video

It isolates the Lambda Functions subtopic cleanly before map() and filter() are introduced, and CodeWithHarry's step-by-step style makes the compact syntax easy to follow for students new to anonymous functions.

Video 2: Map, Filter and Reduce in Python | Python Tutorial - Day #53

CodeWithHarry · 13:01 · 363,497 views · 3y ago · captions — Watch on YouTube

About this video

The follow-up lesson in the same series, demonstrating map(), filter(), and reduce() and how each one takes a function — commonly a lambda — together with an iterable. Expect worked examples showing transformation with map(), selection with filter(), and the need to convert results to a list to display them; reduce() goes slightly beyond this topic but reinforces the same pattern.

Why this video

It directly covers The map() Function, The filter() Function, and Combining map and filter, and because it continues straight from the lambda video it shows lambdas in their most common real setting.

Video 3: Python's map and filter functions

Python Morsels · 4:40 · 510 views · 3y ago · captions — Watch on YouTube

About this video

A short, tightly scoped explanation of how Python's built-in map and filter functions work, including their lazy iterator behavior, and a discussion of whether to reach for them or for a list comprehension instead. Python Morsels videos are deliberately brief and concept-focused rather than long walkthroughs.

Why this video

This is the clearest fit for the Choosing Between Comprehensions and Functional Tools subtopic, and Python Morsels is a well-regarded source for precise, idiomatic Python guidance on exactly this kind of style decision.

How These Videos Support the Learning Outcomes

Together these videos target MO5 most directly: the first builds fluency with lambda syntax, the second shows map() and filter() in action (alone and combined), and the third supplies the comparison with comprehensions that lets you argue for one approach over another on readability grounds. They also reinforce MO1 and MO4 by contrasting throwaway lambdas with reusable def functions and by placing functional pipelines side by side with the comprehensions you practiced earlier in the module. Watch them in the listed order, then try rewriting a few of your own comprehensions as map()/filter() pipelines — and back again — to test which version you find easier to read.

About These Videos

These videos were chosen from YouTube on October 2, 2026. Each has captions; the player turns them on. Videos on YouTube can be changed or removed — if one no longer plays, tell your instructor. If a player does not appear, use its Watch on YouTube link.