While Loops

command = input("Type EXIT to stop.")
while command != "EXIT":
    command = input("Type EXIT to stop.")
print("You typed EXIT")

We previously learned how for loops can iterate through a list of elements, a string, or a file. Since we always know how long those values are, we can iterate safely in these forms of finite iteration. But what about times when we have to loop an arbitrary number of times? For example, if we need to repeatedly ask the user to enter input, until the user successfully enters a number and not something invalid. For this, programmers have the while loop, which is a more powerful and therefore more dangerous form of iteration. It’s sort of like an if statement, except instead of continuing on to the rest of the program, while the condition is True the body will keep repeatedly executing. Anything that a for loop can do, a while loop can do too. However, a while loop can do some things that a for loop cannot easily do. Be careful, though, the programmer must be very careful to avoid causing an infinite loop and letting the program run forever!

While Loop Patterns

Like for loops, we introduce some patterns for while loops that can help guide your coding. However, these patterns are much looser than the patterns we cover with for loops, and are less generalizable. You can think of them as more like examples, or loose guidelines at best. In general, you should try to first think if a given problem can be solved with a for loop before you try to jump to a while loop. You would not immediately leap to a chainsaw when a pair of scissors would do. But of course, sometimes you need a bit of extra chopping power and a chainsaw becomes needed. In the same way, when you need a while loop, nothing else will suffice. These patterns can help you see opportunities for using this interesting control structure.

Plotting

You’ll make graphs! Histograms, line plots, and scatter plots.