簡體   English   中英

為什么while循環在if循環中不起作用?

[英]Why is the while loop not working in the if loop?

    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次。

有任何想法嗎?

多么尷尬的遞歸。 :)

問題在於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')

抱歉縮進。

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.')

因為您知道要循環幾次,所以for (也許)更合適。 for循環的else子句可以處理您沒有得到正確答案的情況。

您一直在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次,則打印結束消息。

這是遞歸的正確方法。 盡管這是遞歸的尾部,但我自己將其展開為類似@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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM