> Source URL: /resources/functions.guide
# Functions

A function is a reusable block of code that performs a specific task.

## Defining a Function

```python
def greet():
    print("Hello!")

greet()
```

Output:

```
Hello!
```

## Parameters

Parameters let you pass data into a function:

```python
def greet(name):
    print("Hello, " + name + "!")

greet("Alice")
greet("Bob")
```

Output:

```
Hello, Alice!
Hello, Bob!
```

## Multiple Parameters

```python
def greet(name, time_of_day):
    print("Good " + time_of_day + ", " + name + "!")

greet("Alice", "morning")
```

Output:

```
Good morning, Alice!
```

## Return Values

Use `return` to send a value back from a function:

```python
def add(a, b):
    return a + b

result = add(3, 5)
print(result)
```

Output:

```
8
```

_Note: If a function has no `return`, it returns `None`._

## Default Parameters

Give parameters default values:

```python
def greet(name, greeting="Hello"):
    print(greeting + ", " + name + "!")

greet("Alice")
greet("Bob", "Hi")
```

Output:

```
Hello, Alice!
Hi, Bob!
```

## Scope

Variables inside a function are local—they only exist inside that function:

```python
def calculate():
    x = 10
    return x * 2

result = calculate()
print(result)  # 20
print(x)       # Error! x doesn't exist here
```

## Functions Calling Functions

Functions can call other functions:

```python
def square(n):
    return n * n

def sum_of_squares(a, b):
    return square(a) + square(b)

print(sum_of_squares(3, 4))
```

Output:

```
25
```

## Documenting Functions

Use a docstring to describe what a function does:

```python
def calculate_area(width, height):
    """Calculate the area of a rectangle."""
    return width * height
```

## Practical Examples

### Processing a list

```python
def get_average(numbers):
    total = 0
    for num in numbers:
        total = total + num
    return total / len(numbers)

scores = [85, 90, 78, 92]
print(get_average(scores))
```

Output:

```
86.25
```

### Validating input

```python
def is_valid_age(age):
    if age < 0:
        return False
    if age > 120:
        return False
    return True

print(is_valid_age(25))   # True
print(is_valid_age(-5))   # False
```

### Formatting output

```python
def format_name(first, last):
    return last + ", " + first

print(format_name("Alice", "Smith"))
```

Output:

```
Smith, Alice
```

## Common Mistakes

**Forgetting to call the function**

```python
# Wrong - this just references the function
def greet():
    print("Hello!")

greet  # Nothing happens

# Right - use parentheses to call it
greet()
```

**Forgetting to return a value**

```python
# Wrong - returns None
def add(a, b):
    result = a + b

print(add(3, 5))  # None

# Right - return the result
def add(a, b):
    return a + b

print(add(3, 5))  # 8
```

**Printing instead of returning**

```python
# Wrong - can't use the result
def add(a, b):
    print(a + b)

result = add(3, 5)  # result is None

# Right - return so you can use it
def add(a, b):
    return a + b

result = add(3, 5)  # result is 8
```

**Wrong number of arguments**

```python
def greet(name, age):
    print(name + " is " + str(age))

# Wrong - missing argument
greet("Alice")  # Error!

# Right - provide both arguments
greet("Alice", 20)
```

**Indentation errors**

```python
# Wrong - code outside the function
def greet():
print("Hello!")

# Right - indent code inside the function
def greet():
    print("Hello!")
```


---

## Backlinks

The following sources link to this document:

- [Functions Guide](/resources/resources.index.llm.md)
- [Protocol Library](/unit-2/projects/01-internal-review/01-internal-review.ticket.llm.md)
- [Protocol Library](/unit-2/projects/01-internal-review/oracle-handbook.guide.llm.md)
- [Protocol Library](/unit-2/projects/02-archive-audit/tickets/signals.ticket.llm.md)
- [Protocol Library](/unit-2/projects/02-archive-audit/tickets/simulations.ticket.llm.md)
- [Protocol Library](/unit-2/projects/02-archive-audit/oracle-handbook.guide.llm.md)
- [Protocol Library](/unit-2/projects/02-archive-audit/tickets/nodes.ticket.llm.md)
- [Protocol Library](/unit-2/projects/03-architects-index/tickets/signals.ticket.llm.md)
- [Protocol Library](/unit-2/projects/03-architects-index/oracle-handbook.guide.llm.md)
- [Protocol Library](/unit-2/projects/03-architects-index/tickets/nodes.ticket.llm.md)
- [Protocol Library](/unit-2/projects/03-architects-index/tickets/simulations.ticket.llm.md)
- [Functions](/unit-2/projects/04-oracle/oracle-handbook.guide.llm.md)
