Dark theme

Control flow


This practical we're going to use control flow statements to rework our code to remove all the repeats. While we do so, we'll also increase the number of agents we can locate, and sort out an issue with boundaries we skipped over last time.


First though, did you manage to get the most easterly point on the graph as a different colour? Here's one solution:

matplotlib.pyplot.ylim(0, 100)
matplotlib.pyplot.xlim(0, 100)
matplotlib.pyplot.scatter(agents[0][1],agents[0][0])
matplotlib.pyplot.scatter(agents[1][1],agents[1][0])
m = max(agents, key=operator.itemgetter(1))
matplotlib.pyplot.scatter(m[1],m[0], color='red')
matplotlib.pyplot.show()

It's not the most elegant solution, as it adds one point in twice, but it will do. As you'll see, we're going to increase the number of agents, and checking each of them to see if it is the maximum would be less efficient.


Right, let's start reducing our code. We're going to use for-loops to reduce the code size and make the number of agents more flexible. There's only so many times you can cut and paste code (how would we do it for a million agents??), and the more code you have, the more likely typos are, so reducing the code is generally good. It will also allow us to run each section of code as many times as we like.

Let's start by adding a variable after the imports, but before the rest of the code, which will control how many agents we have:

num_of_agents = 10

At the moment we have the following code at the top of our file (or similar):

agents.append([random.randint(0,100),random.randint(0,100)])

This creates one new set of coordinates. If, however, we put this into a for-loop, we can create as many agents as we like. Here's such a loop:

for i in range(num_of_agents):
    agents.append([random.randint(0,100),random.randint(0,100)])


That's created a list with num_of_agents agent coordinates. Note that we've had to indent the line that runs inside the for-loop; remember that you can indent one or more lines in Spyder by selecting them and pressing TAB (SHIFT + TAB dedents).

Now let's look at the next chunk of code.


  1. This page
  2. Looping agents II <-- next
  3. Looping movements
  4. Boundary effects
  5. Boundary solutions