> ## Documentation Index
> Fetch the complete documentation index at: https://rajanand.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Function Examples

> Python Function Examples with code

## 1. Basic Function

```python theme={"system"}
def greet():
    print("Hello, World!")

greet()
```

## 2. Function with Arguments

```python theme={"system"}
def greet(name):
    print(f"Hello, {name}!")

greet("Raj")
```

## 3. Function with Default Arguments

```python theme={"system"}
def greet(name="World"):
    print(f"Hello, {name}!")

greet()
greet("Raj")
```

## 4. Function with Return Statement

```python theme={"system"}
def add(a, b):
    return a + b

result = add(10, 5)
print(f"Addition: {result}")
```

## 5. Function with Multiple Return Statements

```python theme={"system"}
def add_sub(a, b):
    return a + b, a - b

add, sub = add_sub(10, 5)
print(f"Addition: {add}, Subtraction: {sub}")    
```

## 6. Function with Keyword Arguments

```python theme={"system"}
def greet(name, message):
    print(f"{message}, {name}!")

greet(name="Raj", message="Good Morning")    
```

## 7. Function with Arbitrary Arguments

```python theme={"system"}
def greet(*names):
    for name in names:
        print(f"Hello, {name}!")

greet("Raj", "Kumar", "Bala")
```

## 8. Function with Docstring

```python theme={"system"}
def greet(name):
    """
    This function greets the person passed in as a parameter
    """
    print(f"Hello, {name}!")

greet("Raj")
print(greet.__doc__)
```

## 9. Function with Lambda

```python theme={"system"}
add = lambda a, b: a + b
result = add(10, 5)
print(f"Addition: {result}")
```

## 10. Function with Recursion

```python theme={"system"}
def factorial(n):
    if n in (0, 1):
        return 1
    else:
        return n * factorial(n - 1)

result = factorial(5)
print(f"Factorial: {result}")
```

## 11. Function with Global Variables

```python theme={"system"}
x = 10

def display():
    print(f"Value of x: {x}")

display()
```

## 12. Function with Local Variables

```python theme={"system"}
def display():
    y = 20
    print(f"Value of y: {y}")

display()
```

## 13. Function with Nonlocal Variables

```python theme={"system"}
def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
        print(f"Inner: {x}")
    inner()
    print(f"Outer: {x}")

outer()
```

Output:

```txt theme={"system"}
Inner: 20
Outer: 20
```

The `nonlocal` keyword is used inside a nested function to modify a variable from its enclosing (non-global) scope. Without nonlocal, assigning a new value to a variable inside a nested function creates a new local variable instead of modifying the one from the outer function.

## 14. Function with Global Keyword

```python theme={"system"}
def display():
    global z
    z = 30
    print(f"Value of z: {z}")

display()
print(f"Value of z: {z}")
```

Output:

```markdown theme={"system"}
Value of z: 30
Value of z: 30
```

## 15. Function with Pass Statement

```python theme={"system"}
def display():
    pass

display()
```

## 16. Function with Recursion Limit

```python theme={"system"}
import sys

sys.setrecursionlimit(200)

def factorial(n):
    if n in (0, 1):
        return 1
    else:
        return n * factorial(n - 1)

result = factorial(100)
print(f"Factorial: {result}")
```

## 17. Function with Annotations

```python theme={"system"}
def greet(name: str) -> None:
    print(f"Hello, {name}!")

greet("Raj")
print(greet.__annotations__)
```

## 18. Function with Annotations and Return Type

```python theme={"system"}
def add(a: int, b: int) -> int:
    return a + b

result = add(10, 5)
print(f"Addition: {result}")
print(add.__annotations__)
```

## 19. Function with Annotations and Default Arguments

```python theme={"system"}
def greet(name: str = "World") -> None:
    print(f"Hello, {name}!")

greet()
greet("Raj")
print(greet.__annotations__)
```

## 20. Function with Annotations and Multiple Return Statements

```python theme={"system"}
def add_sub(a: int, b: int) -> tuple:
    return a + b, a - b

add, sub = add_sub(10, 5)
print(f"Addition: {add}, Subtraction: {sub}")
print(add_sub.__annotations__)
```

## 21. Function with Annotations and Keyword Arguments

```python theme={"system"}
def greet(name: str, message: str) -> None:
    print(f"{message}, {name}!")

greet(name="Raj", message="Good Morning")
print(greet.__annotations__)
```

## 22. Function with Annotations and Arbitrary Arguments

```python theme={"system"}
def greet(*names: str) -> None:
    for name in names:
        print(f"Hello, {name}!")

greet("Raj", "Kumar", "Bala")
print(greet.__annotations__)
```

## 23. Function with Annotations and Lambda

Lambda function does not support annotations.

## 24. Function Decorators

```python theme={"system"}
def uppercase_decorator(function):
    def wrapper():
        result = function()
        return result.upper()
    return wrapper

def greet():
    return "Hello, World!"

greet = uppercase_decorator(greet)
print(greet())
```

## 25. Function with Decorator Syntax

```python theme={"system"}
def uppercase_decorator(function):
    def wrapper():
        result = function()
        return result.upper()
    return wrapper

@uppercase_decorator
def greet():
    return "Hello, World!"

print(greet())
```

## 26. Function with Multiple Decorators

```python theme={"system"}
def uppercase_decorator(function):
    def wrapper():
        result = function()
        return result.upper()
    return wrapper

def split_decorator(function):
    def wrapper():
        result = function()
        return result.split()
    return wrapper

@split_decorator
@uppercase_decorator
def greet():
    return "Hello, World!"

print(greet())
```

## 27. Function with Arguments in Decorator

```python theme={"system"}
def decorator_with_args(function):
    def wrapper(*args, **kwargs):
        print("Arguments:", args, kwargs)
        result = function(*args, **kwargs)
        return result.upper()
    return wrapper

@decorator_with_args
def greet(name):
    return f"Hello, {name}!"

print(greet("Raj"))
```

## 28. Advanced Function

```python theme={"system"}
def apply(func, x):
    return func(x)

def add(x):
    return x + 1

def sub(x):
    return x - 1

def square(x):
    return x * x

print(apply(add, 10))
print(apply(sub, 10))
print(apply(square, 10))
```

## 29. Function with Nested Functions

```python theme={"system"}
def outer():
    def inner():
        print("Inner Function")
    inner()
    print("Outer Function")

outer()
```

## 30. Function with Nested Functions and Closures

```python theme={"system"}
def outer():
    x = 10
    def inner():
        print(f"Value of x: {x}")
    return inner

inner = outer()
inner()
```

* Closure Concept – inner() is a closure because it captures and retains access to x = 10 from outer() even after outer() has finished executing.
* Function Reference – outer() returns inner without calling it, so inner becomes a function reference that can be executed later.
* Execution Flow – Calling outer() assigns x = 10, returns inner, and when inner() is called, it prints "Value of x: 10".
* Variable Retention – Even though outer() is done executing, Python keeps x = 10 alive inside inner() due to the closure mechanism.
* Encapsulation – This technique avoids global variables, keeps data within functions, and allows multiple closures to store different values.
