2013-10-17 31 views
2

有什麼方法可以使用函數打破無限循環?例如,使用函數打破一個while循環

# Python 3.3.2 
yes = 'y', 'Y' 
no = 'n', 'N' 
def example(): 
    if egg.startswith(no): 
     break 
    elif egg.startswith(yes): 
     # Nothing here, block may loop again 
     print() 

while True: 
    egg = input("Do you want to continue? y/n") 
    example() 

這會導致以下錯誤:

SyntaxError: 'break' outside loop 

請解釋爲什麼發生這種情況以及如何可以固定。

回答

3

就我而言,你不能從example()中調用突破,但你可以把它返回一個值(例如:一個布爾)爲了阻止無限循環

代碼:

yes='y', 'Y' 
no='n', 'N' 

def example(): 
    if egg.startswith(no): 
     return False # Returns False if egg is either n or N so the loop would break 
    elif egg.startswith(yes): 
     # Nothing here, block may loop again 
     print() 
     return True # Returns True if egg is either y or Y so the loop would continue 

while True: 
    egg = input("Do you want to continue? y/n") 
    if not example(): # You can aslo use "if example() == False:" Though it is not recommended! 
     break 
0

結束while-true循環的方法是使用break。此外,break必須位於循環的直接範圍內。否則,你可以利用異常來處理堆棧中的任何代碼處理它。

然而,通常值得考慮另一種方法。如果你的例子實際上是接近你真正想要做的,即根據一些用戶提示輸入,我會做這樣的:

if raw_input('Continue? y/n') == 'y': 
    print 'You wish to continue then.' 
else: 
    print 'Abort, as you wished.' 
+0

+1如果您需要複雜的嵌套使用異常。一個真實的例子是迭代器在完成時引發'StopIteration'異常。 –

0

的另一種方式,打破了功能的一個循環內會從提升StopIteration以內的函數,並且到除了StopIteration以外的循環。這將導致循環立即停止。例如,

yes = ('y', 'Y') 
no = ('n', 'N') 

def example(): 
    if egg.startswith(no): 
     # Break out of loop. 
     raise StopIteration() 
    elif egg.startswith(yes): 
     # Nothing here, block may loop again. 
     print() 

try: 
    while True: 
     egg = input("Do you want to continue? y/n") 
     example() 
except StopIteration: 
    pass