May-26-2020, 03:11 AM
(This post was last modified: May-26-2020, 03:11 AM by deanhystad.)
This is an odd case. You have a global "node_list", and if you left out the assignment at the end of animate_nodes, Python would use the global "node_list" and the code would run (well, eventually). The assignment changes things. The assignment creates a local variable named "node_list".
def animate_nodes(): for current_node in node_list: # node_list is a local variable. x = current_node[0] + current_node[2] y = current_node[1] + current_node[3] if current_node[2] > 0 and current_node[2] < 10: vx = current_node[2] + random.randrange(-1, 1) if current_node[3] > 0 and current_node[3] < 10: vx = current_node[3] + random.randrange(-1, 1) new_node_list.append = [x, y, vx, vy] node_list = new_node_list.copy() # Assignment makes a local node_listUse "global" to inform python you want to use the global variable
def animate_nodes(): global node_list for current_node in node_list: # node_list is a local variable. x = current_node[0] + current_node[2] y = current_node[1] + current_node[3] if current_node[2] > 0 and current_node[2] < 10: vx = current_node[2] + random.randrange(-1, 1) if current_node[3] > 0 and current_node[3] < 10: vx = current_node[3] + random.randrange(-1, 1) new_node_list.append = [x, y, vx, vy] # This is the next bug node_list = new_node_list.copy() # Assignment makes a local node_listBetter yet, avoid using the global variable. Pass the variable as an argument and return the modified variable. This exposes the purpose of the function instead of hiding it as a side effect.
def animate_nodes(node_list): """Where is my docstring?""" new_list=[] for current_node in node_list: x = current_node[0] + current_node[2] y = current_node[1] + current_node[3] vx = 0 # Default values? vy = 0 # Used but never assigned if current_node[2] > 0 and current_node[2] < 10: vx = current_node[2] + random.randrange(-1, 1) if current_node[3] > 0 and current_node[3] < 10: vx = current_node[3] + random.randrange(-1, 1) new_list.append = [x, y, vx, vy] return new_list