Given the following code (that doesn't work):
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
My first instinct would be to refactor the nested loop into a function and use return to break out.
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.
for a in xrange(10):
for b in xrange(20):
if something(a, b):
# Break the inner loop...
break
else:
# Continue if the inner loop wasn't broken.
continue
# Inner loop was broken, break the outer.
break
This uses the for / else construct explained at: Why does python use 'else' after for and while loops?
Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.
The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.
PEP 3136 proposes labeled break/continue. Guido rejected it because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.
First, ordinary logic is helpful.
If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.
class GetOutOfLoop( Exception ):
pass
try:
done= False
while not done:
isok= False
while not (done or isok):
ok = get_input("Is this ok? (y/n)")
if ok in ("y", "Y") or ok in ("n", "N") :
done= True # probably better
raise GetOutOfLoop
# other stuff
except GetOutOfLoop:
pass
For this specific example, an exception may not be necessary.
On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.
Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:
breaker = False #our mighty loop exiter!
while True:
while True:
if conditionMet:
#insert code here...
breaker = True
break
if breaker: # the interesting part!
break # <--- !
If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!
I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you really need to break out of nested loops, here's an interesting variant of the exception-raising approach that #S.Lott described. It uses Python's with statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:
from contextlib import contextmanager
#contextmanager
def nested_break():
class NestedBreakException(Exception):
pass
try:
yield NestedBreakException
except NestedBreakException:
pass
Now you can use this context manager as follows:
with nested_break() as mylabel:
while True:
print "current state"
while True:
ok = raw_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": raise mylabel
if ok == "n" or ok == "N": break
print "more processing"
Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built Exception subclass for each use of nested_break; no need to declare your own Exception subclass each time.
First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the while loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...
You may also use goto in the following way (using an April Fools module from here):
#import the stuff
from goto import goto, label
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": goto .breakall
if ok == "n" or ok == "N": break
#do more processing with menus and stuff
label .breakall
I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.
To break out of multiple nested loops, without refactoring into a function, make use of a "simulated goto statement" with the built-in StopIteration exception:
try:
for outer in range(100):
for inner in range(100):
if break_early():
raise StopIteration
except StopIteration: pass
See this discussion on the use of goto statements for breaking out of nested loops.
keeplooping = True
while keeplooping:
# Do stuff
while keeplooping:
# Do some other stuff
if finisheddoingstuff():
keeplooping = False
or something like that.
You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kind of like the GOTO method, provided you don't mind using an April Fool's joke module - it’s not Pythonic, but it does make sense.
This isn't the prettiest way to do it, but in my opinion, it's the best way.
def loop():
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": return
if ok == "n" or ok == "N": break
#do more processing with menus and stuff
I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.
Keep looping if two conditions are true.
I think this is a more Pythonic way:
dejaVu = True
while dejaVu:
while True:
ok = raw_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y" or ok == "n" or ok == "N":
dejaVu = False
break
There is no way to do this from a language level. Some languages have
a goto others have a break that takes an argument, python does not.
The best options are:
Set a flag which is checked by the outer loop, or set the outer
loops condition.
Put the loop in a function and use return to break out of all the loops at once.
Reformulate your logic.
Credit goes to Vivek Nagarajan, Programmer since 1987
Using Function
def doMywork(data):
for i in data:
for e in i:
return
Using flag
is_break = False
for i in data:
if is_break:
break # outer loop break
for e in i:
is_break = True
break # inner loop break
Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:
def it(rows, cols, images):
i = 0
for r in xrange(rows):
for c in xrange(cols):
if i >= len(images):
return
yield r, c, images[i]
i += 1
for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
... do something with r, c, image ...
This has the advantage of splitting up the complicated loop logic and the processing...
There is a hidden trick in the Python while ... else structure which can be used to simulate the double break without much code changes/additions. In essence if the while condition is false, the else block is triggered. Neither exceptions, continue or break trigger the else block. For more information see answers to "Else clause on Python while statement", or Python doc on while (v2.7).
while True:
#snip: print out current state
ok = ""
while ok != "y" and ok != "n":
ok = get_input("Is this ok? (y/n)")
if ok == "n" or ok == "N":
break # Breaks out of inner loop, skipping else
else:
break # Breaks out of outer loop
#do more processing with menus and stuff
The only downside is that you need to move the double breaking condition into the while condition (or add a flag variable). Variations of this exists also for the for loop, where the else block is triggered after loop completion.
An easy way to turn multiple loops into a single, breakable loop is to use numpy.ndindex
for i in range(n):
for j in range(n):
val = x[i, j]
break # still inside the outer loop!
for i, j in np.ndindex(n, n):
val = x[i, j]
break # you left the only loop there was!
You do have to index into your objects, as opposed to being able to iterate through the values explicitly, but at least in simple cases it seems to be approximately 2-20 times simpler than most of the answers suggested.
In this case, as pointed out by others as well, functional decomposition is the way to go. Code in Python 3:
def user_confirms():
while True:
answer = input("Is this OK? (y/n) ").strip().lower()
if answer in "yn":
return answer == "y"
def main():
while True:
# do stuff
if user_confirms():
break
Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the python reference
for i, j in ((i, j) for i in A for j in B):
print(i , j)
if (some_condition):
break
You could scale it up to any number of levels for the loop
The downside is that you can no longer break only a single level. It's all or nothing.
Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on Python - `break` out of all loops but unfortunately that's closed as a duplicate of this one
I'd like to remind you that functions in Python can be created right in the middle of the code and can access the surrounding variables transparently for reading and with nonlocal or global declaration for writing.
So you can use a function as a "breakable control structure", defining a place you want to return to:
def is_prime(number):
foo = bar = number
def return_here():
nonlocal foo, bar
init_bar = bar
while foo > 0:
bar = init_bar
while bar >= foo:
if foo*bar == number:
return
bar -= 1
foo -= 1
return_here()
if foo == 1:
print(number, 'is prime')
else:
print(number, '=', bar, '*', foo)
>>> is_prime(67)
67 is prime
>>> is_prime(117)
117 = 13 * 9
>>> is_prime(16)
16 = 4 * 4
By using a function:
def myloop():
for i in range(1,6,1): # 1st loop
print('i:',i)
for j in range(1,11,2): # 2nd loop
print(' i, j:' ,i, j)
for k in range(1,21,4): # 3rd loop
print(' i,j,k:', i,j,k)
if i%3==0 and j%3==0 and k%3==0:
return # getting out of all loops
myloop()
Try running the above codes by commenting out the return as well.
Without using any function:
done = False
for i in range(1,6,1): # 1st loop
print('i:', i)
for j in range(1,11,2): # 2nd loop
print(' i, j:' ,i, j)
for k in range(1,21,4): # 3rd loop
print(' i,j,k:', i,j,k)
if i%3==0 and j%3==0 and k%3==0:
done = True
break # breaking from 3rd loop
if done: break # breaking from 2nd loop
if done: break # breaking from 1st loop
Now, run the above codes as is first and then try running by commenting out each line containing break one at a time from the bottom.
Try using an infinite generator.
from itertools import repeat
inputs = (get_input("Is this ok? (y/n)") for _ in repeat(None))
response = (i.lower()=="y" for i in inputs if i.lower() in ("y", "n"))
while True:
#snip: print out current state
if next(response):
break
#do more processing with menus and stuff
# this version uses a level counter to choose how far to break out
break_levels = 0
while True:
# snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y":
break_levels = 1 # how far nested, excluding this break
break
if ok == "n" or ok == "N":
break # normal break
if break_levels:
break_levels -= 1
break # pop another level
if break_levels:
break_levels -= 1
break
# ...and so on
# this version breaks up to a certain label
break_label = None
while True:
# snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y":
break_label = "outer" # specify label to break to
break
if ok == "n" or ok == "N":
break
if break_label:
if break_label != "inner":
break # propagate up
break_label = None # we have arrived!
if break_label:
if break_label != "outer":
break # propagate up
break_label = None # we have arrived!
#do more processing with menus and stuff
Here's an implementation that seems to work:
break_ = False
for i in range(10):
if break_:
break
for j in range(10):
if j == 3:
break_ = True
break
else:
print(i, j)
The only draw back is that you have to define break_ before the loops.
What I would personally do is use a boolean that toggles when I am ready to break out the outer loop. For example
while True:
#snip: print out current state
quit = False
while True:
ok = input("Is this ok? (y/n)")
if ok.lower() == "y":
quit = True
break # this should work now :-)
if ok.lower() == "n":
quit = True
break # This should work too :-)
if quit:
break
#do more processing with menus and stuff
Solutions in two ways
With an example: Are these two matrices equal/same?
matrix1 and matrix2 are the same size, n, two-dimensional matrices.
First solution, without a function
same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)
for i in range(n):
for j in range(n):
if matrix1[i][j] != matrix2[i][j]:
same_matrices = False
inner_loop_broken_once = True
break
if inner_loop_broken_once:
break
Second solution, with a function
This is the final solution for my case.
def are_two_matrices_the_same (matrix1, matrix2):
n = len(matrix1)
for i in range(n):
for j in range(n):
if matrix1[i][j] != matrix2[i][j]:
return False
return True
probably little trick like below will do if not prefer to refactorial into function
added 1 break_level variable to control the while loop condition
break_level = 0
# while break_level < 3: # if we have another level of nested loop here
while break_level < 2:
#snip: print out current state
while break_level < 1:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": break_level = 2 # break 2 level
if ok == "n" or ok == "N": break_level = 1 # break 1 level
You can define a variable( for example break_statement ), then change it to a different value when two-break condition occurs and use it in if statement to break from second loop also.
while True:
break_statement=0
while True:
ok = raw_input("Is this ok? (y/n)")
if ok == "n" or ok == "N":
break
if ok == "y" or ok == "Y":
break_statement=1
break
if break_statement==1:
break
My reason for coming here is that i had an outer loop and an inner loop like so:
for x in array:
for y in dont_use_these_values:
if x.value==y:
array.remove(x) # fixed, was array.pop(x) in my original answer
continue
do some other stuff with x
As you can see, it won't actually go to the next x, but will go to the next y instead.
what i found to solve this simply was to run through the array twice instead:
for x in array:
for y in dont_use_these_values:
if x.value==y:
array.remove(x) # fixed, was array.pop(x) in my original answer
continue
for x in array:
do some other stuff with x
I know this was a specific case of OP's question, but I am posting it in the hope that it will help someone think about their problem differently while keeping things simple.
Trying to minimal changes to the OP's question, I just added a flag before breaking the 1st for loop and check that flag on the outer loop to see if we need to brake once again.
break_2 = False
while True:
# Snip: print out current state
if break_2: break
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break_2 = True
if break_2: break
if ok.lower() == "n": break
# Do more processing with menus and stuff
I came across this recently and, wanting to avoid a duplicate return statement, which can conceal logical errors, looked at #yak's idea. This works well within nested for loops but is not very elegant. An alternative is to check for the condition before the next loop:
b = None
for a in range(10):
if something(a, b): # should never = True if b is None
break
for b in range(20):
pass
This might not work everywhere but is adaptable and, if required, has the advantage of allowing the condition to be duplicated rather than a potential result.
My initial code...
name="LOVE"
i=0
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")
The desired outcome is
L
O
Hi
E
The end
I have read other answers on this topic and I was either unable to understand or didn't find the answer I was looking for.
I know writing continue in while loop is bad practice, even so I wanted to know whether there was a way to use it without throwing an error(logical or IndexError) or going to an infinite loop.
'while'
as of my knowledge, doesn't have an option of
while(i++<len(name))
in python, so that didn't work.
Since the control is transferred to the beginning of the loop and test expression is not evaluated again,
I tried keeping the increment statement above the continue block and the print statement below to be logically consistent with the desired output.
First I lost 'L' in my output with 'IndexError' at 'if' statement and I was expecting the same error at print statement in the end. So I tried to improve by beginning index from -1 instead and catching my error.
name="LOVE"
i=-1
try:
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
except IndexError:
print()
print("The end")
In using for, the continue statement transfers control simply to next iteration in which by virtue of being the next iteration the counter(val) is already incremented so it works fluidly. Like below,
for val in "LOVE":
if val == "V":
print('Hi')
continue
print('Hello')#never printed
print(val)
print("The end")
Again I know of this but that is not what I am interested in...
In summary what I would like to know is if there is a more elegant way to do this without a try catch block, some other kind of implementation of continue in while to reach desired output in Python 3.x?
P.S:-this is my first question on this forum, so please go a bit easy on me.
You don't really need continue, just an else clause on your if statement. (Also, since i == 0 to start, you need to wait until you've used i as an index before incrementing it.)
name="LOVE"
i=0
while i < len(name):
if name[i] == "V":
print('Hi')
else:
print(name[i])
i=i+1
print("The end")
or
for c in name:
if c == "V":
print('Hi')
else:
print(c)
This really is a for job. You want an end to the looping, represented by both the except clause and the i < len(name) condition, and a loop increment, presented by the i=i+1 increment. Both of these tasks are typically performed by an iterator, and strings are iterable. It is possible to rewrite a for in while form, but it's not terribly meaningful:
i = iter(name)
while True:
try:
c = next(i)
except StopIteration:
break
print('Hi' if c == 'V' else c)
It's just much easier to write for c in name.
You could also use a finally, which should execute no matter how the try is left:
i = 0
while i < len(name):
try:
if ...:
continue
finally:
i += 1
The elegant (pythonic) way to solve this problem is to use for-loop, like others have suggested. However, if you insist on using while-loop with continue, you should try to tweak the condition of the while-loop. For example like this:
name="LOVE"
i=-1
while i < len(name)-1:
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")
string="LOVE"
i=0
while i<len(string):
if string[i]=="V":
print("HI")
i+=1
continue
else:print(string[i])
i+=1
print("Thank You")
Is there a way to implement something like this:
for row in rows:
try:
something
except:
restart iteration
You could put your try/except block in another loop and then break when it succeeds:
for row in rows:
while True:
try:
something
break
except Exception: # Try to catch something more specific
pass
You could make rows an iterator and only advance when there is no error.
it = iter(rows)
row = next(it,"")
while row:
try:
something
row = next(it,"")
except:
continue
On a side note, if you are not already I would catch specific error/errors in the except, you don't want to catch everything.
If you have Falsey values you could use object as the default value:
it = iter(rows)
row, at_end = next(it,""), object()
while row is not at_end:
try:
something
row = next(it, at_end)
except:
continue
Although I wouldn't recommend that, the only way to do this is to make a While (True) Loop until it gets something Done.
Bear in mind the possibility of a infinite loop.
for row in rows:
try:
something
except:
flag = False
while not flag:
try:
something
flag = True
except:
pass
Have your for loop inside an infinite while loop. Check the condition where you want to restart the for loop with a if else condition and break the inner loop. have a if condition inside the while loop which is out side the for loop to break the while loop.
Like this:
while True:
for row in rows:
if(condition)
.....
if(condition)
break
if(condition)
break
Try this
it = iter(rows)
while True:
try:
something
row = next(it)
except StopIteration:
it = iter(rows)
My 2¢, if rows is a list, you could do
for row in rows:
try:
something
except:
# Let's restart the current iteration
rows.insert(rows.index(row), row)
continue # <-- will skip `something_else`, i.e will restart the loop.
something_else
Also, other things being equal, for-loops are faster than while-loops in Python. That being said, performance is not a first order determinant in Python.
I think user2555451's answer does it pretty well. That being said, you should use continue instead of pass as it will make sure the while True loop is restarted.
for row in rows:
while True:
try:
...
break
except Exception:
continue
I will explain it for newer Python users:
break only breaks the loop you're working in. So if you have something like this: (the variables and functions are imaginary)
for x in imgWidth:
for y in imgHeight:
if ...:
break
drawPixel(x, y, "#FF0000")
and you somehow want to skip a pixel, you can break the loop as it will return to the previous level. The same is true for continue.
Now back to the example:
for row in rows:
while True:
try:
...
break
except Exception:
continue
You move any code you would like to run inside the try block. It will try to do it, and if it catches an error, it will retry because we continue the while True loop! When it finally does the code without errors, it breaks and now it's back in the for loop. Then it continues to the next iteration as it has nothing left to do.
Here is a simple version without using nested loops, an infinite while loop, or mutating the original iterator. Also, it controls the number of attempts with a max_retry parameter:
def do_something(retry=0, max_retry=4):
try:
print('something')
except Exception as e:
if retry == max_retry:
print(f"Max retries reached!")
raise e
do_something(retry=retry + 1)
do_something()
I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
Many beginners accidentally stumble on this syntax when they try to put an if/else block inside of a while or for loop, and don't indent the else properly. The solution is to make sure the else block lines up with the if, assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error, and what the resulting code means. See also I'm getting an IndentationError. How do I fix it?, for the cases where there is a syntax error reported.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
Allow me to give an example on why to use this else-clause. But:
my point is now better explained in Leo’s answer
I use a for- instead of a while-loop, but else works similar (executes unless break was encountered)
there are better ways to do this (e.g. wrapping it into a function or raising an exception)
Breaking out of multiple levels of looping
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
The else clause is only executed when the while-condition becomes false.
Here are some examples:
Example 1: Initially the condition is false, so else-clause is executed.
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
this
Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
4
this
My answer will focus on WHEN we can use while/for-else.
At the first glance, it seems there is no different when using
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE' statement seems always executed in both cases (both when the while loop finished or not run).
Then, it's only different when the statement print 'ELSE' will not be executed.
It's when there is a breakinside the code block under while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return is not in this category, because it does the same effect for two above cases.
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in else clause or right after the while clause will not be executed.
I know this is old question but...
As Raymond Hettinger said, it should be called while/no_break instead of while/else.
I find it easy to understeand if you look at this snippet.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with else and get rid of that check.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_break to understand the code and that syntax makes much more sense to me.
thing = 'hay'
while thing:
if thing == 'needle':
print('I found it!!') # wrap up for break
break
thing = haystack.next()
else:
print('I did not find it.') # wrap up for no-break
The possibly unfortunately named else-clause is your place to wrap up from loop-exhaustion without break.
You can get by without it if
you break with return or raise → the entire code after the call or try is your no-break place
you set a default before while (e.g. found = False)
but it might hide bugs the else-clause knows to avoid
If you use a multi-break with non-trivial wrap-up, you should use a simple assignment before break, an else-clause assignment for no-break, and an if-elif-else or match-case to avoid repeating non-trival break handling code.
Note: the same applies to for thing in haystack:
Else is executed if while loop did not break.
I kinda like to think of it with a 'runner' metaphor.
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).
So the output would be this:
5
4
3
2
1
what the...
Suppose you've to search an element x in a single linked list
def search(self, x):
position = 1
p =self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, "not found in list")
return False
So if while conditions fails else will execute, hope it helps!
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
n = 5
while n != 0:
print n
n -= 1
print "what the..."
As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.