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
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.
不,不行。做一些类似的事情:
一个非常Pythonic的方法是使用异常,如下所示:
另一种不太常见的方法是使用^{} 函数,该函数将返回
True
,指示是时候停止对其调用next()
:您可以让
CardsAssignment
返回True
(继续)或False
(停止),然后或者真的只是循环
相关问题 更多 >
编程相关推荐