Practice with Relational and Logical Operators

Try these exercises for more practice with relational and logical operators.

5. Using Boolean Operators for Flow Control

To control the stream and outcomes of a program in the form of flow control statements, we can use a condition followed by a clause.

condition evaluates down to a Boolean value of True or False, presenting a point where a decision is made in the program. That is, a condition would tell us if something evaluates to True or False.

The clause is the block of code that follows the condition and dictates the outcome of the program. That is, it is the do this part of the construction “If x is True, then do this.”

The code block below shows an example of comparison operators working in tandem with conditional statements to control the flow of a Python program:

if grade >= 65:                 # Condition
    print("Passing grade")      # Clause

else:
    print("Failing grade")

This program will evaluate whether each student’s grade is passing or failing. In the case of a student with a grade of 83, the first statement will evaluate to True, and the print statement of Passing grade will be triggered. In the case of a student with a grade of 59, the first statement will evaluate to False, so the program will move on to execute the print statement tied to the else expression: Failing grade.

Because every single object in Python can be evaluated to True or False, the PEP 8 Style Guide recommends against comparing a value to True or False because it is less readable and will frequently return an unexpected Boolean. That is, you should avoid using if sammy == True: in your programs. Instead, compare sammy to another non-Boolean value that will return a Boolean.

Boolean operators present conditions that can be used to decide the eventual outcome of a program through flow control statements.