Python Development Course
Chapter
>
Level
Learning Loops
For Loop Sequence
Objective
Collect grains and make your way out of the maze by writing no more than four (4) lines of code.
Youâve found yourself lost in the middle of a maze, use loops in order to collect the grains in the field and exit the maze.
As you can see from the map the maze is uneven so you canât just repeat a very specific line of code like in previous levels. For this you need to make full use of the for loops set variable.
for x in range(4): player.move_forward(x + 1) # +1 is added because x starts out as 0 we want to start at 1
The variable set as x checks how many cycles the for loops have gone through, you can set this variable to whatever name you want but by default we name it as x for ease of use. By adding the variable used in the for loop to the move_forward() function, this will allow you to move your character one more step each time the loop cycles.
For example, in the above code the range() is set to four 4, that means that by adding the variable to the move_forward() function the movement will increment an extra step each time the loop cycles, and would look like this in practice:
# This is the same output as the previous code shown move_forward(1) # First Loop move_forward(2) # Second Loop move_forward(3) # Third Loop move_forward(4) # Fourth Loop
Use the variable from the for loop inside the move_forward() code do increment your movement each loop and collect all the grains to complete the level. Remember, this must be done by writing no more than four (4) lines of code.