On 8/8/2013 7:41 AM, Chris Angelico wrote:
On Thu, Aug 8, 2013 at 7:20 AM, <wxjmfa...@gmail.com> wrote:
def z2():
... letters = 'abc'
... while True:
... c = input('letter: ')
... if c not in letters:
... print('end, fin, Schluss')
... break
... else:
... print('do stuff')
Minor quibble: I don't like having a hard exit followed by an "else".
Whereas I tend to prefer to have the two alternatives cleanly marked as
alternatives by both being indented the same.
Many alternatives are not so trivial as the above. I remember reading
one snippet in the CPython codebase where the 'else' was omitted and the
if clause subdivided into about three paths. It took at least a minute
to determine that all paths terminated in such a way that there really
was an inplied else. How much easier it would have been to read the code
if the author had explicitly types the 'else'.
If the "if" branch will unconditionally quit the loop (with a break,
here, but could also be a return, a thrown exception, etc etc), I
would prefer to see the "else" removed and its code unindented one
level. Maybe this is just personal preference, though, learned from
assembly language programming where a "block if" looks something like
this:
; if x == y:
CMP x,y
JNZ .else
; Code for "x == y"
JMP .endif
.else:
; Code for "else"
.endif
Putting an unconditional departure in the "x == y" branch makes the
"JMP .endif" redundant.
Python is not assembly ;-). 3.3 effectively ignores the extraneous
'else:'. Either way, if the condition is false, control jumps to the
second print. For what little it matters, the bytecode is the same length.
def f():
while True:
if a:
b = 1
break
else:
b = 2
>>> dis(f)
2 0 SETUP_LOOP 25 (to 28)
3 >> 3 LOAD_GLOBAL 0 (a)
6 POP_JUMP_IF_FALSE 19
4 9 LOAD_CONST 1 (1)
12 STORE_FAST 0 (b)
5 15 BREAK_LOOP
16 JUMP_ABSOLUTE 3
7 >> 19 LOAD_CONST 2 (2)
22 STORE_FAST 0 (b)
25 JUMP_ABSOLUTE 3
>> 28 LOAD_CONST 0 (None)
31 RETURN_VALUE
def f():
while True:
if a:
b = 1
break
b = 2
>>> dis(f)
2 0 SETUP_LOOP 25 (to 28)
3 >> 3 LOAD_GLOBAL 0 (a)
6 POP_JUMP_IF_FALSE 19
4 9 LOAD_CONST 1 (1)
12 STORE_FAST 0 (b)
5 15 BREAK_LOOP
16 JUMP_FORWARD 0 (to 19)
6 >> 19 LOAD_CONST 2 (2)
22 STORE_FAST 0 (b)
25 JUMP_ABSOLUTE 3
>> 28 LOAD_CONST 0 (None)
31 RETURN_VALUE
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list