1

I am currently stuck on something I am trying to break out of a while loop that is like this

while True
    if blah blah
        function()
        if blah blah:
            #break while loop

I tried a lot of methods but I can't seem to get it working, can anyone teach me?

EDIT: I fixed the example I typed above.

5
  • break However, I would write this code differently, flag = True while flag: "do stuff" if blah blah: flag = False Commented Sep 25, 2018 at 1:04
  • possible duplicate of stackoverflow.com/questions/42318622/… Commented Sep 25, 2018 at 1:04
  • 1
    just add break to that if. I think you meant something else so show us the real code because this example is most likely not what you intended it to be Commented Sep 25, 2018 at 1:04
  • 1
    What do you mean by "in a function"? Is the if condition actually inside function()? Because that's a more difficult and more interesting question than the one posed. Commented Sep 25, 2018 at 1:06
  • break should do what you want. If it doesn't post a minimal reproducible example of actual Python code that reproduces your issue. Commented Sep 25, 2018 at 1:10

2 Answers 2

0

That's exactly what a break statement does.

while True:
    function()
    if blah blah:
        break

Of course, if possible you should move the test to the loop condition.

while not blah blah:
    function()
Sign up to request clarification or add additional context in comments.

Comments

0

If you need to break the loop from "inside" the function, there are several ways of doing it:

  • return True/False from the function, and check the return value in the loop
  • raise a special exception from the function and catch it inside the loop

Examples:

# example 1
def function():
    if cloudy and not umbrella:
        print "no good to stay outside"
        return False
    return True

while nice_weather:
    if not function():
        break


# example 2
class RunHome(Exception):
    pass

def function():
    if thunderstorm:
        raise RunHome()

while enjoying:
    try:
        function()
    except RunHome as re:
        break

Depending on what actually the function and the loop do, some other techniques may be suitable as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.