Pass 'continue' from inside a function to the outer loop in Python - python

I hope i can express myself accordingly, as I'm quite new to programming and I'm sure the answer is quite simple but I can't get there... :)
So I have a 'for' loop that executes some functions. Each function has an 'if' statement in it and only does something, if the conditions allow so.
What I want is the loop to reset, as soon as a function's 'if' statement is satisfied.
Edit: I messed up the function :( thx for your answers so far ^^
An example of what i wish would work:
def do_something():
if something == True:
do_some_stuff
return continue
while i < 999:
do_something()
do_something2()
do_something3()
The 'return continue' is the part that doesn't work as I wish and I can't find a solution for that (maybe I don't know what exactly to google for)

You can have 'do_something' return a boolean
def do_something():
if something is True:
do_some_stuff
return True
return False
while i < 999:
if do_something():
continue
do_something2()
do_something3()

There's no function, so there's nothing to return. You can however break out of the while loop once the condition something is met like so:
while i < 999:
if something == True:
do_some_stuff
break

Related

can we use break statement in if-else statement in python

I am trying to use break statement in below code snippet, but i am getting an error "break is outside loop".
what I am trying to do here is when m1=n2, i want to display that matrix multiplication is possible and when m1 !=n2, i want to display the message saying multiplication is not possible and program should stop after displaying the message. any suggestions as to how can i do it.
code snippet is as below -
if (n1 == m2):
print ("matrix multiplication is possible")
else:
print ("matrix multiplication is not possible")
... where should i put break statement here?
break and continue should be used in the loop body. You can use return in functions to terminate it or exit() to stop running the code.
Break is only used for loops such as: while, do while, switch
If you want to end your if statements from executing, you can use return;
By adding return; all else if statements after it won't execute. It's similar to break but not the same :)
Like this;
def myFunction(n1,m2):
if n1 == m2:
print ("matrix multiplication is possible")
else:
print ("matrix multiplication is not possible")
return None #Not really needed, since functions return None by default
myFunction(2,2)

Continuing function after else

thanks in advance for the help!
I'm building a simple program; the idea is for it to periodically check whether a variable has changed and, if it has, do something and, if not, check again. Use case: show a graph derived from the user's current URL in their browser; if the URL is unchanged, do nothing, if it changes, redraw the graph.
I'm running into an issue; I want my function to keep running while the condition is met, and if the condition is not met do something else, but then keep running.
Here's my while function code; my IDE and reading are telling me that "continue" is not permitted here: is there another way that I can keep my function active? Conversely, please do let me know if this is a foolish way to achieve what I'm trying to do!
while new_value != previous_value:
#wait
#do something
#put contents of new_value into previous_value
#update new_value from external source (e.g. URL from browser, which may or not be have changed)
else:
#wait
#do nothing
#put contents of new_value into previous_value
#update new_value from external source
continue
that's an alright start. The while loop will stop if the values are identical which is often. Inside the while loop you can add an if statement for the desired result. While True keeps going until stopped.
while True:
#wait for a couple of seconds
if new_value != previous_value:
#do something
#put contents of new_value into previous_value
#update new_value from external source
I would try something like this:
while True:
#wait some seconds if you need
if(new_value != previous_value):
#do something
else:
#update new_value from external source
I would use a while loop to keep your program running, and then use an if/else statement within the loop. Then just use break statement to stop running the loop.
while True:
if new_value != previous_value:
# Run your code
else:
# Run your code
# When I want the loop to end
break
The issue here is that the 'else' statement, when used like this, is being executed once your loop is already broken. As such there is nothing to 'continue' and your IDE is flagging a syntax error.
This is a somewhat obscure Python construct, but it (and the reasoning behind it) are well explained here at 15m53s.
What you're probably meaning to do is this:
while True:
if new_value != previous_value:
# Do one thing
else:
# Do a different thing
# You will need to specify an end condition,
# or it will continue looping indefinitely.
if exit_conditon_met:
break

Is it possible to use "while something" instead of "while True" in this piece of code?

I've read on a few pages online that using "while True" and manually break the while loop with "break" is a bad practice. In this particular case, I'd like to not use "while True" and I wonder if it's possible.
while True:
x = input()
try:
x = float(x)
break
except ValueError:
continue
I've tried doing this:
while x is not float:
x = input()
try:
x = float(x)
except ValueError:
continue
But the loop never breaks.
Is there a possible solution, or is it better to keep this as a "while True" loop?
You can use isinstance to check if x is an instance of float or not, as per the suggestion by #Enzo
#Define x as None here
x = None
#Run loop until you find x which is a float
while not isinstance(x, float):
x = input()
try:
#If x can be cast to a float, the loop will break
x = float(x)
except ValueError:
continue
If this is the entire loop, there's not much of a problem with using break. The main reason you should try to avoid break is because it can make larger loops or loops with more branches (if, etc.) inside hard to follow.
I don't think Python has a very simple way to do this, so a simple loop with break works well. The solution suggested in the other answers (using a placeholder value for x) works as well, but I personally find it less readable.
From PEP 315 we have this statement:
Users of the language are advised to use the while-True form with an inner if-break when a do-while loop would have been appropriate.
This statement refers to this part of the PEP 315:
Subsequent efforts to revive the PEP in April 2009 did not meet with success because no syntax emerged that could compete with the following form:
while True:
<setup code>
if not <condition>:
break
<loop body>
You don't cite the sources that claim this is "bad practice", but these excerpts from PEP 315 contradict them.

Break main function that contains "while True" with "return" from a subfunction

I want to run a Python program function from a main function that controls the program function with
while True:
I'm led to believe this is good practice. I thought a return call in the program function would break me out, but I get stuck in an infinite loop. Typing "n" should break the loop - how do I do it and is this a sensible thing to do?
def main():
while True:
runPgm()
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
break
return
if __name__ == '__main__':
main()
You just need one infinite loop
def main():
runPgm()
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
return
if __name__ == '__main__':
main()
This isn't working because your break statement (and subsequent return) just exits the current call to the runPgm function. But this returns you to the loop in main, which is never broken out of.
In general you can do "multiple breaks" like this by setting a Boolean flag to say you've want to do a further break, which is checked in the outer loop. However, in your case I think the easier solution is simply to only use one of the loops, not both. Just get rid of the main function entirely and call runPgm instead!
There are two things for you in this.
Use single while True loop.
rather break just use return here because function exits as soon as return is reached.
see below python3 code example.
def main():
print(runPgm())
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
return a
if __name__ == '__main__':
main()
The original source for my initial code is the pygame manual, the answers here show that I don't need to follow that method. However, I'm still unsure why the example in pygame resolves itself. But that's beyond the scope of this question and I'm satisfied I don't need to implement it.

Best way to quit a python programme?

I feel like an idiot asking this but is doing quit() the best way to terminate a python programme? Or is there a better way that could gradually stop all while True loops ect instead of just instantly stopping it all? Once again, I feel like an idiot asking this but I'm just curious.
I don't know why you don't want to use quit() but you can use this:
import sys
sys.exit()
Or this:
raise SystemExit(0)
To halt a while loop you can use the break statement. For example:
while True:
if True:
do something #pseudocode
else:
break
The break statement will immediately halt the while loop as soon as the else statement is read by python
You can use the break statement to stop a while loop. Eg:
while True:
if True:
<do something>
else:
break
Generally, the best way to end a Python program is just to let the code run to completion. For example, a script that looks for "hello" in a file could look like this:
# import whatever other modules you want to use
import some_module
# define functions you will use
def check_file(filename, phrase):
with open filename as f:
while True:
# using a while loop, but you might prefer a for loop
line = f.readline()
if not f:
# got to end of file without finding anything
found = False
break
elif phrase in line:
found = True
break
# note: the break commands will exit the loop, then the function will return
return found
# define the code to run if you call this script on its own
# rather than importing it as a module
if __name__ == '__main__':
if check_file("myfile.txt", "hello"):
print("found 'hello' in myfile.txt")
else:
print("'hello' is not in myfile.txt")
# there's no more code to run here, so the script will end
# -- no need to call quit() or sys.exit()
Note that once the phrase is found or the search comes to the end of the file, the code will break out of the loop, and then the rest of the script will run. Eventually, the script will run out of code to run, and Python will exit or return to the interactive command line.
If you want to stop a while True loop, you could set a variable to True and False, you could even work with a counter if you loop has to stop after a specific amount of loops.
for example
x = 0
y = True
while y == True:
<do something>
x = x + 1
if x == 9:
y = False
just a quick example of what you could do, without using a while loop(basically what i wrote above, but then in 1 line.)
x = 10
for i in range(x):
<do something>
To stop a program, I normally use exit() or break.
I hope this somehow helped you, if not; please comment and I'll try helping you!

Categories