I keep reading about endless loops, is that something you want or do you always have to control an endless loop situation?

I keep reading about endless loops, is that something you want or do you always have to control an endless loop situation?

Your operating system runs in an endless loop. :)

Truly endless loops are obviously bad news (i.e., shut off the computer and restart). However, most "endless loops" usually provide a way to break out. Here is a common and useful variety:

while True:
    name = raw_input("What is your name? ")
    if name == "King Arthur of Camelot":
       break

In this endless loop, the right response will get you over the bridge of death ... I mean, out of the loop.

This is called a "test-last" loop, because the test comes at the end of the loop. In many languages, it would be implemented as a "do ... until" type of construct. The point of test-lasting is to make sure that the body of the loop is executed at least once (i.e., the question gets asked at least once).

Others might implement the same code as

name = ""
while name != "King Arthur of Camelot":
    name = raw_input("What is your name? ")

but I like the first version.


Here's another example: a shell

dir = "C:"
while True:
   command = raw_input(dir + "> ")
   if command.startswith("dir"):
       list_dir(command[3:])  # this would be parsed differently in real life!
   elif command.startswith("cd"):
       dir = change_dir(command[2:])
   elif command == "exit":
       break
   else:
       print "command not found"

This shell format is the basis for text games, command-line interpreters, etc.

Jeff

I see, so using:

while True:
    pass

would be an endless loop, and you better give it a condition to break out of this loop. Something like:

while True:
    quit = raw_input("press q to quit ")
    if quit == 'q':
        break

Accidental endless loops are the once you have to watch out for. The 'while loop' is more prone to this either through faulty escape logic or accidental use of the control variable:

# accidental endless loop

# this is okay in Python
for k in range(10):
    k = 2
    print k
    
# but not in C ...
"""
// accidental endless loop in C

#include <stdio.h>

int main()
{
  int k;
  
  for(k = 0; k < 10; k++)
  {
    k = 2;
    printf("%d", k);        
  }    
    
  return 0;
}
"""

# the C 'for loop' behaves more like this
# now you have accidental endless loop
k = 0
while k < 10:
    k = 2
    print k

Even if you don't forget to put the counter into the 'while loop' you can still make an error ...

# now you have an accidental endless loop 
k = 0 
while k < 10:
    # the k counter
    k += 1 
    print k
    # more code here
    # now comes the mistake
    # k will never got to 10
    k = 2

Just to add to Vega's example, I try to make my while conditions be "region" conditions instead of "boundary" conditions. Consider the difference between the two following innocent-looking pieces of code:

def print3rds(n):  # Prints every third number from n up to 99

   while n != 99:
        print n,
        n += 3

vs.

def print3rds(n):

    while n <= 99:
       print n,
       n += 3

In the first code, the condition checks the "boundary" and quits if n hits the boundary. But of course, if print3rds(4) is called, n will *never* be equal to the boundary. Hence, an endless loop!

In the second code, the condition checks the "region" and quits if n exits the valid region. In general, this is a much safer way to write conditions.

Jeff

When you do GUI programming, you will find another endless loop usually called mainloop(). This is the loop that continuously scans for windows events like mouse clicks, mouse position, button clicks, key presses and so on.

The mainloop() is not truely endless, when you click on the little x on the upper right corner of the window frame it quits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.