I am creating a program to calculate b1 for a linear regression program in Python.
When trying to assign a value to my b1 global variable, my IDE doesn't find it. You can find the variable assignment at the last line of my function.
x_data = [4, 8, 6, 3, 4, 6, 2, 1, 3]
y_data = [2, 4, 7, 3, 4, 8, 3, 2, 5]
b1 = 0
def b0_b1_calc():
x_sum = 0
y_sum = 0
for i in x_data:
x_sum += x_data[i]
y_sum += y_data[i]
x_mean = round(1, x_sum / len(x_data))
y_mean = round(1, y_sum / len(y_data))
x_list = []
y_list = []
for i in x_data:
x_list.append(i - x_mean)
y_list.append(i - y_mean)
x_minus_x_squared = []
for i in x_list:
x_minus_x_squared.append((x_list[i] - x_mean) ** 2)
x_sum = sum(x_minus_x_squared)
x_y = []
for i in x_data:
x_y.append(y_list * x_list)
x_y = sum(x_y)
b1 = x_y / x_sum
print(str(b1))
b1which is only available inside the function. If you want to access that value later, you have to: 1) call your function, 2) either print the result inside the function or return the result. I would advise you against global variables here, simply change your last line in the function toreturn return x_y / x_sum, and secondly replace your statementprint(str(b1))withprint(b0_b1_calc()))return. Why don't you do that?