A lot of times, we don’t want code to execute just once if a condition is true. Instead, we want it to execute ‘while’ the condition is true, until the condition becomes false. This is where while loops come in handy. They basically run the code inside them until the condition is false. Here is the syntax for a while loop…
while condition: #code to run while condition is true
Here’s an example…
i = 0 while i < 6: print(“I am happy!") i = i+1
In this example, the code will print “I am happy!" 6 times. The true purpose of while loops can’t be seen here. But here’s a good example of where it’s used:
In robotics, for FTC, we use while loops for each phase of the match. ‘While’ in the Autonomous phase, we have the robot do certain tasks on its own. Then, ‘while’ in the TeleOp phase, we have the robot move based on driver input from the controller. To see this in action, feel free to look into the FTC Documentation.
For loops are used for analyzing each part of a sequence of data (lists, sets, dictionaries, etc). For now, just know that it is also a type of loop used for controlling program flow. We will go over it in detail in a later section.