8 data = pd.read_csv(file_path)
9 return data
10
11def visualize_results(data):12 """
13 Visualize the analysis results
14 """
5 """
6 Load data from a CSV file
7 """
8 data = pd.read_csv(file_path) 9 return data
10
11def visualize_results(data):
1import matplotlib.pyplot as plt
2import pandas as pd
3
4def load_data(file_path): 5 """
6 Load data from a CSV file
7 """
20 model.fit(X_train, y_train)
21 return model
22
23def save_model(model, file_path):24 """
25 Save the trained model to a file
26 """
20 model.fit(X_train, y_train)
21 return model
22
23def save_model(model, file_path):24 """
25 Save the trained model to a file
26 """
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()