def函数可以打破while循环吗?

时间:2012-07-29 12:48:01

标签: python

def CardsAssignment():
      Cards+=1
      print (Cards)
      return break      

while True:
      CardsAssignment()

是的,我知道我不能return break。但是如何通过def函数打破while循环呢?或者我的概念是错的?

7 个答案:

答案 0 :(得分:9)

不,不能。做类似的事情:

def CardsAssignment():
  Cards+=1
  print (Cards)
  if want_to_break_while_loop:
    return False      
  else:
    return True

while True:
  if not CardsAssignment():
    break

答案 1 :(得分:5)

非常 Pythonic 这样做的方法是使用以下类似的异常:

class StopAssignments(Exception): pass  # Custom Exception subclass.

def CardsAssignment():
    global Cards  # Declare since it's not a local variable and is assigned.

    Cards += 1
    print(Cards)
    if time_to_quit:
        raise StopAssignments

Cards = 0
time_to_quit = False

while True:
    try:
        CardsAssignment()
    except StopAssignments:
        break

另一种不太常见的方法是使用generator函数返回True,表示是时候退出调用next()

def CardsAssignment():
    global Cards  # Declare since it's not a local variable and is assigned.

    while True:
        Cards += 1
        print(Cards)
        yield not time_to_quit

Cards = 0
time_to_quit = False
cr = CardsAssignment()  # Get generator iterator object.
next(cr)  # Prime it.

while next(cr):
    if Cards == 4:
        time_to_quit = True  # Allow one more iteration.

答案 2 :(得分:4)

您可以CardsAssignment返回True(继续)或False(停止),然后

if not CardsAssignment():
    break

或者确实只是循环

while CardsAssignment():

答案 3 :(得分:3)

如果您使用的是for循环而不是while,则可以raise StopIteration使其早日中断 - 这是for的通常信号{1}}循环完成,作为例外,它可以根据需要嵌套在函数内部,并向外传播直到被捕获。这意味着您需要迭代一些东西 - 因此,您可能希望将函数更改为生成器:

def cards_assignment():
     cards += 1
     yield cards

for card in cards_assignment():
    print(card)

,在这种情况下,您只需要raise StopIteration来自return而不是break,并且循环将完成。但是请注意,这(以及具有该函数的选项返回在循环条件下测试的标志)与使用else略有不同 - 如果在循环中使用return子句,{ {1}来自生成器会触发它,而循环体中的break则不会触发它。

答案 4 :(得分:0)

def CardsAssignment():
      Cards+=1
      print (Cards)
      if (break_it):
          return False      
      else:
          return True      

while CardsAssignment():
    pass

答案 5 :(得分:0)

我很想重新考虑类似于:

def somefunc():
    from random import randint
    while True:
        r = randint(1, 100)
        if r != 42:
            yield r

然后你可以做以下事情:

for cnt, something in enumerate(somefunc(), start=1):
    print 'Loop {} is {}'.format(cnt, something)

这允许从somefunc()返回可能有意义的值,而不是将其用作"我是否打破"标志。

这也将允许以下构造:

sf = somefunc()
for something in sf:
    if some_condition(something):
        break

# other bits of program

for something in sf: # resume...
    pass

答案 6 :(得分:-1)

在3.5,3.6你可以

return "break"