Functions & Scope

Defining functions, parameters, return values, variable scope

6 free lessons available

Start here

Defining & Calling Functions

As your programs grow, you'll find yourself writing the same logic multiple times. This repetition makes code harder to read, maintain, and debug. Functions provide a solution by allowing you to encapsulate a block of reusable code, giving it a name, and executing it whenever needed. They are the fundamental building blocks for organizing complex software into manageable, logical units.

What is a Function?

Function
A named sequence of statements that performs a specific task. Functions allow you to break down complex problems into smaller, more manageable pieces, promoting code reusability and modularity.
Example: A function named calculate_area that takes length and width as inputs and returns their product.

Think of a function as a mini-program within your main program. It has a defined purpose, takes inputs, performs operations, and often produces an output. This abstraction helps manage complexity: once a function is written and tested, you can use it confidently without needing to remember its internal workings, focusing instead on what it accomplishes.

Defining a Function: The def Keyword

In Python, you define a function using the def keyword, followed by the function's name, a pair of parentheses (), and a colon :. The code block that constitutes the function's body must be indented. This indentation signals which statements belong to the function. A function definition simply creates the function; it does not execute it.

pythonBasic Function Definition
⚠️ Indentation is Critical

Python uses indentation to define code blocks. Incorrect indentation will lead to IndentationError or unexpected behavior. Ensure all statements within a function's body are consistently indented, typically by four spaces.

Function Parameters

Parameter
A placeholder variable listed inside the parentheses in a function's definition. Parameters act as inputs that the function expects to receive when it is called.
Example: In def greet(name):, name is a parameter.

Functions often need specific pieces of information to perform their task. These inputs are defined as parameters within the parentheses of the function definition. Parameters are essentially local variables that get their values from the caller when the function is invoked. You can define multiple parameters, separating them with commas.

pythonFunction with Parameters

The return Statement

While print() displays output to the console, the return statement is used to send a value back from the function to the point where it was called. This allows functions to produce results that can be used in further calculations or assignments. If a function doesn't explicitly include a return statement, it implicitly returns None.

pythonReturning a Value from a Function
Check Your Understanding
What is the primary difference between print() and return within a function?

Calling a Function: Invocation

Defining a function only makes it available for use; it doesn't execute the code inside it. To run the function's code, you must call or invoke it. This is done by writing the function's name followed by parentheses (). If the function expects parameters, you provide values, known as arguments, inside these parentheses.

Argument
The actual value passed into a function when it is called. Arguments correspond to the parameters defined in the function's signature.
Example: In greet("Alice"), "Alice" is an argument.
pythonCalling Functions with and without Arguments

Positional vs. Keyword Arguments

When calling a function, you can pass arguments in two main ways: by position or by keyword. Positional arguments are matched to parameters based on their order. The first argument goes to the first parameter, the second to the second, and so on. Keyword arguments are explicitly named, matching the argument to a parameter by its name, which allows you to pass them in any order.

pythonUsing Positional and Keyword Arguments
✨ Readability with Keyword Arguments

For functions with many parameters, especially boolean flags or parameters with default values, using keyword arguments significantly improves code readability. It makes the purpose of each argument explicit, reducing potential errors from incorrect ordering.

Check Your Understanding
Which statement about mixing positional and keyword arguments is true?

Parameters vs. Arguments

The terms 'parameter' and 'argument' are often used interchangeably, but they have distinct meanings in programming. Understanding this difference is key to writing and debugging functions effectively. Parameters are part of the function's definition, acting as named slots for inputs. Arguments are the actual values supplied to those slots when the function is called.

Parameters vs. Arguments
FeatureParametersArguments
RolePlaceholders for inputsActual values passed to inputs
LocationFunction definition (signature)Function call (invocation)
NatureVariables that receive valuesExpressions or literals
Exampledef func(a, b): (a, b are parameters)func(10, 20) (10, 20 are arguments)
Parameters define what a function expects; arguments provide those expectations.

Function Execution Flow

When a function is called, the program's execution flow temporarily transfers control from the calling code to the function's body. The function executes its statements, potentially using the arguments passed to it. Once the function encounters a return statement or reaches the end of its body, control returns to the point in the calling code immediately after the function call. Any value returned by the function is then available at that point.

Function Call Execution Flow
Loading diagram...
This diagram illustrates the sequence of operations when a function is invoked and returns control to the caller.

Docstrings for Function Documentation

Good documentation is essential for maintainable code. Python functions support docstrings, which are string literals that appear immediately after the def line. Docstrings provide a concise summary of the function's purpose, its parameters, what it returns, and any exceptions it might raise. They are accessible at runtime via function_name.__doc__ and are used by documentation tools and IDEs.

pythonDocumenting Functions with Docstrings
Try It Yourself
Modify the calculate_average function. Add a new parameter precision (an integer) that specifies the number of decimal places for the returned average. Use Python's round() function before returning the value. Test it with precision=2 and precision=0.
python
Key Takeaways
  • Functions are defined using the def keyword, followed by a name, parentheses, and a colon, with an indented body.

  • Parameters are placeholders in the function definition, while arguments are the actual values passed during a function call.

  • The return statement sends a value back from the function to the caller; functions without return implicitly return None.

  • Functions are executed by calling their name with parentheses, providing arguments that match the defined parameters.

  • Arguments can be passed positionally (order matters) or as keyword arguments (name matters), with positional arguments always preceding keyword arguments when mixed.

  • Docstrings (triple-quoted strings after def) are crucial for documenting a function's purpose, parameters, and return values, enhancing code readability and maintainability.

Open this lesson on its own page →

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free