Reggies Linear Regression

Hello Everyone,
I was doing the Reggies linear regression challenge and couldn’t figure out the difference between

def calculate_all_error(m, b, datapoints): total_error = 0 for point in datapoints: point_error = calculate_error(m, b, point) total_error += point_error return total_error

and

def calculate_all_error(m,b,datapoints): error_total=0 for point in datapoints: point_error=calculate_error(m,b,point) print("point error",point_error) error_total+=point_error print(" error total",error_total) return error_total

When I print out every step, I can see that the loop works in the first code but not in the second one. If anyone would be able to explain the difference it would be much appreciated!

Can we have a link to the lesson?

https://www.codecademy.com/courses/learn-python-3/informationals/python3-reggies-linear-regression
that’s the link but it’s on jupyter notebook so you’d have to download the zip file.
I’ve just copied all previous code hopefully that helps.

def get_y(m, b, x): y = m*x + b return y get_y(1, 0, 7) == 7 get_y(5, 10, 3) == 25 def calculate_error(m, b, point): x_point, y_point = point y = m*x_point + b distance = abs(y - y_point) return distance #this is a line that looks like y = x, so (3, 3) should lie on it. thus, error should be 0: print(calculate_error(1, 0, (3, 3))) #the point (3, 4) should be 1 unit away from the line y = x: print(calculate_error(1, 0, (3, 4))) #the point (3, 3) should be 1 unit away from the line y = x - 1: print(calculate_error(1, -1, (3, 3))) #the point (3, 3) should be 5 units away from the line y = -x + 1: print(calculate_error(-1, 1, (3, 3))) datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)] def calculate_all_error(m, b, datapoints): total_error = 0 for point in datapoints: point_error = calculate_error(m, b, point) total_error += point_error return total_error

The return in the first one is outside the for-loop, so it happens after the loop finishes running.
The return in the second one is inside the for-loop, so it does one iteration of the loop (meaning the error for one point), and then does return total_error, which ends the function.

That is very helpful. I would assume the second return would return a value for every iteration but as far as I understand what you’re saying is when the loop hits the return function it does not loop through any more?

Yes. The loop (and the function) stops when it reaches return.