5. Iteration - Event Loop
5.1 While Loop
You may have noticed that many of the example programs have contained a line with:
1 | |
This is a loop. A loop will run whatever is inside it until it meets a false condition. while True: is the same as saying run forever and will run until you stop the Edison.
Let's look at the syntax (structure) of a while loop – lines 11 and 12:
1 2 3 4 5 6 7 8 9 10 11 12 | |
If this code gets loaded onto the Edison it will play a beep sound, and keep playing it.
- The code enters at
line 11and see that thewhileloop istrue - It will then run
line 12and play the beep - It will then come back up to
line 11and once again see that the loop istrue - It will then run
line 12and play the beep - etc...
Try it and see
Copy the code to EdPy and download it to your Edison. You will hear a droning sound instead of distinct beeps. Why?
We can also make the Edison continually drive:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
5.2 Python Syntax
Notice that the code underneath the event loop (while True:) is indented. This is how Python understands that the code below needs to be repeated. Indentation is used in Python to allow us to attach code to structures such as while loops.
Indentation can either be created using the tab key or spaces, so long as they are consistent.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
In the above example we could expect the Edison to move forward by 10cm and then go backwards 10cm. What actually happens is that the Edison will move forwards forever and never go backwards. Why?
Fix the indentation
Copy the above code into EdPy and fix it so that the Edison repeats cycles of move forward 10cm and goes backwards 10cm.
Of course, the event loop can be combined with what we've learnt previously (functions and variables):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
In the above example the Edison will beep and pause for a random number of seconds between one and three. You can see from above that functions are being called from within the while loop.