Exercise: Starting from the back of the string find all the numbers which could possibly lead to a number which is greater than or equal to 100, then stop and find the average of the number before that.
def avgBackwList(values):
total = 0
for i in range(1,len(values)+1):
while values[-i] <= 100:
total = total + int(values[-i])
return (total/i)
values = [110,2,4]
print(avgBackwList(values))
函数中的while循环计算bool值[-1]<;=100。既然这是真的,它就不会打破循环。你知道吗
您已经创建了一个无限
while
循环。while循环的条件是:为了让这个循环到达每一端,最终
values[-i] <= 100
需要计算到False
。但是,在您的例子中,i
永远不会有机会改变,因为while
循环需要完成for
循环才能继续。为了更清楚地说明发生了什么,请注意以下几点:换句话说,for循环到达值
'a'
,然后while循环完成0-4,然后外部for循环到达'b'
,依此类推。为了你,我不想帮你解决家庭作业。不过,我要说的是,对于您当前的代码,您需要找到一种方法,使您的while
条件最终False
,而不依赖于外部for循环生成的值的更改。你知道吗线路
只要
values[i]
小于或等于100,就会导致函数循环。由于while
块中的任何内容都不会更改values[i]
,因此如果完全进入循环,它将永远不会终止。你知道吗您的函数还有其他问题,这意味着它不能正常工作,但首先,您可以尝试将该行更改为
。。。它至少有终止的机会,因为
total
在while
块内被改变。你知道吗相关问题 更多 >
编程相关推荐