# What is UnboundLocalError in Python?

This error occurs when you try to use a local variable in a function **before assigning a value** to it.

### ⚠️ Error Example:

```plaintext
pythonCopy codex = 5

def my_func():
    print(x)  # Trying to access x
    x = 10    # Local assignment

my_func()
```

Output:

```plaintext
UnboundLocalError: local variable 'x' referenced before assignment
```

## Why Does This Error Happen?

In Python, if you assign a value to a variable **anywhere in a function**, Python treats it as a **local variable** throughout the function.

So in the example above, Python thinks `x` is a local variable, but we’re trying to print it **before** assigning a value.

---

## ✅ How to Fix It

### ✅ Solution 1: Use `global` keyword

If you want to access and modify a global variable, declare it with `global`:

```plaintext
pythonCopy codex = 5

def my_func():
    global x
    print(x)
    x = 10

my_func()
print("After:", x)
```

### ✅ Solution 2: Pass the variable as an argument

This is safer and more Pythonic than using `global`.

```plaintext
pythonCopy codex = 5

def my_func(x):
    print(x)
    x = 10
    return x

x = my_func(x)
print("After:", x)
```

---

## ✅ Best Practice

Try to avoid using global variables unless necessary. It’s cleaner and safer to **pass variables into functions**.

---

## 💡 Bonus Tip: Local vs Global Variable Rules

| Variable Scope | Defined Outside Function | Assigned Inside Function |
| --- | --- | --- |
| Global | ✅ Accessible | ❌ `UnboundLocalError` unless declared `global` |
| Local | ❌ Not accessible | ✅ Assigned normally |

---

## 🧪 Test Your Understanding

What will the following code print?

```plaintext
pythonCopy codecount = 0

def increment():
    count += 1
    print(count)

increment()
```

**Hint**: You’ll get the same `UnboundLocalError`.

✅ Try fixing it using either `global count` or passing `count` as an argument.

---

## 🚀 Conclusion

`UnboundLocalError` is one of those errors that seems confusing at first, but once you understand Python’s scoping rules, it becomes easy to fix.

The golden rule: **If you assign a variable inside a function, Python assumes it’s local.**
