Control Flow Statements


By HyperNeutrino
Written 19 days ago

There are five main control flow statements: break, continue, pass, raise, and return.

Break and Continue are used to interact with loops. Pass is used as a placeholder. Return is used to interact with functions.

break will cause the current loop to immediately exit. For example:

while True:
    if input() == "quit":
        break

This will loop forever; however, if the user inputs "quit", it will manually exit the otherwise infinite loop. This works the same for for loops.

continue will cause the current loop to jump back to the start, essentially skipping the rest of the code. For example:

for i in range(10):
    if i == 5:
        continue
    print(i)

This will output the numbers 0, 1, 2, 3, 4, 6, 7, 8, 9 on individual lines. It skips 5 because when i == 5, the if statement passes, which runs the continue statement, which returns to the top of the loop. Note that it skips forward, meaning that the value of i will advance forward if you continue the loop.

pass is the easiest one. It does nothing. It only exists because in Python, you can't have a loop with nothing inside of it because Python relies on indentation for the block syntax.

return exits a function immediately. You can also place a value following return (like this: return 4), which makes the function's output value equal to the value placed after it (for example, a = f() will set a to the return value of f).

raise causes an error manually. If outside of a except block, you have to specify an error; for example, raise ValueError("Invalid input!"). If inside an except block, you can just state raise, which will throw the error that was caught by the try-except block. This is useful if you want your code to perform some shutdown before erroring, and then raise the error anyway.