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

5-1: Introducing While Loops (3:37)

5-2: Ending a While Loop (4:35)

5-3: Using Break to End a Loop (4:33)

5-4: Using Continue to Skip Part of a Loop (7:13)

5-5: Guessing Game with Loops (15:17)

5-6: S5 Explanation (5:21)

5-7: Introducing For Loops (11:47)

5-8: Guessing Game with For Loop (5:40)

A5 Explanation (13:32)

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 

Activities for this Module

S5 - Flower Maker

Note: Sandbox assignments are designed to be formative activities that are somewhat open-ended. To get the most value, spend some time playing around as you code.

One of the best things about turtle graphics is that it makes it possible to see something in a visual way that has previously been difficult to see or understand.  In this module, we are learning about looping control structures, or “loops” for short.

If you look at a picture of a flower, they often have a repeating pattern where there are a number of flower petals. In many cases the petals of a flower are very similar, and are also arranged in a sort of circular or sunburst pattern.  This repetitive pattern, which is often found in nature, is a good way for us to think about and study loops in our code.

For this Sandbox Challenge, we are going to be using the Turtle module and loops together to draw flower-like designs. I’ll start out by giving you some code.  Then we’ll change the code a little at a time to see what happens.  Finally, I’ll challenge you to modify the code to make your own flower design.

Let’s start with something very simple.  You can copy and paste this code directly into Pycharm, and it should run:

import turtle

myturtle = turtle.Turtle()
myturtle.speed(9)
intPetalsTotal = 6
intAngle = 360 // intPetalsTotal
intPetalsDrawn = 0

while (intPetalsDrawn < intPetalsTotal):
    myturtle.circle(150)
    myturtle.right(intAngle)
    intPetalsDrawn += 1

screen = turtle.Screen()
screen.exitonclick()

Go ahead and run the code, so you can see what it does.  Here is the same code, but with explanations in the form of comments, so you can learn a little more about what each line does:

import turtle

# ##### Setup Section #######
myturtle = turtle.Turtle()

# Turtle speed should be between 1-9
myturtle.speed(9)
# How many petals do we want?
intPetalsTotal = 4
# Variable to make sure the petals are spaced evenly
intAngle = 360 // intPetalsTotal
# Variable to keep track of the number of petals drawn in the loop.
intPetalsDrawn = 0
# ##### END Setup Section #######

# ##### START Loop to Draw Petals #######
# ##### Each time through the loop draws one petal #######
# ##### The loop continues as long as the number of petals
# ##### drawn is less than the total number of petals.
while (intPetalsDrawn < intPetalsTotal):
    ## Draw a circle with a radius of 150
    myturtle.circle(150)
    ## Turn to the right so next circle will be drawn next to this one.
    myturtle.right(intAngle)
    ## Add one to the number of petals drawn
    intPetalsDrawn += 1
# ##### END Loop to Draw Petals #######

# The turtle.done() line makes sure the window stays open 
# after the turtle stops drawing.
screen = turtle.Screen()
screen.exitonclick()

The code above is very similar, to the first section of code, but with one change?  Can you see it? If not, go ahead and copy/paste, then run the code and see what happens. After seeing the change in the effect of the code, perhaps you can spot the difference more easily.

The change in the value of intPetalsTotal from 6 to 4 in the new code changed the number of times the code block in the loop was run, reducing the number of petals in the flower to just 4.

In a while loop, the code block (the indented part of the loop) will be run as long as the expression in the parenthesis next to “while” evaluates to “True”.  So…

  1. The first time the loop is run, intPetalsDrawn equals 0, which is less than intPetalsTotal (4 in this code). The last line of the while loop code block adds 1 to intPetalsDrawn, making it equal to 1.
  2. Then, the “while” expression is evaluated with the current values of intPetalsDrawn and intPetalsTotal (1 and 4).  Since 1 is less than 4, the code block is executed again, drawing another circle, changing the angle, and adding 1 to intPetalsDrawn.
  3. Next, the “while” loop is executed again since intPetalsDrawn (2) is still less than intPetalsTotal (4). intPetalsDrawn is incremented to 3.
  4. This same thing happens again, drawing the fourth petal, and incrementing the intPetalsDrawn to 4.
  5. This time, intPetalsDrawn (4) is NOT less than intPetalsTotal (4) because they are EQUAL. Since the “while” expression is now False, the loop is not run again, and the program skips to the next line below the indented “while” block of code.

    Now that you know how it works, let’s try making a flower with 10 petals.

    How about changing the size of the petals to 100? (HINT: It’s the number in the circle( ) method)
    Let’s make the flower a little better looking - first, change the while loop block to the following (keeping the rest of the code as-is):

while (intPetalsDrawn < intPetalsTotal):
    myturtle.fillcolor("#EEEE77")
    myturtle.begin_fill()
    myturtle.circle(100)
    myturtle.end_fill()
    myturtle.right(intAngle)
    intPetalsDrawn += 1

Run the code and see what it does. Quick note: If you want a different color, you can find the code for the color you want by looking up what are called “Hex color codes” — I’ll trust your Google skills to figure that one out. If you don’t like searching, then the W3Schools HTML Color Picker (https://www.w3schools.com/colors/colors_picker.asp) is also very helpful.

Try changing the line that says this:

myturtle.circle(100)

to this:

myturtle.circle(100, steps=5)

(Make sure everything inside the loop stays indented)
Now run your code, and see what happens.

What other things can you think of to try?
I find that it’s a good idea to change one thing at a time, so I can really start to see an understand what all the pieces of code do.

I have one more thing to recommend trying out — What if we want more complex petals? I like daisies, so I was thinking it would be fun to make something that looked a little more like a daisy, with long, skinny petals, and a dark round center.  Try the code below, and see if you can figure out what’s going on (this time, you can copy and paste the whole block of code). It’s not commented, except for a few lines. I’m confident that you can figure out the rest.

import turtle
myturtle = turtle.Turtle()
# ##### Setup Section #######

myturtle.speed(9)
intPetalsTotal = 2
intAngle = 360 // intPetalsTotal
intPetalsDrawn = 0
intDotSize = 25
# ##### END Setup Section #######

# ##### START Loop to Draw Petals #######
while (intPetalsDrawn < intPetalsTotal):
myturtle.fillcolor("#EEEE77")
myturtle.begin_fill()
# Draw a circle segment with a 200 radius, but only for 40 degrees
myturtle.circle(200, 40)
# Draw a circle segment with a radius of 10, for 140 degrees
myturtle.circle(10, 140)
# Repeat the two lines above, to complete
# 360 degrees and end up back at the start.
myturtle.circle(200, 40)
myturtle.circle(10, 140)
myturtle.end_fill()
myturtle.right(intAngle)
intPetalsDrawn += 1
# ##### END Loop to Draw Petals #######

##### START Drawing the center of the flower #######
myturtle.forward(intDotSize)
myturtle.left(90)
myturtle.fillcolor("#000000")
myturtle.begin_fill()
myturtle.circle(intDotSize)
myturtle.end_fill()
##### END Drawing the center of the flower #######

# Finish up
screen = turtle.Screen()
screen.exitonclick()

Now that you can make all kinds of interesting things happen with the turtle and loops, it’s your turn to get creative.  Use this code as a starting place, and make a flower with petals and colors that you decide. 

A5 - Python ATM Machine

The Challenge

You will need to create an ATM machine, where the user can check the balance of their savings and their checking account, or make a deposit or withdrawal from either.

Constraints:

  • The balance cannot go below zero, so make sure you prevent that.
  • use string.rjust() as needed to make sure numbers line up properly.
  • Make the UI look good.
  • After each transaction, ask the user if they want to make another transaction.
  • Make sure you keep track of the amount in each account while the program runs.
  • Start each account with some $$.

Resources

Here is some sample code to get you started:

# start with some $$
flSavBal = 500.99
flChkBal = 100.31

# Welcome UI Message
print("#"*80)
print("Welcome to the ATM")
print("#"*80)

# create a loop for the program
while (True):

#Show the menu options
print("Choose an option: 1 - Deposit, 2 - With")
# Ask the user for their choice
strMenu = input("what do you want to do?")

if (strMenu == "1"):
print("You want to make a deposit.")
# ask for account

# ask for amount

elif (strMenu == "2"):
print("You want to make a withdrawal.")

elif (strMenu == "3"):
print("You want to check a balance.")

else:
print ("Sorry - that's not a valid choice")

print("")
strMore = input("Would you like another transaction?")

if (strMore != "y"):
break