||Home||Switchboard||Unix Administration||Red Hat||TCP/IP Networks||Neoliberalism||Toxic Managers|
|(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix|
When combined with the loop
else clause, the
break statement can often eliminate the need for the search
status flags used in other languages.
If else clause is present then break transfere control after then else clause.
For instance, the following piece of code determines whether a positive integer
y is prime by searching for factors
greater than 1:
x = y // 2
# For some y > 1while x > 1: if y % x == 0:
# Remainderprint(y, 'has factor', x) break
# Skip elsex -= 1 else:
# Normal exitprint(y, 'is prime')
Rather than setting a flag to be tested when the loop is exited, it inserts a
break where a factor is found. This way,
else clause can assume that it will be executed only if no factor is found; if you don’t hit the
the number is prime. Trace through this code to see how this works.
else clause is also run if the body of the loop is never executed, as you don’t run a
that event either; in a
while loop, this happens if the test in the header is false to begin with. Thus, in the preceding
example you still get the “is prime” message if
x is initially less than or equal to 1 (for instance, if
What is actually is needed is not else clause but the full case statement with branches continued outside the loop. That was pointed out by Knuth classic paper. So Python solution falls short unless if have a subroutine and can use return in else clause.
Google matched content