Note that there are some explanatory texts on larger screens.

plurals
  1. POwhile (1) Vs. for while(True) -- Why is there a difference?
    primarykey
    data
    text
    <p>Intrigued by this question about infinite loops in perl: <a href="https://stackoverflow.com/questions/885908/while-1-vs-for-is-there-a-speed-difference">while (1) Vs. for (;;) Is there a speed difference?</a>, I decided to run a similar comparison in python. I expected that the compiler would generate the same byte code for <code>while(True): pass</code> and <code>while(1): pass</code>, but this is actually not the case in python2.7.</p> <p>The following script:</p> <pre><code>import dis def while_one(): while 1: pass def while_true(): while True: pass print("while 1") print("----------------------------") dis.dis(while_one) print("while True") print("----------------------------") dis.dis(while_true) </code></pre> <p>produces the following results:</p> <pre><code>while 1 ---------------------------- 4 0 SETUP_LOOP 3 (to 6) 5 &gt;&gt; 3 JUMP_ABSOLUTE 3 &gt;&gt; 6 LOAD_CONST 0 (None) 9 RETURN_VALUE while True ---------------------------- 8 0 SETUP_LOOP 12 (to 15) &gt;&gt; 3 LOAD_GLOBAL 0 (True) 6 JUMP_IF_FALSE 4 (to 13) 9 POP_TOP 9 10 JUMP_ABSOLUTE 3 &gt;&gt; 13 POP_TOP 14 POP_BLOCK &gt;&gt; 15 LOAD_CONST 0 (None) 18 RETURN_VALUE </code></pre> <p>Using <code>while True</code> is noticeably more complicated. Why is this?</p> <p>In other contexts, python acts as though <code>True</code> equals 1:</p> <pre><code>&gt;&gt;&gt; True == 1 True &gt;&gt;&gt; True + True 2 </code></pre> <p>Why does <code>while</code> distinguish the two?</p> <p>I noticed that python3 does evaluate the statements using identical operations:</p> <pre><code>while 1 ---------------------------- 4 0 SETUP_LOOP 3 (to 6) 5 &gt;&gt; 3 JUMP_ABSOLUTE 3 &gt;&gt; 6 LOAD_CONST 0 (None) 9 RETURN_VALUE while True ---------------------------- 8 0 SETUP_LOOP 3 (to 6) 9 &gt;&gt; 3 JUMP_ABSOLUTE 3 &gt;&gt; 6 LOAD_CONST 0 (None) 9 RETURN_VALUE </code></pre> <p>Is there a change in python3 to the way booleans are evaluated?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload