Dungeon Coder

 

Until the End of Time

Loops and Control Flow

Sometimes, there are sections of code we wish to be executed over and over until certain conditions are met (remember conditional branching). Simple if statements don't allow us to repeat specific lines of code. Instead, we need to use some sort of looping mechanism.

Two of the most common forms of loops in python are "for loops" and "while loops". Let's take a look at a couple such loops in action before explaining any further:

The first loop you see is a for loop. Specifically, this for loop consists of an "iterator" which is i. That iterator (which basically means looper) loops through the iterable (which means loopable) which is range(6). This range(6) magically creates a list of the numbers 0 through 5. So, the first time through the loop, i is given the value 0. The second time through, i is given the value 1. This continues up through i being set to 5. Along with placing values in i, the loop also executes the body inside the loop with each iteration (each loop through). What's the body? That's that print() line you see inside the for loop.

The second loop you see is a while loop. Before the while loop is run (another word for executed), I had to create a variable that will act as a sentinal variable. Sentinal variables, much like their medieval human counterparts, keep watch for certain conditions or events. In this case, our sentinal variable is countDown, which is initially set to 10. In the python while loop, you must first specify the condition under which the loop will continue to execute. In our case, the loop will repeat as long as countDown is greater than 0. Like the for loop, a while loop executes its body each time through the loop. The body here consists of printing a message and decrementing (decreasing) that value stored in countDown.

Assignment:

  1. Change the while loop so that it decrements countDown by 2 each time through the loop.
  2. How does the output change now that you've made the changes specified in step 1?
  3. Change the for loop so that it prints "You shall not pass!" 10 times.
  4. Change the while loop so that it counts down by 1 from 100 to 0.
  5. What happens if you get rid of the countDown -= 1 line from the while loop?

Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.

If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!

Become a Patron!

Glossary

Contact: dungeon_master@dungeoncoder.com