What does “while False” mean?

后端 未结 3 1540
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 17:31

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 Fa

相关标签:
3条回答
  • 2020-12-18 18:21
    while True:
    

    means that it will loop forever.

    while False:
    

    means it won't execute.

    0 讨论(0)
  • 2020-12-18 18:31

    it is saying if something is not true do this. for example:

    while (0 == 1) == False: # this statement is true because 0 does not equal 1
         print('hi') # this will create a infinite loop of hi.
    

    meanwhile.

    while (0 == 0) == False: # this statement is false since 0 does equal 0.
         print('hi') # this will do nothing since the past statement is false.
    
    0 讨论(0)
  • 2020-12-18 18:34

    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.

    0 讨论(0)
提交回复
热议问题