176 def main():
177 # observations / data
178 x = np.array(data_point_list_x)
179 y = np.array(data_point_list_y)180
181 # estimating coefficients
182 b = estimate_coef(x, y)
175
176 def main():
177 # observations / data
178 x = np.array(data_point_list_x)179 y = np.array(data_point_list_y)
180
181 # estimating coefficients
154 return (b_0, b_1)
155
156
157 def plot_regression_line(x, y, b):158 # plotting the actual points as scatter plot
159 plt.scatter(x, y, color="m",
160 marker="o", s=30)
135
136 operatorReaction(x)
137 operatorReaction2(x)
138 def estimate_coef(x, y):139 # number of observations/points
140 n = np.size(x)
141
135
136 operatorReaction(x)
137 operatorReaction2(x)
138 def estimate_coef(x, y):139 # number of observations/points
140 n = np.size(x)
141
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()