Both programs 4 and 5 made a circle move back and forth on the stage, forever. In program 5, we check after every move of the circle whether the edge of the stage has been reached and the direction needs to be changed. Why not let the circle move from one end of the stage and change direction when the circle has reached the edge of the stage? This can be done by using a repeat loop inside the forever loop as shown in program 6.
- Scratch link: http://scratch.mit.edu/projects/17394175/
- Program file: P6_nested_loop.sb2
Having a repeat loop inside a forever loop creates a nested loop situation. Note that in program 6 we need to add the “if on edge, bounce” statement to make the circle move away from the edge before it starts the next repeat loop.
|Program 5||Program 6|
We consider both program 5 and 6 to be good implementations of the moving circle problem. Which version one prefers is almost a matter of taste. However, many problems needing nested loops cannot be implemented efficiently without them. We refer to the Nested Loop document for more examples on nested loops in Python. Video Length: 2:40