Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Python - break statement not working in else statement within while loop

The while loop in my code refuses to terminate when I use the break statement, and I'm really confused why this is happening.

point = 0
while point < len(list_of_line_lists) - 1:
    sentence = list_of_line_lists[point]["text"]
    datapoint = point
    while True:
        try:
            if list_of_line_lists[datapoint]["author"] == list_of_line_lists[datapoint + 1]["author"]:
                sentence += list_of_line_lists[datapoint + 1]["text"]
                datapoint += 1
                print(datapoint)
            else:
                print("this isn't breaking")
                break
        except IndexError:
            break

In my code above, the break statement within the else statement refuses to trigger. The code within it is executed, as there's a flurry of "this isn't breaking" in the output, but the loop itself doesn't terminate. This is how my output looks(until I manually stop it myself):

this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking

Any ideas to why this is happening?

question from:https://stackoverflow.com/questions/65648715/python-break-statement-not-working-in-else-statement-within-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The inner loop is breaking, but the outer loop isn't. The reason is because you are using the point variable in the outer while loop, but that (point) variable value is never changed (incremented/decremented).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...