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
1.4k views
in Technique[技术] by (71.8m points)

Why is this python while loop not ending?

I am wondering why this code seems to loop infinitely? The logic, while not False = while True, and this True is referring to 100 < 0 which is false, hence it should execute the print statement instead, right? Why is it stuck in the loop then..?

num = 100
while not False:
    if num < 0:
        break
print('num is: ' + str(num))
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

a while statement should be proceeded with a conditional. The conditional True (or in your cause not False) always evaluates to True so the loop never ends.

the if block is never executed because because num < 0 never evaluates to True. Did you mean to decrement num by 1 in each iteration of the while block? If so, add a num = num - 1 within the while block:

num = 100
while not False:
    if num < 0:
        break
    num = num - 1
print('num is: ' + str(num))

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

...