| | |
Endless Loops
Thread Solved |
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
•
•
•
•
I keep reading about endless loops, is that something you want or do you always have to control an endless loop situation?

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:
[php]
while True:
name = raw_input("What is your name? ")
if name == "King Arthur of Camelot":
break
[/php]
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
[php]
name = ""
while name != "King Arthur of Camelot":
name = raw_input("What is your name? ")
[/php]
but I like the first version.
Here's another example: a shell
[php]
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"
[/php]
This shell format is the basis for text games, command-line interpreters, etc.
Jeff
I see, so using:
would be an endless loop, and you better give it a condition to break out of this loop. Something like:
Python Syntax (Toggle Plain Text)
while True: pass
Python Syntax (Toggle Plain Text)
while True: quit = raw_input("press q to quit ") if quit == 'q': break
No one died when Clinton lied.
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:
[php]# 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
[/php]
[php]# 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
[/php]
Even if you don't forget to put the counter into the 'while loop' you can still make an error ...
[php]# 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
[/php]
[php]# 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
[/php]
Last edited by vegaseat; Nov 12th, 2006 at 3:56 pm.
May 'the Google' be with you!
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
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:
[php]
def print3rds(n): # Prints every third number from n up to 99
while n != 99:
print n,
n += 3
[/php]
vs.
[php]
def print3rds(n):
while n <= 99:
print n,
n += 3
[/php]
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
[php]
def print3rds(n): # Prints every third number from n up to 99
while n != 99:
print n,
n += 3
[/php]
vs.
[php]
def print3rds(n):
while n <= 99:
print n,
n += 3
[/php]
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.
The mainloop() is not truely endless, when you click on the little x on the upper right corner of the window frame it quits.
Last edited by bumsfeld; Nov 14th, 2006 at 1:01 pm.
![]() |
Similar Threads
- Loops in Python (Python)
- Maximum execution time exceeded. (PHP)
- sorting parallel arrays (C)
Other Threads in the Python Forum
- Previous Thread: Qestion on Encoding and Decoding.
- Next Thread: Python Byte Code
| Thread Tools | Search this Thread |
accessdenied apache application approximation argv array beginner book builtin calculator change converter countpasswordentry curved dan08 dictionary dynamic edit enter examples file float format function gui homework import inches input java keyboard lapse launcher library line lines linux list lists loop microphone mouse movingimageswithpygame mysql mysqlquery newb number numbers numeric output parameters parsing path phonebook plugin port prime programming projects py2exe pygame pyopengl pysimplewizard python random recursion redirect remote reverse scrolledtext session simple smtp software sprite statictext string strings syntax table tennis terminal text textarea thread threading time tlapse trick tuple tutorial twoup ubuntu unicode unit urllib urllib2 variable wordgame wxpython






