为什么while循环在if循环中不起作用?
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循环中不起作用?
任何想法?
什么是一个尴尬的递归。 :)
问题是,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')
对不起缩进。
您应该在函数定义之外初始化您的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
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.')
既然你知道你想要多少次都要经过环,为是(也许)更合适。 其他子句为为循环处理的情况下,你完成没有得到正确的答案。
您一直在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次时打印结束消息。
非常感谢你,这工作完美! – Francis
不客气! –
这里是递归的正确方法。虽然这是尾递归,所以我将它打包成一个像@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)
递归调用从0开始。您永远不会进入while循环的第二次迭代。 – Prune
'if'不是一个循环;这是一个分支语句。 – chepner