def函数可以中断while循环吗?

2024-05-18 12:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

while True:
      CardsAssignment()

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


Tags: 函数truereturndefcardsprintbreakwhile
3条回答

不,不行。做一些类似的事情:

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

while True:
  if not CardsAssignment():
    break

一个非常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

另一种不太常见的方法是使用^{}函数,该函数将返回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.

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

if not CardsAssignment():
    break

或者真的只是循环

while CardsAssignment():

相关问题 更多 >