> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/python/basic/functions.md).

# Functions

Functions in Python help organize code into **reusable**, **modular**, and **maintainable** blocks. A well-structured Python script typically includes **helper functions**, a **main()** function, and the `if __name__ == "__main__":` guard.

***

### **1. Basic Function Structure**

A function is defined using the `def` keyword.

```python
def function_name(parameters):
    """
    This is a docstring that describes what the function does.
    """
    # Function body (logic goes here)
    return result
```

#### **Key Components**

| Component       | Description                                    |
| --------------- | ---------------------------------------------- |
| `def`           | Keyword to define a function                   |
| `function_name` | The name of the function                       |
| `parameters`    | Inputs passed to the function (optional)       |
| Function body   | Contains logic or computation                  |
| `return`        | Sends the result back to the caller (optional) |

***

### **2. Simple Example**

```python
def greet(name):
    """
    Returns a greeting message for the given name.
    """
    return f"Hello, {name}!"
```

#### **Usage**

```python
message = greet("Alice")
print(message)
```

**Output:**

```
Hello, Alice!
```

***

### **3. Using `main()` and `__name__ == "__main__"`**

Organizing your script with a `main()` function and a proper entry point is a **Python best practice**.

#### **Example**

```python
def greet(name):
    """
    Returns a greeting message for the given name.
    """
    return f"Hello, {name}!"

def main():
    """
    Main function to handle program logic.
    """
    name = input("Enter your name: ")
    message = greet(name)
    print(message)

if __name__ == "__main__":
    main()
```

***

### **4. Step-by-Step Explanation**

| Part                             | Purpose                                                                               |
| -------------------------------- | ------------------------------------------------------------------------------------- |
| **`greet(name)`**                | A helper function that creates a greeting message.                                    |
| **`main()`**                     | The main function that manages program flow — input, logic, output.                   |
| **`if __name__ == "__main__":`** | Ensures the code runs **only** when executed directly, not when imported as a module. |

***

### **5. Running the Script**

#### **Run Directly:**

```bash
python script.py
```

**Output:**

```
Enter your name: Alice
Hello, Alice!
```

#### **When Imported:**

```python
import script
print(script.greet("Bob"))
```

**Output:**

```
Hello, Bob!
```

> 💡 The `main()` function won’t execute automatically when imported — only `greet()` will be available.

***

### **6. Another Example — Calculation Script**

```python
def add_numbers(a, b):
    """
    Returns the sum of two numbers.
    """
    return a + b

def main():
    """
    Main function to handle user input and display result.
    """
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    result = add_numbers(num1, num2)
    print(f"The sum is: {result}")

if __name__ == "__main__":
    main()
```

**Output:**

```
Enter the first number: 5
Enter the second number: 10
The sum is: 15
```

***

### **7. Why This Structure Matters**

| Benefit                   | Explanation                                                |
| ------------------------- | ---------------------------------------------------------- |
| **Reusability**           | Functions can be imported and reused in other programs.    |
| **Modularity**            | Logic is broken into smaller, easier-to-understand pieces. |
| **Professional Practice** | This is the standard format for Python scripts.            |
| **Safe Imports**          | Prevents code from running automatically when imported.    |

***

### **8. Summary**

| Component                    | Purpose                                                  |
| ---------------------------- | -------------------------------------------------------- |
| **Helper Functions**         | Handle specific tasks (`greet()`, `add_numbers()`, etc.) |
| **Main Function**            | Entry point for user input and program logic             |
| **`__name__ == "__main__"`** | Controls script execution and import behavior            |
