Module 5 - Looping Control Structures Header

Module 5 - Looping Control Structures

Introducing Loops

There are many times in your code where you will want your program to do the same thing many times, perhaps with a small difference each time.  For example, if you want Python to print out the numbers from 1 to 10, you could do the following:

print("1")
print("2")
print("3")
print("4")
print("5")
print("6")
print("7")
print("8")
print("9")
print("10")

That's not a lot of fun, and it's probably prone to errors, but it's not the end of the world.  But can you imagine doing that all the way to 1,000, or 1,000,000?  No thanks.

Loops give us a clever, more convenient way to do this:

// Set the value of x to 1
x = 1
// Start a loop with an expression that will eventually be false
while x < 11:
     // Print the value of x
     print(x)
     // Add 1 to the value of x
     x += 1

The code above will give you the same result as the first example.  However, by changing the number in the expression, we could make Python count as high as we wanted without additional code.  I think that's pretty magical… don't you?

Note: While we only want Python to count to 10, the expression for the while loop is: x < 11.  Can you think of why that might be?  Play around with different expressions and values, and see what happens!



While Loops

In Python, a while loop is a control flow statement that allows code to be executed repeatedly until a specific condition is met. The syntax for a while loop is as follows:

while expression:
     code block that gets executed repeatedly as long as the expression is true

The condition is a Boolean expression that is evaluated each time the loop executes. If the condition is True, the code block will be executed. If the condition is False, the loop will terminate.

The code block inside the while loop will be executed repeatedly until the condition becomes False. This means that the code block will be executed at least once, even if the condition is False on the first iteration.

Here is an example of a while loop:

counter = 0
while counter < 11:
     print(counter)
     counter += 1

In this example, the variable counter is initialized to 0. The while loop will continue to execute as long as counter is less than 10. On each iteration, the value of counter will be printed to the console and then incremented by 1. The loop will terminate when counter is no longer less than 11 (this means that the number 10 will be the last number printed).

Check out this flowchart that shows how the loop works:

I want to point out a few things about the code above:

  1. Notice that the while line ends in a colon.
  2. Notice that the code block that belongs to the while loop is all indented at the same level.

This is a pattern that you need to pay attention to, because this structure of a line with a colon and an indented block of code below it is very common in Python. Indents are very important and meaningful in Python, where in other languages they are often used just to make code more readable.  It takes a little bit of getting used to, but it's a very convenient way of managing code and structure within a Python program.

While loops are a powerful tool that can be used to perform a variety of tasks. Among many things, they can be used to:

  • Iterate over a list or string.
  • Calculate a factorial or Fibonacci sequence.
  • Play a game.
  • Solve a mathematical problem.


For Loops

A for loop is a powerful programming construct that allows us to repeat a block of code a specific number of times or iterate over a sequence of elements. It's a fundamental concept in programming, so let's get started!

The basic structure of a for loop in Python is as follows:

for item in sequence:
   # Code to be executed
   # for each item in the sequence

Here's a visual of the process:

Let's break it down step by step:

  • The for keyword: It indicates the start of the loop and is followed by a variable name that will be used to represent each item in the sequence. You can choose any valid variable name you like.
  • The item variable: It represents the current item being processed in each iteration of the loop. Think of it as a placeholder that takes on the value of each item in the sequence, one by one.
  • The in keyword: It is used to specify the sequence over which we want to iterate. A sequence can be a list, tuple, string, or any other iterable object.
  • The sequence: It is the collection of items that we want to iterate over. Each item in the sequence will be assigned to the item variable in turn.
  • The colon (:): It is used to indicate the start of the code block that will be executed for each item in the sequence.
  • The indented code block: It contains the instructions or operations that we want to perform for each item in the sequence. This code block is executed once for each item, and the item variable holds the current value.

Now, let's see some examples to solidify our understanding. Consider the following example that prints each element in a list (we will be getting to the details of lists in the next module or two):

fruits = ['apple', 'banana', 'orange', 'grape']

for fruit in fruits:
   print(fruit)


In this example, we have a list called fruits containing four elements. The for loop iterates over each element in the fruits list. In each iteration, the fruit variable takes on the value of the current element, and then it is printed using the print() function.

The output will be:

apple
banana
orange
grape


Another common use case is to iterate over a range of numbers. Let's print the numbers from 1 to 5 using a for loop:

for number in range(1, 6):
   print(number)


Here, we use the range() function, which generates a sequence of numbers from the starting value (1) to the ending value (6 - 1 = 5). The for loop iterates over this sequence, assigning each number to the number variable, which is then printed.

The output will be:

1
2
3
4
5


You can also combine for loops with conditional / branching statements to perform more complex operations. For example, let's print only the even numbers from 1 to 10:

for number in range(1, 11):
   if number % 2 == 0:
       print(number)


In this case, we use the modulo operator (%) to check if the current number is divisible by 2. If the remainder is 0, it means the number is even, so we print it.

The output will be:

2
4
6
8
10


Remember, the possibilities with for loops are vast, and they allow you to automate repetitive tasks and process data efficiently



Breaking out of a loop

In Python, you can also end a loop prematurely, or based on a condition other than the one that would normally cause the loop to end.

For example, look at the following code:

for intNumber in range(1,10):
print(intNumber)

This for loop will print the digits from 1 to 9 - The range() function creates a list of all whole numbers between the first number and the second number. That list always includes the first number, but not the second one, because Python sees the first number as part of the between group, but the second one as just outside that group.  So, range(1,10) results in a list containing 1,2,3,4,5,6,7,8,9.  If we want to include 10, then we'd need to write range(1,11).  It's a little odd, but once you get used to the idea it's not hard to remember.

So this loop produces the following output:

1
2
3
4
5
6
7
8
9

What if we want the counting to stop at 5, but for whatever reason we don't want to change the code for the loop?  Let's look at the following code:

for intNumber in range(1,10):
if intNumber == 6:
break
print(intNumber)

Now, each time the loop runs, the first thing it does is to check and see whether the value of intNumber is equal to 6.  If it is, then it executes the break command, which terminates the loop.  If there is code following the loop, then that code gets executed next.  So this loop starts out printing the numbers from 1 to 9, but as soon as it gets to 6, it quits printing (notice that this happens before it prints the number 6).

The break command is also useful inside a. while loop.  In fact, sometimes it's the only way out of a while loop.  In the following code, a while loop is started with the simple expression “True”.  

x = 1
while True:
if x > 10:
break
else:
print(x)
x += 1

Since “True” is always going to be true, the loop will just keep going until the computer dies, or unless we end the loop some other way. So inside this loop, we use an if statement to check the value of the variable x, and if x is greater than 10, we break out of the loop.  If x isn't greater than 10, we print the value of x and then add 1 to x before running the loop again.

In situations where there is a loop inside another loop, break will only end the loop that it is contained within.  For an example of this, check out the following code:

y = 1
x = 1
while True:
if x > 5:
break
else:
print("X is",x)
x += 1
while True:
if y > 5:
break
else:
print("Y is", y)
y += 1

The results for this code, when run, will be the following:

X is 1
Y is 1
Y is 2
Y is 3
Y is 4
Y is 5
X is 2
X is 3
X is 4
X is 5

Notice that it prints the first “X” line, then goes into the “Y” loop, printing the “Y” values until that loop breaks, then going back out into the “X” loop until that loop breaks.  You might be wondering why, after printing the “X is 2” line, it doesn't go back into the Y loop. It does, actually, but the value of Y is still 6 at that point, so it immediately breaks out of that loop each time.  If you want it to count through the Y values after each X, what do you think you would need to do?



The Continue Statement

In Python, the continue statement is used within loops (such as for loops and while loops) to alter the flow of the program by skipping the rest of the current iteration and moving on to the next iteration of the loop. When continue is encountered, the remaining code within the current iteration is bypassed, and the loop proceeds to the next iteration as if nothing happened. This can be useful for various purposes, such as skipping specific items or values in a loop or implementing conditional logic within a loop.

Here's the basic syntax of the continue statement:

for item in iterable:
# Some code here

if condition:
continue

# More code here

In this example, when the continue statement is encountered inside the loop and the specified condition is met, the code after continue is skipped, and the loop continues with the next item in the iterable.

Use Cases:

Skipping Specific Items

You can use continue to skip processing certain items in a loop based on some condition. For example, in a loop that iterates through a list of numbers, you can skip processing even numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
continue
print(num)

In this case, continue is used to skip even numbers, so only odd numbers are printed.

Error Handling and Validation

In situations where you want to skip iterations that would result in errors, you can use continue to handle validation or error-checking within a loop. For instance, if you're processing data and want to skip invalid or incomplete records, you can use continue to move to the next record without processing the current one.

data = [valid_data_1, invalid_data, valid_data_2, invalid_data, valid_data_3]
for record in data:
if not is_valid(record):
continue
process(record)

Optimizing Loops

In some cases, you may want to optimize loops by skipping unnecessary iterations. For instance, if you're searching for a specific value in a list and want to stop the search as soon as you find it, you can use continue to skip the remaining iterations:

target_value = 42
numbers = [1, 5, 8, 12, 42, 67, 89, 102]
for num in numbers:
if num == target_value:
print(f"Found {target_value}!")
break # Exit the loop early
else:
continue

Limitations:

  • Nested Loops: When using continue in nested loops (loops within loops), it can sometimes be challenging to control the flow as it only affects the innermost loop. Careful consideration is needed to ensure the desired behavior is achieved.
  • Infinite Loops: Misuse of continue can potentially lead to infinite loops if not used with proper termination conditions. Make sure your loop has an exit condition to prevent infinite looping.
  • Readability: Overuse of continue statements can make code less readable and harder to maintain. It's essential to strike a balance between using continue for control flow and keeping code clean.

In summary, the continue statement in Python is a useful control flow tool that allows you to skip the current iteration of a loop and move on to the next one. It can be handy for skipping specific items, handling errors, and optimizing loops, but it should be used judiciously to maintain code clarity.



Try it: Loops

Enter the following lines of code in the block below, and press ENTER after each one (and SHIFT-ENTER after the last line):


lisFruit = ("apple", “orange”, “banana”)
for strFruit in lisFruit:
     print(strFruit)

Now, try some of the following things:

  1. Can you add another fruit to the list?
  2. Can you figure out how to only print the fruit if it is an orange or banana?
  3. Can you print the fruit as a numbered list, starting at 1 and increasing with each fruit?

Videos for Module 5 - Looping Control Structures

Key Terms for Module 5 - Looping Control Structures

No terms have been published for this module.

Quiz Yourself - Module 5 - Looping Control Structures

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question