Teacher's Guide

Chapter 4 / Level 3: More complex looping

Teaching Objective:

  • Student understands how to integrate functions in loops
  • Reasons which method he would like to traverse the map be it for or while loop
  • Gains more experience writing loops and taking advantage of their practical application.

Guide

In order to complete the level, the student must use the for loop or while loop in order to traverse the field, water the crops and reach the exit.

to use the while loop the variable count is set to 0 and used to determine how many cycles the loop should run. The while loop uses count to test if it should perform the loop cycle or not. The tabbed code that follows is the code that should repeat for as long as the while condition returns true.

count = 0

while count < 4:
  player.turn_left()
  player.move_forward(2)
  player.water()
  player.turn_left()
  player.move_forward(5)
  player.turn_right()
  player.move_forward(2)
  player.water()
  player.turn_right()
  player.move_forward(5)
  count += 1

The variable count is increased by 1 in order to meet the condition for the loop to finalize.

The for loop allows you to repeat the same code a set number of times. The range() part of the loop code determines how many times the looping code is run, in the case of the following example it is four.

for x in range(4):
  player.turn_left()
  player.move_forward(2)
  player.water()
  player.turn_left()
  player.move_forward(5)
  player.turn_right()
  player.move_forward(2)
  player.water()
  player.turn_right()
  player.move_forward(5)

Remember you must tab the code that comes after the loop code in order for it to be part of the loop, otherwise the code won’t loop.

Loop your movements across the field, water the crops and reach the exit to complete the level.

Caution

The while loops can fall into what is called an infinite loop, this means the code is repeated forever causing your program to get stuck and crash. In order to prevent this from happening it’s always important to set up a cap or a stopping point. For the purpose of this exercise, we use the count variable to cap the number of cycles to prevent an infinite loop from happening.

Map overview and path

Map overview and path

Code Solution using for loop

import player

for x in range(4):
  player.turn_left()
  player.move_forward(2)
  player.water()
  player.turn_left()
  player.move_forward(5)
  player.turn_right()
  player.move_forward(2)
  player.water()
  player.turn_right()
  player.move_forward(5)

Code Solution using while loop

count = 0

while count < 4:
  player.turn_left()
  player.move_forward(2)
  player.water()
  player.turn_left()
  player.move_forward(5)
  player.turn_right()
  player.move_forward(2)
  player.water()
  player.turn_right()
  player.move_forward(5)
  count += 1
Chapter 4 / Level 3: More complex looping | Teacher's Guide