如何使用函数打破循环

时间:2016-04-04 15:33:16

标签: python python-2.7

如何通过使用函数来破坏函数外部的循环? 这是我的代码:

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

返回只会破坏函数并且循环是一个条件,它将继续打印上面的语句只有5次,我希望它能继续打印它直到条件不满足。谢谢!

1 个答案:

答案 0 :(得分: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