Hi folks,

Firstly **Spoilers Ahead**

This post contains solution code to part 2 of Reggie’s Linear Regression project so if you don’t want to see the solution please scroll no further!

After some head-scratching and trial-and-error, i finally managed to write some code which produced the correct answers for part 2 of Reggie Linear Regression project.

However, upon comparing my code to the solution code, there is one simple aspect that I don’t understand.

My code:

```
datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]
best_m = 0
best_b = 0
def try_slopes_and_intercepts(possible_ms, possible_bs):
smallest_error = float("inf")
for m in possible_ms:
for b in possible_bs:
if calculate_all_error(m, b, datapoints) < smallest_error:
best_m = m
best_b = b
smallest_error = calculate_all_error(m, b, datapoints)
print(best_m, best_b, smallest_error)
try_slopes_and_intercepts(possible_ms, possible_bs)
```

Solution code:

```
datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]
smallest_error = float("inf")
best_m = 0
best_b = 0
for m in possible_ms:
for b in possible_bs:
error = calculate_all_error(m, b, datapoints)
if error < smallest_error:
best_m = m
best_b = b
smallest_error = error
print(best_m, best_b, smallest_error)
```

Ok, I overcomplicated the problem by making a function, however, the thing bugging me is that I MUST define smallest_error as float(“inf”) INSIDE my function. Why?

For example, in the code below:

```
datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]
best_m = 0
best_b = 0
smallest_error = float("inf")
def try_slopes_and_intercepts(possible_ms, possible_bs):
for m in possible_ms:
for b in possible_bs:
if calculate_all_error(m, b, datapoints) < smallest_error:
best_m = m
best_b = b
smallest_error = calculate_all_error(m, b, datapoints)
print(best_m, best_b, smallest_error)
try_slopes_and_intercepts(possible_ms, possible_bs)
```

this results in

```
UnboundLocalError: local variable 'smallest_error' referenced before assignment
```

Why am i not able to define smallest_error before I define my function?