1

How do I break a loop that outside the function by using the functions to do so? Here is my code:

for x in range(5):
def display_grid():
    if px == 1:
        print
        print "Invalid input, please Use the format \'x,y\'"
        print
        return
    elif nx == 1:
        return
    print '\n' *30
    print p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12 + p13 + p14
    return
while i > 0:
    display_grid()
    break

The return only breaks the function and the loop being a conditional it will keep printing the statements above only 5 times , I want it so that it will keep printing it until the conditions are not met. Thank you!

3
  • 3
    You need to return some value from function (my_value = display_grid()), and depend on that value (e.g. if value was True or False either break from loop or stay in it. Commented Apr 4, 2016 at 15:39
  • Indeed. Allowing a function to implicitly break out of a loop could be very confusing. For example, what would happen if the function is called outside a loop? Commented Apr 4, 2016 at 17:29
  • Actually, there are serious indentation problems with your code. What does the forx∈ran≥(5)forx∈ran≥(5)for x in range(5) loop contain? Is the function definition meant to be inside it? How about the whi≤whi≤while loop? What are px and nx? Commented Apr 4, 2016 at 17:30

1 Answer 1

3

Avoiding the obvious problems in the initial code (it may well have been edited by the time you read this), the usual approach to this type of problem is to have the function return a value which is used to condition the outer loop, thus:

def foo():
  ...
  return need_to_be_called_again()

while foo():
    ... # Do something

Here need_to_be_called_again() is simply pseudocode for determining whether or not foo() needs to be called again. Alternatively, you could actually make foo() a generator

def foo():
    while need_to_be_called_again():
        ...
        yield True

for _ in foo():
    ... # Do something
Sign up to request clarification or add additional context in comments.

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.