Introduction
Functions are a convenient way to organize your code into reusable and modular blocks. They improve readability, reusability, and efficiency by allowing you to:
- Divide complex tasks into smaller, manageable parts.
- Avoid repeating the same code.
- Define clear interfaces for sharing code with others.
Defining Functions
In Python, you define a function using the def keyword, followed by:
- The function name.
- Parentheses
()containing optional parameters. - A colon
:. - An indented block of code to execute.
Syntax
| |
Example: Simple Function
Print numbers from start to stop-1 with a given step:
| |
Output:
| |
Return Values
The return statement is used to send a value back to the caller of the function. If no return statement is used, the function returns None by default.
Example: Function with Return
Calculate the volume of a sphere:
| |
Output:
| |
Function Parameters
Parameters allow you to pass data into a function. They are defined inside the parentheses when declaring the function.
Types of Parameters
- Positional Parameters: Order matters.
- Keyword Parameters: Specified by name.
- Default Parameters: Assigned a default value if not provided.
- Variable-Length Parameters: Use
*argsfor arbitrary positional arguments and**kwargsfor arbitrary keyword arguments.
Example: Default Parameters
| |
Output:
| |
Example: Variable-Length Parameters
| |
Output:
| |
Variable Scope
Variables in Python have scope, which determines where they can be accessed.
Local Variables
- Defined inside a function.
- Only accessible within that function.
Global Variables
- Defined outside any function.
- Accessible anywhere in the code.
The global Keyword
To modify a global variable inside a function, use the global keyword.
Example: Local vs. Global Variables
| |
Output:
| |
Example: Modifying Global Variables
| |
Lambda Functions
Lambda functions are small, anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.
Syntax
| |
Example: Lambda Function
Square a number:
| |
Comprehensions
Comprehensions provide a concise way to create sequences (lists, sets, dictionaries) in Python.
List Comprehension
Syntax:
| |
Example: List Comprehension
Create a list of squares for numbers from 1 to 5:
| |
With condition:
| |
Set Comprehension
Syntax:
| |
Example: Set Comprehension
Create a set of squares for numbers from 1 to 5:
| |
With condition:
| |
Dictionary Comprehension
Syntax:
| |
Example: Dictionary Comprehension
Create a dictionary of numbers and their squares:
| |
With condition:
| |
Comprehension with if-else
You can use if-else logic within comprehensions.
Example: List Comprehension with if-else
Replace the word “the” with 0 in a list of word lengths:
| |
Example: Dictionary Comprehension with if-else
Create a dictionary with word lengths, replacing “the” with 0:
| |
| |
Nested Functions
You can define a function inside another function. The nested function is only accessible within the outer function.
Example: Nested Function
| |
Recursive Functions
A recursive function is a function that calls itself. It must have a base case to stop the recursion.
Example: Factorial with Recursion
| |
Docstrings
Docstrings are used to document functions. They are enclosed in triple quotes (""" or ''').
Example: Function with Docstring
| |
Conclusion
Functions are a powerful tool in Python for organizing, reusing, and sharing code. Key takeaways:
- Use
defto define functions. - Use
returnto send back results. - Understand variable scope (local vs. global).
- Use lambda functions for small, anonymous tasks.
- Use comprehensions for concise sequence creation.
- Document your functions with docstrings.