Flow Control: while, pass, break, continue

From Master of Neuroscience Wiki
Revision as of 11:01, 15 October 2025 by Davrot (talk | contribs) (Created page with " == The goal == While we wait… Questions to [mailto:davrot@uni-bremen.de David Rotermund] '''Logic blocks need to be indented.​ Preferable with 4 spaces!''' == [https://docs.python.org/3/reference/compound_stmts.html#the-while-statement The while statement] == <syntaxhighlight lang="python">i = 0​ while i < 3:​ print(i)​ i += 1</syntaxhighlight>Output<syntaxhighlight lang="python">0​ 1​ 2</syntaxhighlight> == The full statement == <syntaxhighlig...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The goal

While we wait…

Questions to David Rotermund

Logic blocks need to be indented.​ Preferable with 4 spaces!

The while statement

i = 0
while i < 3:
    print(i)
    i += 1

Output

0
1
2

The full statement

while_stmt ::=  "while" assignment_expression ":" suite
                ["else" ":" suite]

pass

Since Python uses indents as definition for a functional block it needs pass for signaling an empty functional block.

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed

pass_stmt ::=  "pass"

break

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break, the loop control target keeps its current value.

break_stmt ::=  "break"
for i in range(0, 5):
    if i == 2:
        break
    print(i)

Output:

0
1

continue

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

continue_stmt ::=  "continue"
for i in range(0, 5):
    if i == 2:
        continue
    print(i)

Output:

0
1
3
4