Python Control Flows

Control flows in Python defines the order that the computer executes statements, instructions or function calls in a script.

They are used to write more complex and dynamic programs to answer different situations in different ways.

The control flow in Python is defined by the conditional statements, the loops and the function calls.

Join the Newsletter

    • if/elif/else statements
    • for loops statements
    • while loops statement
    • break and continue statements
    • pass statement
    • try/except statements
    • match statement

    if/elif/else Statements

    The if, elif and else keywords are used to apply conditions for the Python code execution.

    (If condition, do something, else do something else.)

    if condition:
        # Do something if condition is true
    else:
        # Do something else if condition is false
    

    If Statement

    The if statement is the statement that starts the control flow and defines the condition to be tested on.

    The if statement can be used by itself.

    # If statement
    if True:
        print('This is True')
    
    This is True
    

    Else Statement

    The else statement is the optional control flow statement that defines the code to be executed when the prior condition(s) is not met.

    # If/Else Statement
    i = 1
    if i > 10:
        print('i is greater than 10')
    else:
        print('i is smaller than 10')
    
    i is smaller than 10
    

    Elif Statement

    The elif statement is the optional control flow statement that defines additional conditions to be evaluated and the code to be executed in the conditional statement.

    # Simple Elif Example
    i = 12
    if i < 2:
        print('i is less than 2')
    elif i > 10:
        print('i is greater than 10')
    else:
        print('i is a number between 2 and 10')
    
    i is greater than 10
    

    For Loops Statements

    The for loops are control flow statements used to iterate over a sequence (e.g. list, tuple, string) and execute code for each item.

    for item in sequence:
        # Do Something
    

    Example of a for loop in Python.

    # Simple for loop
    for i in [1,2,3]:
        print(i)
    
    1
    2
    3
    

    While Loops Statements

    The while loops are control flow statements are used to execute code as long as a given condition is True.

    Similar to a if else block that would be repeated over and over.

    while condition:
        # do something
    

    Example of a while loop in Python.

    # Simple while loop
    while True:
        print('hello')
        break
    
    hello
    

    Above the break statement stops the loop to prevent an infinite loop caused by the while True statement.

    break and continue Statements

    The break and continue keywords define control flow statements to either stop a loop early or skip to the next iteration:

    • The break statement is used to stop a loop early.
    • The continue statement is used to skip to the next iteration of the loop.
    # Break and continue example
    letters = ['a', 'b', 'c', 'd', 'e', 'f']
    
    for letter in letters:
        if letter == 'e':
            # if the letter is "e", stop the loop
            break
        elif letter == 'c':
            # if the letter is "c", skip to the next iteration
            continue
        print(letter)
    
    a
    b
    d

    pass statement

    The pass control flow statement is a null operation that is used as a placeholder when the code should do nothing.

    The pass keyword is often used to list the functions to be created in the code, but not yet ready to be worked on.

    # Example pass
    def a_func():
        pass
    

    try/except Statements

    The try/except control flow statements are used to handle errors (exceptions).

    • The try block contains the code that may return an exception.
    • The except block contains the code to execute if there is an exception.

    It has the following structure:

    try:
        # code that may break
    except:
        # code to execute if it breaks
    

    Handling exceptions with Try and Except

    # Example Try and Except
    try:
        1 / 0
    except:
        print("You can't divide by zero") 
    
    You can't divide by zero

    match Statement

    The match keyword define the control flow statement used perform pattern matching for code execution.

    If a pattern match the expression, code is executed.

    # Example match statement
    def http_error(status):
        match status:
            case 400:
                return "Bad request"
            case 404:
                return "Not found"
            case 418:
                return "I'm a teapot"
            case _:
                return "This code was not matched"
            
    print('404:', http_error(404))
    print('1000:', http_error(1000))  
    
    404: Not found
    1000: This code was not matched

    Conclusion

    We have now learned about the various control flow statements in Python.

    Enjoyed This Post?