Loops


While Loops

A while loop is a block of code that will continue ‘looping’ (repeating) until its boolean condition becomes false.

Syntax

After the last statement in the repeat block completes, the computer will jump backwards to the test and start anew. If the test evaluates to True, the computer will move through the repeat block again. If the test evaluates to False, the computer will ‘exit’ the loop, skipping over the repeat block.

While Loop Checklist

  1. Boolean condition
    1. Located after ‘while’ and before ‘:’
    2. Can use any boolean operator (==, !=, >, <. >=. <=)
    3. Can also use a boolean variable (a_condition)
  2. Code inside the while block (repeat block) is useful
  3. A ‘counter’ variable or boolean expression that will eventually become False and exit the loop – this should be placed inside the body of the while loop.

Examples of Counters

Numerical counter:

Common ways to increment a numerical counter include:

The counter variable can also be incremented by numerical amounts other than 1.

Boolean expression:

Something is Wrong!

If your loop just won’t end, you probably have implemented an infinite loop. Make sure that your condition can eventually become false! Example:

This is incorrect because the counter ‘i’ is never changed and thus will never be >= 110. Therefore, the while loop will INFINITELY execute and the string “Done” will never print.

Now, the while loop will execute 110 times, printing “I love COMP110 each time. The string”Done" will be printed once i = 110.

Nested While Loops!

We can nest while loops, meaning we can place one while loop inside of another! Check out this example:

These nested loops build up the string ‘sound’. The inner loop starts over and runs through again each time we reenter the outer loop.

For-in Loops

for-in loops are similar to while loops, but instead of looping through a statement until a boolean condition changes, a for-in loop iterates over a collection of items.

The Syntax:

identifier is a variable name you choose for each item in the repeat block.

How Does this Work?

The assignment of the identifier to each item in the sequence is handled for you, and so is the progression from one item to the next. (Thank you, computers!)

The loop ends after the repeat block evaluates the last item.

for-in loops are great for when you want to process every item in a collection. Collections can include Lists, Dictionaries, Sets, and even Strings! Anything iterable can be processed by a for-in loop.

One advantage of for-in loops are since iteration is taken care of by the computer, we don’t have to worry about forgetting to increment/decrement our counter variable (goodbye infinite loops!).

Converting a While Loop

Any while loop can be turned into an equivalent for-in loop. Here’s an example of printing out elements of a List:

The output for both of these loops will be exactly the same: 1, 2, 3, 4, 5, 6. These two types of loops are completely interchangeable; however, the syntax of a for-in loop often proves to be preferable as you get more comfortable with the process.

Which Loop to Use?

Although for-in loops and while loops are interchangeable, there are some instances where you want to use one over the other.

While loops provide more control to the author because you must know how many times the loop should run – either by a specific numerical amount using a counter varible, or by telling the loop when to end based on a boolean condition.

for-in loops are fantastic for-in looping through an entire collection of data in a deceptively simple way.

Nested For Loops!

We can nest for-in loops, too!

The nested loops print out combinations of the two lists. The output of this will be ‘spooky skeletons, spooky shivers, scary skeletons, scary shivers’.

Range Objects in Loops

You can also loop through a defined range using Python’s range() function.

Check out this page for more information about this function!

While the syntax looks a bit different for using range within with loops and for-in loops, both can use the range() function in their implementation!

Both loops’ outputs are ‘0 1 2 3 4’. This is another way to control the amount of times a loop repeats!