Monday, May 25, 2020

While loops

While Loop

The format is: 

while x op y:
    commands
    iterating command on either x or y
    optional break to exit loop forcibly
    optional continue to go to next iteration at top of loop; it is essentially a go-to statement.
else:
    commands that execute only once, if at all.

where op is:       ==   !=  <  >  <=  >=  

What happens here?

r = 1
s = 1
while r < 10:
r +=1
if r == 7:
# 7 is not included in this running total
continue
if r == 8:
break
# since s is updated only AFTER the break and continue calls, the loop only iterates 5 times, not 6 times.

s += r
print(s)
else:
print(s)  # not reachable

gives

3
6
10
15
21

The else clause is unreachable because break forces an exit before the iterating loop variable can hit the condition for it to quit; a break bypasses any else clause. r only got as far as 7.

Now remove the if - break commands

r = 1
s = 1
while r < 10:
r +=1
if r == 7:
# 7 is not included running total
continue
s += r
print(s)
        y = 999
else:
print(s)  # prints s a second time as r hit 10 so the the while condition failed right then
        print(y)


gives:

3
6
10
15
21
29
38
48
48
999

notice that 7 was not included in the result.

Important: if you use the continue keyword, then make sure that your iterating command comes before continue in the loop. Otherwise an infinite loop will result.

Note that the else keyword is optional, but if used, is considered outside of the loop.  It means that break and continue are invalid in the else and will generate a run-time error. Unexpectedly though, any variable local to the loop will still be in scope in the else portion, as was shown above.



No comments:

Post a Comment