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

Ant*_*Lee 0 python

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

while True:
      CardsAssignment()
Run Code Online (Sandbox Code Playgroud)

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

ste*_*fen 9

不,它不能.做类似的事情:

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

while True:
  if not CardsAssignment():
    break
Run Code Online (Sandbox Code Playgroud)

  • 或者可能只是`当CardsAssignment():`取决于实际发生的事情. (8认同)

mar*_*eau 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
Run Code Online (Sandbox Code Playgroud)

另一种不太常见的方法是使用一个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.
Run Code Online (Sandbox Code Playgroud)