python function
python function
---
### **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}!")
```
---
```python
greet("Alice") # Output: Hello, Alice!
```
---
```python
def add(a, b): # a and b are parameters
return a + b
---
```python
def square(x):
return x * x
print(square(4)) # Output: 16
```
---
```python
def power(base, exponent=2): # Default exponent=2
return base ** exponent
---
```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.
```
---
---
## **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
```
---
```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
```
---
---
## **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)` |
---