> ## 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 Functions

## 1. **What is a Function?**

* A **function** is a reusable block of code that performs a specific task.
* Functions help in organizing code, reducing redundancy, and improving readability.
* In Python, functions are defined using the `def` keyword.

## 2. **Defining a Function**

* Use the `def` keyword followed by the function name and parentheses `()`.
* Parameters (inputs) can be included inside the parentheses.
* The function body is indented and contains the code to be executed.
* Use the `return` statement to send a value back to the caller.

**Syntax**:

```python theme={"system"}
def function_name(parameters):
    # Function body
    return value  # Optional
```

**Example**:

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

## 3. **Calling a Function**

* To use a function, you need to call it by its name followed by parentheses `()`.
* If the function has parameters, pass the required arguments inside the parentheses.

**Example**:

```python theme={"system"}
message = greet("Raj")
print(message)  # Output: Hello, Raj!
```

## 4. **Function Parameters and Arguments**

* **Parameters**: Variables listed inside the parentheses in the function definition.
* **Arguments**: Values passed to the function when it is called.

**Example**:

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

result = add(5, 10)  # 5 and 10 are arguments
print(result)  # Output: 15
```

## 5. **Types of Arguments**

* **Positional Arguments**: Arguments are passed in the order of parameters.
  ```python theme={"system"}
  def greet(name, age):
      return f"Hello, {name}! You are {age} years old."

  print(greet("Ram", 25))  # Output: Hello, Ram! You are 25 years old.
  ```

* **Keyword Arguments**: Arguments are passed with the parameter name.
  ```python theme={"system"}
  print(greet(age=30, name="Anand"))  # Output: Hello, Anand! You are 30 years old.
  ```

* **Default Arguments**: Parameters have default values if no argument is provided.
  ```python theme={"system"}
  def greet(name, age=18):  # age has a default value of 18
      return f"Hello, {name}! You are {age} years old."

  print(greet("Bala"))  # Output: Hello, Bala! You are 18 years old.
  ```

* **Variable-Length Arguments**:

  * `*args`: Accepts any number of positional arguments as a tuple.
  * `**kwargs`: Accepts any number of keyword arguments as a dictionary.

  **Example**:

  ```python theme={"system"}
  def print_names(*args):
      for name in args:
          print(name)

  print_names("Karthik", "Kumar", "David")  # Prints all names

  def print_details(**kwargs):
      for key, value in kwargs.items():
          print(f"{key}: {value}")

  print_details(name="Kannan", age=28, city="Chennai")
  ```

## 6. **Return Values**

* The `return` statement is used to send a value back to the caller.
* A function can return multiple values as a tuple.

**Example**:

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

result = calculate(10, 5)
print(result)  # Output: (15, 5)
```

## 7. **Scope of Variables**

* **Local Variables**: Variables defined inside a function are local to that function.
* **Global Variables**: Variables defined outside a function can be accessed globally.
* Use the `global` keyword to modify a global variable inside a function.

**Example**:

```python theme={"system"}
x = 10  # Global variable

def update_x():
    global x
    x = 20  # Modifying the global variable

update_x()
print(x)  # Output: 20
```

## 8. **Lambda Functions (Anonymous Functions)**

* Lambda functions are small, anonymous functions defined using the `lambda` keyword.
* They can have any number of arguments but only one expression.

**Syntax**:

```python theme={"system"}
lambda arguments: expression
```

**Example**:

```python theme={"system"}
square = lambda x: x ** 2
print(square(5))  # Output: 25
```

## 9. **Additional Examples**

* **Simple Function**:
  ```python theme={"system"}
  def greet_person(name):
      return f"Good morning, {name}!"

  print(greet_person("Siva"))  # Output: Good morning, Siva!
  ```

* **Function with Default Argument**:
  ```python theme={"system"}
  def greet_person(name, city="Chennai"):
      return f"Hello, {name}! Welcome to {city}."

  print(greet_person("Ramesh"))  # Output: Hello, Ramesh! Welcome to Chennai.
  print(greet_person("Suresh", "Bangalore"))  # Output: Hello, Suresh! Welcome to Bangalore.
  ```

* **Function with Variable-Length Arguments**:
  ```python theme={"system"}
  def print_scores(**kwargs):
      for subject, score in kwargs.items():
          print(f"{subject}: {score}")

  print_scores(math=95, science=89, english=92)
  # Output:
  # math: 95
  # science: 89
  # english: 92
  ```

* **Lambda Function**:
  ```python theme={"system"}
  is_even = lambda x: x % 2 == 0
  print(is_even(10))  # Output: True
  ```

## 10. **Best Practices**

* Use descriptive function names to indicate their purpose.
* Keep functions small and focused on a single task.
* Use comments to explain complex logic.
* Avoid using too many global variables.
