def CardsAssignment():
Cards+=1
print (Cards)
return break
while True:
CardsAssignment()
是的,我知道我不能return break
。但是我怎样才能通过 def 函数打破 while 循环呢?还是我的概念错了?
def CardsAssignment():
Cards+=1
print (Cards)
return break
while True:
CardsAssignment()
是的,我知道我不能return break
。但是我怎样才能通过 def 函数打破 while 循环呢?还是我的概念错了?
不,它不能。执行以下操作:
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
另一种不太常见的方法是使用一个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.
您可以CardsAssignment
返回True
(继续)或False
(停止)然后
if not CardsAssignment():
break
或者实际上只是循环
while CardsAssignment():
如果您使用for
循环而不是 a ,则可以通过ingwhile
使其提前中断- 这是循环结束的常用信号,作为例外,它可以嵌套在函数中任意深度,并将向外传播直到被抓住。这意味着您需要一些东西来迭代 - 因此,您可能希望将您的函数更改为生成器:raise
StopIteration
for
def cards_assignment():
cards += 1
yield cards
for card in cards_assignment():
print(card)
raise StopIteration
,在这种情况下,您只需return
从生成器中完成,而不是做,循环将完成。但是,请注意,这(以及使函数返回您在循环条件中测试的标志的选项)与使用略有不同break
- 如果您else
在循环中使用子句,return
来自生成器的 ing 将触发它,而break
在循环体不会。
我很想重新考虑类似于:
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
def CardsAssignment():
Cards+=1
print (Cards)
if (break_it):
return False
else:
return True
while CardsAssignment():
pass
在 3.5、3.6 中可以
return "break"