Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - What does "while False" mean?

I don't undestand how this code works:

i = 1
while False:
    if i % 5 == 0:
        break
    i = i + 2
print(i)

what does while False? What does it have to be false? I don't get it...

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

A while loop checks the condition (well, the expression) behind the while before each iteration and stops executing the loop body when the condition is False.

So while False means that the loop body will never execute. Everything inside the loop is "dead code". Python-3.x will go so far that it "optimizes" the while-loop away because of that:

def func():
    i = 1
    while False:
        if i % 5 == 0:
            break
        i = i + 2
    print(i)

import dis

dis.dis(func)

Gives the following:

  Line        Bytecode

  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (i)

  7           6 LOAD_GLOBAL              0 (print)
              9 LOAD_FAST                0 (i)
             12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             15 POP_TOP
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE

That means the compiled function won't even know there has been a while loop (no instructions for line 3-6!), because there is no way that the while-loop could be executed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...