# **Python Functions: A Complete Guide**
A **function** in Python is a reusable block of code that performs a specific task.
Functions help in organizing code, reducing repetition, and improving readability.
---
## **1. Defining a Function**
Use the `def` keyword followed by the function name and parentheses `()`.
### **Syntax:**
```python
def function_name(parameters):
"""Docstring (optional)"""
# Function body (code)
return value # Optional
```
### **Example:**
```python
def greet(name):
"""This function greets the user."""
print(f"Hello, {name}!")
```
---
## **2. Calling a Function**
To execute a function, call it by its name followed by parentheses.
```python
greet("Alice") # Output: Hello, Alice!
```
---
## **3. Parameters vs. Arguments**
- **Parameter** → Variable in the function definition.
- **Argument** → Value passed to the function when calling it.
```python
def add(a, b): # a and b are parameters
return a + b
result = add(3, 5) # 3 and 5 are arguments
print(result) # Output: 8
```
---
## **4. Return Statement**
- A function can return a value using `return`.
- If no `return` is given, it returns `None`.
```python
def square(x):
return x * x
print(square(4)) # Output: 16
```
---
## **5. Default Arguments**
You can set default values for parameters.
```python
def power(base, exponent=2): # Default exponent=2
return base ** exponent
print(power(3)) # Output: 9 (3^2)
print(power(3, 3)) # Output: 27 (3^3)
```
---
## **6. Keyword Arguments**
Pass arguments by parameter name (order doesn’t matter).
```python
def describe_pet(name, animal="dog"):
print(f"I have a {animal} named {name}.")
describe_pet(animal="cat", name="Whiskers")
# Output: I have a cat named Whiskers.
```
---
## **7. Variable-Length Arguments**
- `*args` → Accepts any number of positional arguments (as a **tuple**).
- `**kwargs` → Accepts any number of keyword arguments (as a **dictionary**).
### **Example with `*args`:**
```python
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
```
### **Example with `**kwargs`:**
```python
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
```
---
## **8. Lambda (Anonymous) Functions**
- Small, one-line functions defined with `lambda`.
- No `return` statement needed.
### **Syntax:**
```python
lambda arguments: expression
```
### **Example:**
```python
double = lambda x: x * 2
print(double(5)) # Output: 10
```
---
## **9. Scope of Variables**
- **Local variable** → Defined inside a function (accessible only inside).
- **Global variable** → Defined outside a function (accessible everywhere).
```python
x = 10 # Global variable
def my_func():
y = 5 # Local variable
print(x + y) # Can access global x
my_func() # Output: 15
print(y) # Error: y is not defined globally
```
---
## **10. Recursion (Function Calling Itself)**
A function can call itself (useful for problems like factorial, Fibonacci).
### **Example (Factorial):**
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5! = 5*4*3*2*1)
```
---
## **Summary Table**
| Feature | Example |
|---------|---------|
| Define a function | `def greet():` |
| Return a value | `return x + y` |
| Default argument | `def func(a=1):` |
| Keyword argument | `func(name="Alice")` |
| Variable arguments | `*args`, `**kwargs` |
| Lambda function | `lambda x: x * 2` |
| Recursion | `factorial(n-1)` |
---
### **Key Takeaways**
✅ Functions are defined using `def`.
✅ Use `return` to send back a value.
✅ `*args` for multiple positional arguments.
✅ `**kwargs` for multiple keyword arguments.
✅ `lambda` for small anonymous functions.
✅ Recursion allows a function to call itself.
Would you like more examples or explanations on any part? 😊