python run newspaper wrong with debug error position is not the same

Today a school brother asked me a question, asked why he wrote the code being given?
I probably looked at, I feel very easy error correction, not that sort of a simple thing, but still to run again.

def fun():
    before_li = [1, 5, 2, 21, 3, 6, 24, 12, 7, 11]
    after_li = []
    active = True
    while active:
        if before_li == []:
            active = False
        after_li.append(min(before_li))
        before_li.remove(min(before_li))
    print(after_li)
fun()

The results of running the wrong position makes me feel very strange (I think this is not only out of the end of the conditional logic error, the error message but why not end it?), I tried a little print output re-run again, get run the following error result:
Here Insert Picture Description
then I run several times and found the location of the error actually is not the same! ! ! (Here only put one picture, you can see for yourself)
Here Insert Picture Description
then I really can not stand with the debug (bebug Here is the code used)

def fun():
    before_li = [1, 5, 2, 21, 3, 6, 24, 12, 7, 11]
    after_li = []
    i = 0
    while True:
        if before_li == []:
            break
        print("第%d次"%i)
        print("min of before_li=%s"%min(before_li))
        after_li.append(min(before_li))
        before_li.remove(min(before_li))
        print("before_li: ", before_li)
        i+=1
    print(after_li)

fun()

The results are shown debug, finally, I thought being given and the results! It really is not a logical error in time to jump out of the end conditions.
Here Insert Picture Description
The following is the proper code:

def fun():
    before_li = [1, 5, 2, 21, 3, 6, 24, 12, 7, 11]
    after_li = []
    active = True
    i = 0
    while active:
        if before_li == []:
            # active = False
            break
    # for i in range(10):
        print("第%d次"%i)
        print("min of before_li=%s"%min(before_li))
        after_li.append(min(before_li))
        before_li.remove(min(before_li))
        print("before_li: ", before_li)
        i+=1
    print(after_li)

fun()

Finally, talk about, this article is not the point code, but throws a strange phenomenon, why run the error position is very consistent with normal logic, and also debug different? There are big brother passing can help answer!

Published 131 original articles · won praise 81 · views 60000 +

Guess you like

Origin blog.csdn.net/weixin_43469047/article/details/103357805