[Tutor] How do I create a "loop until" looping structure?

Alan Gauld alan.gauld at btinternet.com
Wed May 21 15:41:10 CEST 2014


On 21/05/14 11:32, 1 2 wrote:
> Hi there,
>    As shown in the codes below, I want to end the loop until the s is no
> greater than -5 but I found there is no "do... loop until..." like C so
> what should I do? I will write it in C's style

Normally you just reverse the logic and use a
while loop instead.

> s,n = 0,1
> do:
>      import math
>      s=s+(math.log((n+1)/(n+2))/math.log(2))
> loop until s < -5

import math
s = 100  # or whatever
while s >= -5:
    s = .....
print(s)

But that doesn't work if the variant can not be suitably
initialized before the loop starts - as is the case here.
So instead you can use a while True with a break condition:

import math
s,n = 0,1
while True:
    s = ...
    if s < -5: break


hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list