Python Development Course
Chapter
>
Level
Conditions
Break and Continue Statements
Objective
Clean out some weeds in the passage between buildings using loop conditions.
The passage between buildings has weeds growing, gather all the weeds and dump them by using loops. There are ways you can automate this process by using loop conditions.
Create a variable named bag and use it to store the weeds as you pick them up. Use a while loop with conditions to automate the process, there are ten (10) weeds in total.
while True: player.move_forward() bag += 1 if bag == 10: break
By setting the while loop to True the while loop will not end unless the operator break is used to close out the loop. Each loop cycle adds a weed to the bag and checks how many weeds have been picked up to break the loop. The if statement is used to check if the loop should break or not, it checks how many weeds are in the bag and breaks if the amount is met.
After navigating the passage, use a for loop to dump the weeds into containers by using the place() function at the X marks. The amount of steps between each container is uneven though as there is a gap in between. By using the operator continue , you skip a loop cycle by testing a condition via if statement.
for x in range(3): player.move_forward() if x == 1: continue player.turn_right() player.place(bag/2) player.turn_left()
In the code above, the if statement checks if x, that is the number of loop cycles, is at 1. This for loop runs three (3) times as defined by range() , since x starts at 0, it runs 0,1,2 before completing the loop. Since you check if the loop cycle is at 1 , the code under continue will not run and instead be skipped if that condition is met. With this we can avoid the gap between the two containers, by skipping the middle cycle.
Since there are two (2) crates, use the place() function to dump the weeds stored in the bag variable by dividing the total placed, like this: player.place(bag/2) .
Once you’ve collected and placed the weeds in the proper location, reach the exit marked by a star to complete the level.