当我运行代码时,python只是坐在那里不打印任何东西

2024-10-02 18:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: ofthetofromnumberwhichstringback
3条回答

函数中的while循环计算bool值[-1]<;=100。既然这是真的,它就不会打破循环。你知道吗

您已经创建了一个无限while循环。while循环的条件是:

while values[-i] <= 100:

为了让这个循环到达每一端,最终values[-i] <= 100需要计算到False。但是,在您的例子中,i永远不会有机会改变,因为while循环需要完成for循环才能继续。为了更清楚地说明发生了什么,请注意以下几点:

In [8]: for i in ['a', 'b', 'c']:
   ...:     print(i)
   ...:     j = 0
   ...:     while j < 5:
   ...:         print(j)
   ...:         j += 1

a
0
1
2
3
4
b
0
1
2
3
4
c
0
1
2
3
4

换句话说,for循环到达值'a',然后while循环完成0-4,然后外部for循环到达'b',依此类推。为了你,我不想帮你解决家庭作业。不过,我要说的是,对于您当前的代码,您需要找到一种方法,使您的while条件最终False,而不依赖于外部for循环生成的值的更改。你知道吗

线路

        while values[-i] <= 100:

只要values[i]小于或等于100,就会导致函数循环。由于while块中的任何内容都不会更改values[i],因此如果完全进入循环,它将永远不会终止。你知道吗

您的函数还有其他问题,这意味着它不能正常工作,但首先,您可以尝试将该行更改为

        while total <= 100:

。。。它至少有终止的机会,因为totalwhile块内被改变。你知道吗

相关问题 更多 >