left-icon

Python Succinctly®
by Jason Cannon

Previous
Chapter

of
A
A
A

CHAPTER 3

Booleans and Conditionals

Booleans and Conditionals


A Boolean is a specific data type that is only capable of having one of two possible values: True or False. Another way to think of a Boolean is to consider it either on or off. To assign a Boolean to a variable use variable_name = boolean, where boolean is either True or False. Do not use quotes around True or False. Remember, quotes should only be used for strings.

Code Listing 97

the_true_boolean = True

the_other_boolean = False

print(the_true_boolean)

print(the_other_boolean)

Output:

Code Listing 98

True

False

Comparators

The following chart lists six operators that compare one numeric value with another and will result in a Boolean.

Table 2: Comparison Operators

Operator

Description

==

Equal to

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

!=

Not equal

When you see 1 == 2 you can think "Is 1 equal to 2?" If the answer is yes, then it is True. If the answer is no, then it is False. In the following example the answer is no, so the condition will be False. Note that while = assigns a value to a variable, == performs a comparison.

Code Listing 99

is_two_equal_to_three = 2 == 3

print(is_two_equal_to_three)

Output:

Code Listing 100

False

Let's try running the numbers 1 and 2 through all six comparators interactively within the Python interpreter.

Code Listing 101

>>> 1 == 2

False

>>> 1 > 2

False

>>> 1 >= 2

False

>>> 1 < 2

True

>>> 1 <= 2

True

>>> 1 != 2

True

Boolean Operators

Keep in mind that Boolean logic is used extensively in the field of computer programming. There are only three Boolean operators: and, or, and not. Each one of them can be used to compare two conditions or negate a condition. Like comparators, they will result in a Boolean.

Table 3: Boolean Logic Operators

Operator

Description

and

Evaluates to True if both statements are true. Otherwise evaluates to False.

or

Evaluates to True if either of the statements is true. Otherwise evaluates to False.

not

Evaluates to the opposite of the statement.

The following is a truth table that clearly explains Boolean operators and their outcomes.

Code Listing 102

True and True is True

True and False is False

False and True is False

False and False is False

True or True is True

True or False is True

False or True is True

False or False is False

Not True is False

Not False is True

Let's take a moment and evaluate two statements using the Boolean and operator. The first statement is 43 > 29 and it evaluates to True. The second statement is 43 < 44 and it also evaluates to True. 43 > 29 and 43 < 44 evaluates to True because True and True evaluates to True.

Code Listing 103

>>> 43 > 29

True

>>> 43 < 44

True

>>> 43 > 29 and 43 < 44

True

>>>

What is the result of 43 > 29 or 43 < 44?

Code Listing 104

>>> 43 > 29 or 43 < 44

True

The not Boolean operator will evaluate to the reverse of the statement. Since 43 > 29 is True, not 43 > 29 is False.

Code Listing 105

>>> 43 > 29

True

>>> not 43 > 29

False

The order of operations for Boolean operators is:

not

and

or

Just as an example, True and False or not False is True. First, not False is assessed and is True. Next, True and False is calculated and is False. Finally, True or False is evaluated and is True.

Code Listing 106

>>> not False

True

>>> True and False

False

>>> True or False

True

>>> True and False or not False

True

To control the order of operations, use parentheses. Anything surrounded by parentheses will be evaluated first and as its own independent unit. True and False or not False is the same as (True and False) or (not False). It's also the same as ((True and False) or (not False)). Using parentheses will allow you to avoid memorizing the order of operations, and more importantly ensure that your intentions are explicit and clear.

Conditionals

The if statement will evaluate a Boolean expression and if it is True the code associated with it will be executed. Let's look at the following example to see this demonstrated.

Code Listing 107

if 43 < 44:

    print('Forty-three is less than forty-four.')

Output:

Code Listing 108

Forty-three is less than forty-four.

Because the Boolean expression 43 < 44 is True, the code indented under the if statement will be executed. This indented code is referred to as a code block. Any statements that are the same distance to the right will also belong to that code block. A code block can contain one or more lines, and its ending will be marked by a line that is less indented than the current code block. Also, keep in mind that code blocks can be nested. The following code listing is a logical view of code blocks.

Code Listing 109

Block One

    Block Two

    Block Two

        Block Three

Block One

Block One

In most cases code blocks are indented using four spaces, but this occurs more out of sense of convention and is not strictly enforced. Python will allow you to use other levels of indentation within your programs. For example, while using four spaces is the most popular option for indentation, using two spaces is the next most popular choice. It is important however that whichever you choose you use it consistently. If you make the decision to use two spaces for indentation, then continue to use two spaces throughout the entire program. When in doubt though, it is always best to follow established conventions unless you have a particular reason not to do so. Also, if you encounter the following error, it means you have a problem within your spacing.

Code Listing 110

IndentationError: expected an indented block

Now let's get back to the if statement. Notice that the line containing the if statement will always end with a colon.

Code Listing 111

age = 32

if age >= 35:

    print('You are old enough to be the President.')

print('Have a nice day!')

Output:

Code Listing 112

Have a nice day!

In this example, since age >= 35 is False, the Python code indented underneath the if statement was not executed. The final print function will always execute because it exists outside of the if statement. Notice that it is not indented.

The if statement can also be paired with else. The code indented under else will execute in instances where the if statement is false. Try to think of the if/else statement as meaning, "If the statement is true, run the code underneath if. Otherwise run the code underneath else."

Code Listing 113

age = 32

if age >= 35:

    print('You are old enough to be the President.')

else:

    print('You are not old enough to be the President.')

print('Have a nice day!')

Output:

Code Listing 114

You are not old enough to be the President.

Have a nice day!

You can also evaluate multiple conditions by using elif, which is short for "else if." Such as in the case of if and else, you want to end the line of the elif statement with a colon, as well as indent the code to execute underneath it.

Code Listing 115

age = 32

if age >= 35:

    print('You are old enough to be a Senator or the President.')

elif age >= 30:

    print('You are old enough to be a Senator.')

else:

    print('You are not old enough to be a Senator or the President.')

print('Have a nice day!')

Output:

Code Listing 116

You are old enough to be a Senator.

Have a nice day!

In this instance, since age >= 35 is False, the code underneath the if statement was not executed. Since age >= 30 is True, the code underneath elif did execute. The code under else will only execute in instances where all of the preceding if and elif statements evaluate to False. Also, the first if or elif statement to evaluate to True will execute, with any remaining elif or else blocks not executing. The following listing is a final example to illustrate the points explained previously.

Code Listing 117

age = 103

if age >= 35:

    print('You are old enough to be a Representative, Senator, or the President.')

elif age >= 30:

    print('You are old enough to be a Senator.')

elif age >= 25:

    print('You are old enough to be a Representative.')

else:

    print('You are not old enough to be a Representative, Senator, or the President.')

print('Have a nice day!')

Output:

Code Listing 118

You are old enough to be a Representative, Senator, or the President.

Have a nice day!

Review

Booleans are always either True or False.

Comparators contrast one numeric value with another and will result in a Boolean.

Boolean operators (and, or, not) either compare or negate two conditions and will result in a Boolean.

Parentheses can be utilized to control the order of operations.

A code block is marked by a section of code at the same level of indentation.

Conditional keywords include if, if/else, and if/elif/else.

Exercises

Walk, Drive, or Fly

Try creating a program that will ask the user how far they wish to travel. If they express a desire to travel less than three miles, have the program tell them to walk. If they desire to travel more than three miles, but less than three hundred miles, advise them that they should drive. In any instance where they want to travel three hundred or more miles, tell them to fly.

Sample Output:

Code Listing 119

What distance are you traveling in miles? 3125

I suggest flying to your destination.

Solution

Code Listing 120

# Ask for the distance.

distance = input(' What distance are you traveling in miles? ')

# Convert the distance into an integer.

distance = int(distance)

# Determine what transportation to use.

if distance < 3:

    transportation = 'walking'

elif distance < 300:

    transportation = 'driving'

else:

    transportation = 'flying'

# Display the result.

print('I suggest {} to your destination.'.format(transportation))

Resources

Built-in Types: https://docs.python.org/3/library/stdtypes.html

Order of Operations (PEMDAS): http://www.purplemath.com/modules/orderops.htm

Style Guide for Python Code (PEP 8): http://legacy.python.org/dev/peps/pep-0008/

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.