Module lessons (1/4)
def and return
Function syntax with def, explicit vs implicit None return, positional parameters, and docstrings.
What you'll learn in this lesson
- Define modular functions with
def, self-documenting docstrings, and explicitreturnstatements. - Distinguish between
return <valore>and the implicit default valueNone, using early-return as the guard clause. - Understand LEGB name resolution (Local -> Enclosing -> Global -> Built-in) between call frame and module.
Overview
A function encapsulates reusable logic under a meaningful name, accepts input via parameters, and returns output to the caller. With each call, Python creates a new Local frame on the stack, isolates the temporary variables there, and destroys them as soon as it encounters return.
When a function reads a variable, Python searches strictly in four scopes from closest to widest (LEGB: Local -> Enclosing -> Global -> Built-in). Everything assigned inside def is Local by default: it never dirty the global module and disappears at the end of the call.
Sections covered in this lesson
- 1The mental model: Stack Frame and LEGB research
- 2Basic syntax, multiple returns and implicit
None - 3Early return, local variables and LEGB
- 4Quick check
- 5Test yourself
Unlock "def and return" and the full Python Course curriculum
Function syntax with def, explicit vs implicit None return, positional parameters, and docstrings.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.