Python Functions: A Complete Guide from Basics to Advanced
Master Python functions with our comprehensive guide covering definitions, arguments, returns, lambda, decorators, and best practices.
Python Functions: A Complete Guide
What is a Function?
A function is a reusable block of code that performs a specific task. Functions help you:
- Write DRY (Don''t Repeat Yourself) code
- Organize complex logic
- Make code maintainable
- Enable code reuse
Defining Functions
```python
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
```
Function Arguments
Positional Arguments
```python
def add(a, b):
return a + b
```
Default Arguments
```python
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 (uses default exp=2)
print(power(2, 10)) # 1024
```
Keyword Arguments
```python
def describe(name, age, city="Unknown"):
return f"{name}, {age}, from {city}"
print(describe(age=30, name="Bob"))
```
Variable Arguments (*args, **kwargs)
```python
def report(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
```
Return Values
Functions can return single or multiple values:
```python
def get_coordinates():
return 10, 20 # Returns tuple
x, y = get_coordinates()
```
Lambda Functions
Anonymous functions for simple operations:
```python
square = lambda x: x * x
print(square(5)) # 25
nums = [1, 2, 3, 4]
squared = list(map(lambda n: n ** 2, nums))
```
Best Practices
- Use clear names: `calculate_total` not `calc`
- Single responsibility: Function does one thing
- Document with docstrings: Explain what it does
- Keep functions small: Under 20 lines ideally
- Use type hints: Help others understand types
```python
def add(a: int, b: int) -> int:
"""Add two numbers and return the result."""
return a + b
```
By PythonExecutor Team