KKAIROS
Practical guideIllustrative3 min read

Python if, for and while: the basics

if branches on a condition, for iterates any iterable, while repeats while a condition holds. Tested here: for works over any iterable, not only sequences.

Published:

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-38-A: for works over any iterable, not only sequences

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'def g():\n    yield 1\n    yield 2\nfor v in g():\n    print(v)\nfor i, c in enumerate("ab"):\n    print(i, c)\n' > s.py

Command:

python3 s.py

Recorded output:

1
2
0 a
1 b

TE-38-B: an if inside a for loop keeps only the odd numbers, and a while loop counts up to its limit

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
for i in range(5):
    if i % 2:
        print(i)
n = 0
while n < 3:
    n += 1
print(n)
EOS

Command:

python3 s.py

Recorded output:

1
3
3

Exit status: 0. This status and the output match what was written before the run.

TE-38-C: expected non-zero exit: an if without an indented block is a syntax error and nothing runs

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
print('before')
if True:
print('inside')
EOS

Command:

python3 s.py

Recorded output: none, standard output was empty.

Standard error from the same run:

File "/tmp/b14-hkso_fce/work/s.py", line 3
    print('inside')
    ^
IndentationError: expected an indented block after 'if' statement on line 2

Exit 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-38-B: the if inside the for loop printed 1 and 3, the odd numbers below 5. The while loop stopped when n reached 3, and print(n) printed 3. TE-38-C: the file has an if line with no indented block under it. Python stopped with exit status 1 and before was not printed. Standard error ends with IndentationError: expected an indented block after 'if' statement on line 2.

Limits

Covers iteration over a generator and a string; else clauses and break are outside this page.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-38-A | for works over any iterable, not only sequences | 0 | PASS | 9dce1bf0daef | | TE-38-B | an if inside a for loop keeps only the odd numbers, and a while loop counts up to its limit | 0 | PASS | 1716b9a87a47 | | TE-38-C | expected non-zero exit: an if without an indented block is a syntax error and nothing runs | 1 | PASS | b834b4391304 |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides