2014-07-10 88 views
0

我一直在做一些事情,需要在另一個無限的while循環內運行一個無限的while循環(不要判斷)並在發生某種事件時中斷。我需要在內部循環中斷時運行一次語句,而不必在外部循環中修改它。如果在Python中循環停止,只運行語句一次

我需要的是這樣的:

while True: 
    while condition: 
     do stuff 
    <run some code when the inside while finishes> 

    continue running external loop without running the line inside <> 

基本上,while-else結構的反向。

編輯:我已經改變了代碼來解決真正的問題。我很抱歉這個錯誤。被其他東西轟炸,並沒有想好。

+5

爲什麼不在'break'之前移動''? – bereal

回答

3

如果你只需要語句在內部休息時運行一次,爲什麼不把它放在if塊呢?

while True: 
    while condition: 
    if other-condition: 
     <code to run when the inside loop breaks> 
     break 

    <continue external loop> 

編輯:爲了(無if other_condition: ...; break)只有一次內部循環完成後運行,你應該使用下列內容:

while True: 
    has_run = False 
    while condition: 
    <loop code> 
    if not has_run: 
    <code to run when inner loop finishes> 
    has_run = True 

    <rest of outer loop code> 
+0

因爲我在寫代碼的時候搞亂了代碼。抱歉。 – Dumitru

+0

@KuraiHikari這可能是我錯誤地解釋了你的編輯,但似乎我提出的解決方案仍然有效。如果情況並非如此,請澄清。 – RevanProdigalKnight

+0

事情是,沒有「如果」,也沒有「其他條件」。我自己誤解了這個問題,並錯誤地發佈了它。如果我將''condition''而不是'other-condition'',基本上重複代碼,你的代碼就可以工作。 – Dumitru

-1

添加您切換代碼已經經過布爾執行一次!通過這種方式,您可以始終在循環中讓事情發生一次。另外,如果你想再次運行外部循環,內部循環將再次啓動,並且會再次中斷,那麼你確定只想運行那一行嗎?

broken = False 
while True: 
    while condition: 
     if other-condition: 
      break 
    if not broken: 
     broken = True 
     <run some code when the inside while breaks> 

    continue running external loop without running the line inside <> 
-1

如果需要繼續後while循環代碼要比使用可變was_break

while True: 

    was_break = False 

    while condition: 
     if other-condition: 
      was_break = True 
      break 

    if was_break: 
     <run some code when the inside while breaks> 

    continue running external loop without running the line inside <> 
+0

來自downvoter的評論? – furas

-1

Python的方式進行,這是與while循環使用別的。這是應該如何完成的。

如果else語句與while循環一起使用,則在條件變爲false時執行else語句。

x=1 
while x: 
    print "in while" 
    x=0 
    #your code here 
else: 
    print "in else" 
+0

「while-else」的問題是每當'while'中的條件是'False'時''else''都會運行,所以這是一個禁止行爲。當循環結束時,我需要該代碼運行一次。 – Dumitru

+0

是的,這是真的。 –

+0

如果在'while'中執行'break',則'else'不執行 - OP需要相反的東西。 – furas