Python Loop Else: runs when the loop did not break
The else block of a for loop runs when the loop ends without break. A break skips it. A break inside a while loop was not tested.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-76-A: for-else prints in the no-break case and stays silent after break
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
for n in [1, 2, 3]:
if n == 9:
break
else:
print('no break')
for n in [1, 2, 3]:
if n == 2:
break
else:
print('never printed')
print('end')
EOSCommand:
python3 s.pyRecorded output:
no break
endExit status: 0. The output matches the expected text written before the run.
TE-76-B: a while loop also has an else block, and it runs when the condition becomes false
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
n = 0
while n < 2:
n += 1
else:
print('while else')
print(n)
EOSCommand:
python3 s.pyRecorded output:
while else
2Exit status: 0. This status and the output match what was written before the run.
TE-76-C: expected non-zero exit: an uncaught error inside the loop ends the program, and the else block does not run
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
for n in [1]:
raise ValueError('x')
else:
print('else')
EOSCommand:
python3 s.pyRecorded output: none, standard output was empty.
Standard error from the same run:
Traceback (most recent call last):
File "/tmp/b21-wg336tii/work/s.py", line 2, in <module>
raise ValueError('x')
ValueError: xExit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.
TE-76-B: the while condition became false, so the else block printed while else. After the loop n is 2. TE-76-C: the ValueError was not caught. The else block did not run, nothing was printed to standard output, and the program ended with exit status 1 and ValueError: x on standard error.
Limits
TE-76-A runs for loops and TE-76-B runs one while loop. A break inside a while loop was not tested.
Source
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-76-A | for-else prints in the no-break case and stays silent after break | 0 | PASS | 45e76ecd840b | | TE-76-B | a while loop also has an else block, and it runs when the condition becomes false | 0 | PASS | 27481f7b19bf | | TE-76-C | expected non-zero exit: an uncaught error inside the loop ends the program, and the else block does not run | 1 | PASS | fd63c0a4cc8a |
Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides