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"
Related
How do I create a while loop using python in the command prompt? I want to create an infinite loop that prints a string. I know how to do this normally but being limited to a one line execute makes this very confusing.
$ python -c "while True: print(\"test\")"
Something like this?
The command line won't execute your line if there is another line that's meant to be there. You can just write your loop as you would normally and Python won't start executing it until your loop is closed:
>>> while True:
... print("abc")
... #something else
...
You have to press Enter twice to signal Python that you are done with your loop.
The syntax is the same that you would use in an IDE like vs code.
This is a really easy example:
c = 0
while c <= 3:
print(c)
c+=1
If you're making an infinite loop that simply just prints a string over and over again, something like this should work:
while True: print("Hello!")
Fits on one line and the condition and print argument can be modified to anything you like
I'm making a Discord bot with a lot of commands that take a while to finish (like loops) so I'd like to also have a command that stops any actively running code. I've tried sys.exit but I don't want to have to restart the program each time before it will take another input. Anyone know what I can do?
It will depend on the way your code is formatted, but you will probably want to use functions that utilize boolean or return statements:
def foo():
if end_this:
return
# stuff
If you have some tracking boolean end_this that is set to True, the function foo() will not execute everything below. Alternatively, you could use a while-loop with a break in your code:
def foo():
while True: # runs forever unless ended
# stuff
break
Now, foo() will continue indefinitely until the break statement is reached. An if-statement can enclose the break, setting some logic on when the break occurs. Again, this may require a main() function to handle the calls and ends of your previous functions, but it would allow following code/functions to execute.
I'm trying to exit an infinite loop but I'm stuck in it. I've tried using the break statement in different ways but the result is always the same: the program terminates after exiting the loop and it doesn't perform the rest of the code. What should I change in the code to solve this problem?
moylist = []
import copy
while True:
thing = input()
if thing == '':
break
moylist.append(thing)
moylist.insert(-2, 'and')
moynovlist = copy.deepcopy(moylist)
moynovlist1 = moynovlist[-2:] # cutting the end
perv = str(moynovlist1)
perv1 = perv[:4] + perv[4:] #without the comma (and ...)
The code is running fine! The reason you think it is exiting the whole program instead of just the while loop is because you don't have any print statements. Simply add, print(perv1) at the end of your program and you'll see that perv1 changes, meaning the loop was exited properly.
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.
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.