Sep-11-2018, 06:24 PM
REF: The Python Tutorial, 4.4. break and continue Statements, and else Clauses on Loops, 1st example code.
The example looks straight forward (no pun intended) until you insert code between the inner 'for' and 'if'.
To watch the variable values during execution, I added the debugging line:
print('n=' + str(n) + ', x=' + str(x))'
Where's the output from, "print('n=' + str(n) + ', x=' + str(x)) ", before "2 is a prime number" ?!?!
Change the start value of 'for n in range(2,10)'
to a non-prime, i.e. 'for n in range(4,10)'
and now the 'print' line before the 'if' test works as expected.
The line to display the variable values should execute before the 'if' test in every iteration of the loop.
This illogical behavior ONLY occurs the very first time through the inner loop. Each successive time, the code executes as expected.
Never seen a 'for' loop behave like this in any other language. Is the 'else' clause somehow to blame?
The example looks straight forward (no pun intended) until you insert code between the inner 'for' and 'if'.
To watch the variable values during execution, I added the debugging line:
print('n=' + str(n) + ', x=' + str(x))'
for n in range(2, 10): for x in range(2, n): print('n=' + str(n) + ', x=' + str(x)) if n % x == 0: print(n, 'equals', x, '*', n//x) break else: # loop fell through without finding a factor print(n, 'is a prime number')
Where's the output from, "print('n=' + str(n) + ', x=' + str(x)) ", before "2 is a prime number" ?!?!
Change the start value of 'for n in range(2,10)'
to a non-prime, i.e. 'for n in range(4,10)'
and now the 'print' line before the 'if' test works as expected.
The line to display the variable values should execute before the 'if' test in every iteration of the loop.
This illogical behavior ONLY occurs the very first time through the inner loop. Each successive time, the code executes as expected.
Never seen a 'for' loop behave like this in any other language. Is the 'else' clause somehow to blame?