2015-10-20 255 views
-1
def n(): 
     name = input('What is the missing animal?') 
     if name == 'dog': 
       print('Well done') 
     else: 
     print('Sorry this is not right') 
     rep= 0 
     while rep < 5: 
        n() 
     rep = rep + 1 
     if rep == 5: 
       print ('You have guessed incorrectly 5 times.) 

當我運行這個並得到錯誤的答案,程序不斷重複,而不是重複最多5次。爲什麼while循環在if循環中不起作用?

任何想法?

+1

遞歸調用從0開始。您永遠不會進入while循環的第二次迭代。 – Prune

+1

'if'不是一個循環;這是一個分支語句。 – chepner

回答

2

什麼是一個尷尬的遞歸。 :)

問題是,rep變量是本地作用域,即不傳遞給遞歸調用。

您應該將while置於外部,並使用success變量與while以測試是否需要再次循環。

無需遞歸。

編輯: 像這樣:

def n(): 
    rep= 0 
    success = 0 
    while rep < 5 or success == 1: 
     name = input('What is the missing animal?') 
     if name == 'dog': 
      success = 1 
     else: 
      print('Sorry this is not right') 
      rep = rep + 1 
    if rep == 5: 
     print ('You have guessed incorrectly 5 times.') 
    elif success == 1: 
     print('Well done') 

對不起縮進。

+0

我曾嘗試在外面放置while循環,但是當我這樣做,並且我猜對了合適的動物時,它總是問我缺少的動物是什麼。@維克多 – Francis

+0

這就是爲什麼你必須檢查「成功」。你也可以像Zach的答案一樣使用'break'。 – Victor

-3

您應該在函數定義之外初始化您的rep變量,因爲每當您調用n()函數時,它都會重新初始化爲0,並且永遠不會遞增。程序將繼續運行。

你也應該增加代表變量後調用N()函數,因爲否則它不會到達

rep = rep + 1 

聲明。

所以你的代碼應該是這樣的。

rep= 0 
def n(): 
    name = input('What is the missing animal?') 
    if name == 'dog': 
     print('Well done') 
     rep = 0 # re initialize rep for future usage 
     return # guessed correctly so should exit the method. 
    else: 
     print('Sorry this is not right') 

    while rep < 5: 
     rep = rep + 1 
     n() 
    if rep == 5: 
     print ('You have guessed incorrectly 5 times.) 
     rep = 0 # re initialize rep for future usage 
2
def n(): 
    for rep in range(5): 
     name = input('What is the missing animal?') 
     if name == 'dog': 
      print('Well done') 
      break 
     else: 
      print('Sorry this is not right') 
    else: 
     print ('You have guessed incorrectly 5 times.') 

既然你知道你想要多少次都要經過環,是(也許)更合適。 其他子句爲循環處理的情況下,你完成沒有得到正確的答案。

0

您一直在else語句中反覆調用n()方法。我相信這段代碼會爲你的願望是什麼工作:

def n(): 
    rep= 0 
    while rep < 5: 
     name = input('What is the missing animal? ') 
     if name == 'dog': 
      print('Well done') 
      break 
     else: 
      print('Sorry this is not right') 
     rep = rep + 1 
    if rep >= 5: 
     print ('You have guessed incorrectly 5 times.') 

這將運行循環5次,除非你得到的答案是正確的。如果答案是正確的,循環將break,這意味着它停止運行。最後,它會檢查rep是否大於(它永遠不會)或等於(它發生在第5個循環上),並在結束消息循環5次時打印結束消息。

+0

非常感謝你,這工作完美! – Francis

+0

不客氣! –

0

這裏是遞歸的正確方法。雖然這是尾遞歸,所以我將它打包成一個像@Prune這樣的循環。

def n(rep=0): 
    if n >= 5: 
     print ('You have guessed incorrectly 5 times.') 
    else: 
     name = input('What is the missing animal?') 
     if name == 'dog': 
      print('Well done') 
     else: 
      n(rep+1) 
相關問題