为什么while循环在if循环中不起作用?

时间:2015-10-20 21:30:14

标签: python

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

有什么想法吗?

4 个答案:

答案 0 :(得分: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')

抱歉缩进。

答案 1 :(得分: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.')

由于您知道要循环多少次, (或许)更合适。 for 循环的 else 子句处理完成但没有得到正确答案的情况。

答案 2 :(得分: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次则打印结束消息。

答案 3 :(得分: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)