Possibly better loop construct, also labels+goto important and on the fly compiler idea.
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Oct 29 10:08:16 EDT 2013
On Tue, 29 Oct 2013 12:37:36 +0100, Skybuck Flying wrote:
> To put the exit condition at the bottom is logical.
>
> The exit condition glues the loop to the code that will be executed next
> which is also at the bottom.
Skybuck, please excuse my question, but have you ever done any
programming at all? You don't seem to have any experience with actual
programming languages.
In a while loop, such as in Python, the test is at the top of the loop
because the test is performed at the start of the loop, not the end:
while x > 0:
do_this()
do_that()
It would be inappropriate (as well as ugly!) to put the test at the end
of the loop, like this:
x = 0
while:
do_this()
do_that()
many more lines go here
possibly even pages of code
until finally, at long last
you get to the end where you find the test...
x > 0
... and discover whether or not the while loop was actually entered or
not. Similarly with for-loops, the loop condition is at the beginning
because it runs at the beginning. This would be silly:
for i:
body of loop goes here
could be many many lines of code
even pages of code
but eventually, at long last
we get to the end, and find out
what the first value for i will be
in range(100, 110)
There is one sort of loop where it makes sense to have the loop condition
at the end. Python doesn't have such a loop, but Pascal does: the repeat
until loop. Unlike while, repeat until is always executed at least once,
so the loop condition isn't tested until the end of the loop:
repeat
do this
do that
do something else
until x > 0
[...]
> LoopBegin( Step = 10 )
>
> if ButtonExists then
> begin
> ClickButton()
> end;
>
> LoopEnd( ButtonClicked )
>
> Execute next code...
>
> This loop waits for the button to appear, once it's found it is clicked
> and then the loop exits to continue the next code.
What if the button has already appeared before the loop starts?
I think that is better written as:
# Check the loop condition at the start
while the button does not exist:
wait a bit
# Outside the loop
click the button
(Although such a loop is called a "busy wait" loop, since it keeps the
computer being busy without doing anything useful. There are better ways
to do this than a loop.)
Even in Pascal, I would use a while loop rather than repeat, but if you
insist on using repeat, clicking the button still should go on the
outside of the loop:
# this is wasteful, since even if the button exists, the loop still
# waits a bit, for no good reason
repeat
wait a bit
until the button exists
click the button
> Putting this exit condition on the top makes no sense.
Wait until you actually start programming before deciding what makes
sense or doesn't.
--
Steven
More information about the Python-list
mailing list