Python Tutorial Part 8 | Conditional Flow: While Loops

We’ll start exploring loops with the ‘while’ loop in this tutorial. Loops are critical in all programming languages, especially in the control world, where loops form the basis of PLC functionality.

In this Python tutorial series, we have begun to explore flow control, beginning with the previous topic of ‘if’ statements. The next basic form of flow control is the ‘loop’ structure.

What is a Loop?

In my humble opinion, a good way to understand the broader concept of loops extending beyond Python programming is a roundabout. You may perceive this as a strange analogy. However, the simple roundabout is something many of you have first-hand experience with.
Upon entering a roundabout, you are free to drive around in an endless circle, constantly reading road signs for directions. You may choose to pass intersections or exit the loop at an intersection of your choice based on the destination you have in mind. If none of the choices are appropriate, you can keep circling until the conditions change and a decision is reached. Loops in programming, while perhaps not a perfect one-to-one comparison, are similar.
Roundabout analogy of a While loop

Figure 1. Think of loops like driving around a roundabout. 

While Loops

The while loop is the simplest version of a loop in the Python language. This loop will perform a task or execute code until a given conditional expression is False. While loops are used most often when the conditional expression is tied to a sensor value, such as the duration of a button press or while an analog value lies under a certain threshold.
To better explain, let’s take a look at a simple loop construct for a pseudo-PLC in Python:
To start, time and random modules will help simulate time delay and real-time analog values from a simulated PLC tag assigned to a variable called tag_A. Next, we hard code the PLC mode variable to run.
The while loop begins with the ‘while’ keyword in red. To the right of the keyword is the condition to evaluate. In this case, we are asking the while loop to determine whether or not the PLC is in run mode. If the PLC is in run mode, the while loop begins, and the indented code block below the while keyword is executed.
Once the loop reaches the end of the indented code block, it again evaluates the test expression. If the expression is still True, the indented code block is executed once again top to bottom. Thus, if the PLC stays in run mode indefinitely, the loop will continue indefinitely. In this first example, there is no escape condition or logic that could change the mode of the PLC. Running the above code will demonstrate a loop that runs forever with random tag_A integer readings.
13 8 9 8 20
To terminate an infinite loop, such as this example, hit either the ctrl+c or cmd+c keys to force the interruption of the loop.

Break, Continue, Pass, and Loop Else

While the infinite PLC scan above may prove useful (no downtime), it may be problematic if maintenance or testing needs to be performed on the system. Similar to the roundabout, driving around in a circle endlessly may not apply to the various real-world factors that must be considered for properly designing a loop. That’s where the break, continue, pass, and else commands come into play. They are generally nested inside of the loop with a conditional if statement.

Break

The break command immediately stops the execution of the loop. It is similar to a car braking test, in that immediate termination is required.
Braking analogy for a break instruction

Figure 2. Immediate stopping of a loop can be thought of as a car pouring all resources into terminating motion. 

Modifying the PLC example earlier, once the tag_A value exceeds 20 the loop should be terminated for system stability:
The output will resemble something like the example below:
1 35 Warning: tag_A value of 35 exceeds 20 – Exiting loop Exited loop Process finished with exit code 0

Continue

The continue statement causes a jump back to the top of the indented code within the loop, and resembles a “go-to” statement in other languages. Similar to a U-turn in the indented code back to the starting point.
U-turn analogy for a continue instruction

Figure 3. U-turn analogy. 

It can be an alternative to conditional statements, but in practice, I find that conditional statements are much easier to read. Generally, I would recommend against using the continue statement, but would like to inform you of the general structure nonetheless.
Let’s say you wish to stop a machine after every 10th cycle for maintenance. As long as the counter is not a perfect multiple of 10, the ‘continue’ command will redirect the code back to the beginning of the indented section, just below the ‘while’ True: line. Using the continue keyword, it would look something like this:
Note the print statement and input function do not get executed until every 10th sequence. The output appears below:
machine cycle: 1 machine cycle: 2 machine cycle: 3 machine cycle: 4 machine cycle: 5 machine cycle: 6 machine cycle: 7 machine cycle: 8 machine cycle: 9 machine cycle: 10 Maintenance cycle needed on cycle: 10 Press any key to continue machine cycle: 11 machine cycle: 12 machine cycle: 13 machine cycle: 14 machine cycle: 15 machine cycle: 16 machine cycle: 17 machine cycle: 18 machine cycle: 19 machine cycle: 20 Maintenance cycle needed on cycle: 20 Press any key to continue

Pass

The pass statement is nothing but a placeholder for when code is being developed; it performs no operation. For example, in brainstorming controls engineering examples of while loop examples for this tutorial I started the code with the following:
This does create an infinite loop that does nothing, but it avoids the alternative of a syntax error with an empty indented body preceding the while loop. Below, we can see the output if the ‘while True:’ line had been followed by simply an empty line.
File “/Users/mlevanduski/PycharmProjects/pythonSeries/whileLoops.py”, line 36 ^ IndentationError: expected an indented block Process finished with exit code 1

Loop Else

The else clause can also be paired with while loops and not just conditional if statements. The else clause is triggered once the test condition of the while loop becomes false. For example, once the counter of PLC scans exceeds 10 the test condition becomes false and triggers the else clause below:
The output appears below:
plc_scan: 0, tag_A: 29 plc_scan: 1, tag_A: 24 plc_scan: 2, tag_A: 1 plc_scan: 3, tag_A: 17 plc_scan: 4, tag_A: 19 plc_scan: 5, tag_A: 9 plc_scan: 6, tag_A: 21 plc_scan: 7, tag_A: 29 plc_scan: 8, tag_A: 31 plc_scan: 9, tag_A: 19 plc_scan: 10, tag_A: 18 plc_scan exceeds 10 scans Process finished with exit code 0

Wrapping Up

While loops are a good introduction to looping concepts in Python, and are especially useful for random time or conditional durations, like sensor values. However, for loops, which we will learn about in the next section, are more common in practice for predictable numeric counts and sequences.


Copyright Statement: The content of this website is intended for personal learning purposes only. If it infringes upon your copyright, please contact us for removal. Email: admin@eleok.com

Leave a Comment