Python Control Flow

PythonBeginner
Practice Now

Introduction

Control flow is the order in which individual statements, instructions, or function calls are executed or evaluated. The control flow of a Python program is regulated by conditional statements, loops, and function calls.

In this lab, you will learn the core concepts of controlling program execution in Python. You will explore conditional logic using if statements, various operators, the new match-case statement, and iteration using while and for loops. By the end of this lab, you will be able to write more dynamic and powerful Python programs.

Comparison and Boolean Operators

In this step, you will learn how to use comparison and boolean operators to form logical expressions. These expressions are fundamental to control flow as they evaluate to either True or False, which then determines how the program proceeds.

Comparison Operators

Comparison operators are used to compare two values. Here is a table of common comparison operators:

Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater Than
<= Less than or Equal to
>= Greater than or Equal to

These operators evaluate to True or False. For example, 42 == 42 is True, but 42 == '42' is False because the types (integer and string) are different.

Boolean Operators

There are three Boolean operators: and, or, and not. They are used to combine or invert boolean values. Their order of precedence is not, and, then or.

The and operator returns True only if both expressions are true. The or operator returns True if at least one of the expressions is true. The not operator inverts the boolean value (not True becomes False).

Mixing Operators

You can combine comparison and boolean operators to create more complex logical expressions.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

For example:

(4 < 5) and (5 < 6)

Output:

True

Now, let's practice this. Open the operators_example.py file from the file explorer on the left. Add the following code to the file. This code combines multiple operators to evaluate a single boolean result.

## operators_example.py
result = 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
print(result)

To run the script, open a terminal in the WebIDE and execute the following command:

python3 operators_example.py

You should see the following output, as the expression evaluates to True:

True

If Statements and Ternary Operator

In this step, you will learn to control program flow with if, elif, and else statements to execute code blocks based on specific conditions. This step also introduces the ternary conditional operator for writing concise one-line conditional expressions.

The if, elif, and else Statements

  • The if statement executes a block of code if its condition is True.
  • The elif (else if) statement checks another condition if the preceding if or elif conditions were False.
  • The else statement executes a block of code if all preceding if and elif conditions were False.

Here is the basic structure:

if condition1:
    ## code to execute if condition1 is True
elif condition2:
    ## code to execute if condition1 is False and condition2 is True
else:
    ## code to execute if all conditions are False

Ternary Conditional Operator

The ternary operator provides a shorthand way to write simple if-else statements in a single line. Its syntax is:

<expression1> if <condition> else <expression2>

For example, print('kid' if age < 18 else 'adult') is a compact way of writing a full if-else block.

Now, let's practice using a full conditional block. Open the if_example.py file and add the following code. This script will check the value of the name variable and print a different message accordingly.

## if_example.py
name = 'Antony'

if name == 'Debora':
   print('Hi Debora!')
elif name == 'George':
   print('Hi George!')
else:
   print('Who are you?')

Run the script from the terminal:

python3 if_example.py

Since the name is 'Antony', neither the if nor the elif condition is met, so the else block is executed.

Output:

Who are you?

Switch Case Statement

In this step, you will explore Structural Pattern Matching, Python's powerful switch-case equivalent introduced in Python 3.10. You will practice matching values, using OR patterns, and implementing default cases with the match and case keywords.

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks.

Basic Matching

You can match against literal values like numbers or strings.

OR Patterns

You can combine several literal patterns in a single case using the | (or) operator. For example, case 200 | 201:.

Default Case

The underscore symbol (_) is a wildcard and is used to define a default case that will match if no other case has matched.

Let's practice this. Open the match_example.py file and add the following code. This script uses a match statement to determine an action based on an HTTP response code.

## match_example.py
response_code = 800

match response_code:
    case 200 | 201:
        print("OK")
    case 300 | 307:
        print("Redirect")
    case 400 | 401:
        print("Bad Request")
    case 500 | 502:
        print("Internal Server Error")
    case _:
        print("Invalid Code")

Run the script from your terminal:

python3 match_example.py

Since response_code is 800, it doesn't match any of the specific cases, so the default case (_) is executed.

Output:

Invalid Code

While Loops and Loop Control

In this step, you will master the while loop for repeated execution as long as a condition is true. You will also learn to manage loop behavior using the break statement to exit the loop and the continue statement to skip the current iteration.

The while Loop

A while loop repeatedly executes a target statement as long as a given condition is True. It's crucial to ensure the condition eventually becomes False to avoid an infinite loop.

The break Statement

The break statement terminates the current loop and resumes execution at the next statement, just like the traditional break in C.

The continue Statement

The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

Let's create a simple while loop. Open the while_example.py file and add the following code. This script will print a message five times.

## while_example.py
spam = 0
while spam < 5:  ## Continue while spam is less than 5
    print('Hello, world.')
    spam = spam + 1  ## Increment counter to avoid infinite loop

Now, run the script from the terminal:

python3 while_example.py

The loop will execute as long as spam is less than 5. In each iteration, spam is incremented by 1.

Output:

Hello, world.
Hello, world.
Hello, world.
Hello, world.
Hello, world.

For Loops and Iteration

In this step, you will use the for loop to iterate over items in a sequence like a list or string. This step covers using the range() function to loop a specific number of times, the optional else block in a for loop, and how to terminate a program entirely with sys.exit().

The for Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

The range() Function

The range() function generates a sequence of numbers, which is useful for looping a specific number of times.

  • range(stop): Generates numbers from 0 up to (but not including) stop.
  • range(start, stop): Generates numbers from start up to stop.
  • range(start, stop, step): Generates numbers from start up to stop, incrementing by step.

Ending a Program with sys.exit()

The sys.exit() function can be called to terminate the program immediately. You must first import sys to use it.

Let's practice using a for loop with range(). Open the for_example.py file and add the following code. This script will print even numbers from 0 to 8.

## for_example.py
## range(start, stop, step)
for i in range(0, 10, 2):
   print(i)

Run the script from the terminal:

python3 for_example.py

The range(0, 10, 2) function generates numbers starting at 0, up to (but not including) 10, with a step of 2.

Output:

0
2
4
6
8

Summary

Congratulations on completing the lab! You have now mastered the fundamental concepts of control flow in Python.

In this lab:

  • You learned how to use comparison and boolean operators to form logical conditions.
  • You practiced controlling program execution with if, elif, and else statements, as well as the concise ternary operator.
  • You explored Python 3.10's powerful match-case statement for structural pattern matching.
  • You learned to create loops with while and for, and control their behavior using break and continue.

With these skills, you can now write more complex and intelligent Python programs that can make decisions and repeat tasks.