[Tutor] while x != 'n' or 'N' or 'l' or 'L':

D-Man dman@westsidecnc.rh.rit.edu
Wed, 6 Dec 2000 09:25:27 -0500 (EST)


Doug solved the problem correctly, however I feel that his solution is bad programming style and is harder to read than the alternative I will provide.

[snip]

> while 1:
>     if x in ('n','N','l','L'):
>         break
      # (some other processing snipped here)

When reading this code, it appears that the loop is supposed to be infinite.  I don't like loops like that.  Then the loop termination condition is buried in the body of the loop with a 'break' statement.  This is rather similar to using if's and goto's in BASIC or assembly to create a loop.  Try this instead:

while ( x not in ( 'n' , 'N' , 'l' , 'L' ) ) :
	# body of loop here


I prefer this because you can see the loop termination condition in the loop's "declaration".  (I also like parenthesis around the expression and spaces between symbols, but that is less important)

An alternative could be :

while ( string.upper( x ) not in ( 'N' , 'L' ) ) :
	# body of loop here

I have often used the "toupper" operation when writing C code so I don't need as many equality comparisons (C doesn't have then "x in (list)" construct).

Hope this helps,
-D

PS  The Computer Science department at my school has some coding guidelines that forbid the use of 'break' and 'continue'.  I had a class once where the professor was testing our understanding of C by writing similar loops  ex:

int i ;
for( i = 0 ; i < 16 ; i++ ) {
	if ( i % 5 ) {
		printf( "%d\n" , i ) ;
		continue ;
	}
	else if ( i > 8 ) {
		break ;
	}

	printf( "End of loop\n" ) ;
}


Needless to say, this is very confusing and easy to make a mistake when tracing through it.