If I have two while: loops, one inside of the other, like such:
while #test :
while #test :
#other code
if #test :
break
#other code
Will the break stop both while: loops or only the one where the if #test : is in?
Thanks for the help!
It would only stop the inner loop. If you wanted to break both loops, you'd have to provide another condition to break in the outer loop.
A break always breaks only the loop enclosing it, so the last line of the code will be executed under the outer loop.
Learn more
From python documentation:
break may only occur syntactically nested in a for or while loop, but
not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional else
clause if the loop has one.
"break terminates the nearest eclosing loop" - e.g. only inner while
break only stop the one where the if #test,so the other code will be exec.
Related
who can say me:
What is the difference between writing code inside else or just after the loops?
for x in range(6):
print('hello')
print('bye')
or
for x in range(6):
print('hello')
else:
print('bye')
From for/else documentation:
The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.
This means that in your specific example there is no difference in using else or not.
In the second example you're using conditional statement, Whereas in the first scenario after the loop completes, It automatically executes the next line.
Basically your post is an example of getting same result with alternative solutions.
Though your first solution can be considered as valid practice comparing with second one.
Although I would suggest you to read this article before posting any questions on stack overflow.
I've been doing something that needs to run an infinite while loop inside another infinite while loop (don't judge) and breaks if some sort of event happens. I need to run a statement once when the inside loop breaks, without having it modified in the external loop.
I need something like this:
while True:
while condition:
do stuff
<run some code when the inside while finishes>
continue running external loop without running the line inside <>
Basically, the reverse of a while-else construct.
Edit: I've changed the code to relate to the real problem. I'm really sorry for the mistake. Was bombarded by other stuff and wasn't thinking right.
If you only need the statement to run once when the internal while breaks, why not just put it in the if block?
while True:
while condition:
if other-condition:
<code to run when the inside loop breaks>
break
<continue external loop>
EDIT: In order to run only once after the inner loop is finished (without an if other_condition: ...; break) you should use the following:
while True:
has_run = False
while condition:
<loop code>
if not has_run:
<code to run when inner loop finishes>
has_run = True
<rest of outer loop code>
Add a boolean that you switch after the code has been executed once! This way you can always make things happen just once in a loop. Also, if you want to run the external loop again, the internal loop will start again, and it will break again, so are you sure you only want to run that line once?
broken = False
while True:
while condition:
if other-condition:
break
if not broken:
broken = True
<run some code when the inside while breaks>
continue running external loop without running the line inside <>
If you need continue code after while loop than use variable was_break
while True:
was_break = False
while condition:
if other-condition:
was_break = True
break
if was_break:
<run some code when the inside while breaks>
continue running external loop without running the line inside <>
Pythonic way for this is to use else with while loop. This is how it should be done.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
x=1
while x:
print "in while"
x=0
#your code here
else:
print "in else"
This question already has answers here:
Is there a difference between "pass" and "continue" in a for loop in Python?
(13 answers)
Closed 5 years ago.
My test shows that both pass and continue can be used equivalently to construct a empty for-loop for test purpose. Are there any difference between them?
The pass keyword is a "no-operation" keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later:
if response == "yes":
pass # add "yes" code later.
The continue keyword, on the other hand, is used to restart a loop at the control point, such as with:
for i in range(10):
if i % 2 == 0:
continue
print(i)
That loop will only output the odd numbers since continue returns to the loop control statement (for) for iterations where i is even.
Contrast that with the exact same code, but using pass in place of continue:
for i in range(10):
if i % 2 == 0:
pass
print(i)
That loop prints all the numbers in the range, since pass does not return to the loop control statement for even (or any) values of i. It simply drops through to the print statement.
In terms of an empty for loop, you're correct that they're functionally identical. You can use either of:
for i in range(10):
pass
for i in range(10):
continue
pass does nothing (no operation), while continue make control flow to continue to next cycle of the loop.
If the loop contains only a single statement, a pass or continue won't make any difference. But if there are multiple statements, then it matters:
for item in my_list:
pass
print(item) #This will be executed
for item in my_list:
continue
print(item) #won't be executed
Basically, the pass statement do nothing, while the continue statement will restart the loop.
But in your case:
for item in my_list:
pass
#Since there's nothing after pass, the loop is finished.
for item in my_list:
continue
#You're restarting the loop
There difference is not very visible.
Hope this helps!
continue means "skip to the end of the loop body". If it's a while loop, the loop continues on to the loop test; if it's a for loop, the loop continues on to the next element of whatever it's iterating over.
pass does absolutely nothing. It exists because you have to have something in the body of an empty block statement, and pass is more readable than executing 1 or None as a statement for that purpose.
This will lead to an infinite loop if you use continue:
i = 0
while i<1:
continue
i = i + 1
print i
because continue only goes to the next iteration. But pass will work for this case.
pass and continue both work, but may create infinite loops.
For example, the following code will create infinite loop.
i = 0
while i<100:
continue # replacing continue with pass still creates an infinite loop.
If you want to avoid this (perhaps you intend to modify i withe loop, but you haven't written the code yet), use break.
I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above
What I've ended up doing works, but feels off somehow:
def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop
if some_condition_met is False:
do a thing
Is there a better way?
You're looking for while-else loop:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above
From docs:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.
Use an else clause to the while loop:
while some_condition:
do_stuff()
if a_condition_is_met:
break
else:
executed_when_never_broken
See the while statement documentation:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
If you think about it, you might already have a perfectly good condition to use without setting a flag: the condition at the top of the while loop (or, rather, the not of it). Assuming you don't change the truthiness of your condition during the same iteration as a break, this gives you:
while something:
do_stuff()
if something_else:
break
if not something:
more_stuff()
This makes sense if you think of while as a repeated if: instead of happening once, a while keeps going until the condition becomes falsey.
But, like the other answers have mentioned, the analogy goes further: just like you don't have to spell all your ifs as
if a:
a_stuff()
if not a:
b_stuff()
while accepts an else that is executed if the condition at the top is tested and found to be falsey. So,
while something:
do_stuff()
if something_else:
break
else:
more_stuff()
And, same as the if/else case, this doesn't imply any further tests of the condition than what would happen anyway. In the same way that an else attached to if a won't run if the true-branch makes a falsey, an else attached to a while will never run after a break since that explicitly skips ever checking the condition again. This makes the else: equivalent to a decicated flag in every case.
This also extends to for loops, even though the analogy breaks - but it executes under similar enough rules: the else is run if the loop ends by having run its course rather than hitting a break.
in the following python code:
narg=len(sys.argv)
print "#length arg= ", narg
if narg == 1:
print "#Usage: input_filename nelements nintervals"
break
I get:
SyntaxError: 'break' outside loop
Why?
Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit() or return instead?
break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like
for item in some_iterable:
...
if break_condition():
break
The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.
Because break can only be used inside a loop.
It is used to break out of a loop (stop the loop).
Because the break statement is intended to break out of loops. You don't need to break out of an if statement - it just ends at the end.
This is an old question, but if you wanted to break out of an if statement, you could do:
while 1:
if blah:
break