Python: Functions
Python Functions
1 Overview
📘 Functions in Python
Python functions are blocks of code that perform a specific task and can be called by their name. Functions are defined using the def keyword, followed by the function name and parentheses. The code block within the function is indented and executed when the function is called. Functions can take parameters, which are values that are passed to the function when it is called. Functions can also return values, which are the results of the function’s execution. Functions are a fundamental concept in programming and are used to break down complex problems into smaller, more manageable pieces.
Dictionaries can be created using literals with curly braces, the dict() constructor, or comprehensions. They are versatile for associating data where keys serve as unique identifiers for their values, facilitating fast data retrieval and modification.
2 Functions
Functions in Python are characterized by several key aspects:
- Definition and Structure: Functions are defined using the
defkeyword, followed by a unique name and parentheses that may include parameters. The body of the function contains the code to execute, indented according to Python syntax rules. - Parameters and Arguments: Functions can accept input through parameters—values provided to the function when it is called. These parameters allow functions to operate on different data inputs dynamically. Python supports various argument types, such as positional, keyword, default, and variable-length arguments.
- Return Values: Functions can produce output using the
returnstatement, passing a value back to the caller. Not all functions need to return a value; some perform actions without returning data, such as printing to the console. - Built-in vs User-defined: Python offers built-in functions like
len(),type(),print(),int()andrange(), which perform common tasks. Users can also create their own functions, known as user-defined functions, tailored to specific needs. - Function Types:
- Recursive functions call themselves to solve problems through self-reference.
- Anonymous (lambda) functions are small, unnamed functions created with the
lambdakeyword, mainly for short operations. - Higher-order functions accept other functions as parameters or return functions as results, enabling functional programming paradigms.
- Function Scope and Lifetime: Functions define a scope—variables created within a function are local to that function unless declared otherwise. This encapsulation helps prevent unintended side effects.
Overall, Python functions are central to writing clean, efficient, and maintainable code by encapsulating reusable logic, managing data flow, and supporting various programming styles, including procedural, functional, and object-oriented paradigms.
3 Function creation
- Functions are defined using the
defkeyword. - Input variables (parameters/arguments), are specified between parentheses.
Function definition:
This function can now be used anywhere in the code.
Call our greet function with the argument “Alice”.
- Optionally, use the
returnstatement to return a value from the function:
- Now we can assign the returned value of
greet()to a variable. - Notice that by default this prints nothing.
- We can print the variables:
Hello, Bob!
- When a value is returned, python exits the function, not executing the rest of the code in the function.
Hello, Alice!
- We could also use an “empty return” to exit the function.
- This does not return any value.
4 Built-in Functions in Python
- Built-in functions are regular functions that Python provides by default.
- Example: how
sum()could be implemented in Python:
5 Positional arguments
- Positional arguments are passed in the order they are defined.
"Aclie"and30have the same order asnameandagein the definition:
- If we swap the order of the arguments,
nameandagehave different values inside the function:
- We get an error if we don’t pass in the correct number of arguments:
6 Keyword arguments
- Are passed by specifying the parameter name and its value.
- When specifying the names, we can follow any order we like.
7 Optional arguments
- Have default values.
- Don’t give an error if the optional argument is omitted.
- When calling the greet function without providing a value for
age, the function will use the default value instead:
- We can define any number of optional arguments.
- They must be defined at the tail of the function parameters:
- We get an error if we define a non-default argument (
name) after a default one (age).
8 Parameters vs Arguments
In programming, particularly in Python, the terms “parameters” and “arguments” have distinct meanings:
Parameters:
- Variables defined within the parentheses of a function definition.
- Act as placeholders for the values that will be passed to the function.
Arguments:
- Actual values passed to a function when it is called.
- Values are assigned to the corresponding parameters in the function definition.
- However, these terms are often used interchangeably in practice (a lot!).
9 Variable scope
- Determines the accessibility of a variable.
- Local variables can only be accessed inside a particular function.
- Global variables can be accessed throughout the entire program.
9.1 Global Variable
I am a global variable.
9.2 Local Variable
NameError: name ‘var2’ is not defined.
10 Variables as Parameters
- A function always uses the names defined as parameters.
- Even if variable names are different outside the function.
- May be confusing for beginners.
11 Best practices
- Use descriptive names for functions and parameters.
- Follow the PEP 8 naming conventions
- Function names should be in snake case.
- Each function should perform one specific task.
- To make your functions easy to understand and use, document them.
12 Example of function documentation
13 Recursion
- Recursion is a technique in which a function calls itself.
- Recursive functions need:
- Base case, which is the condition that stops the recursion.
- Recursive case, which is the part that calls the function itself.
- Example countdown:
2
1
GO!!!
- Recursion should always have a base case to stop the recursion!
- Otherwise, the function will call itself indefinitely, leading to an error:
-2
-3
…
-2967
-2968
-2969
RecursionError: maximum recursion depth exceeded while calling a Python object
- Example factorial:
- Example Fibonacci:
14 Type Hints
- Also known as type annotations.
- Programmer provides hints to the expected types of a function’s input parameters and return value (->).
- Help make the code:
- More readable.
- Self-documenting.
- Easier to maintain.
- Can be used by other tools: linters, code editors, static type checkers.
- Example: