Boolean values and flow control statements (if, else, elif) - Python
Baha Abu-Shaqra, PhD (DTI uOttawa)
Digital Transformation and Innovation (EBT/EBC) | Academic Bullying at uOttawa Researcher
In this post we look at the Python concepts of Boolean values, comparison operators, Boolean operators, and flow control statements (if, else, elif). This post is part three of a nine-part series covering necessary background for the Cisco DevNet and ENAUTO streams certifications.
You may also be interested in Pre-DevNet (Python, Linux, Bash).
Before we dive in, I try to make the world a little better. You're invited to read my letter to uOttawa President?Jacques Frémont about how to easily implement policy reforms to prevent supervisor bullying of uOttawa students: uOttawa President Jacques Frémont ignores university bullying problem. You may also be interested in How to end supervisor bullying at uOttawa.
Introduction
A flow chart represents the execution in Python code. The execution can follow different paths depending on different conditions. We start at the start box and follow the arrows to the other boxes until finally we get to the end box.
Flow control statements are Python instructions that determine which instructions to execute under which conditions. Based on how expressions evaluate, a program can skip instructions, repeat them, or choose one of several instructions to run.
Boolean values, comparison operators, and Boolean operators
First let's look at how to represent the yes and no options in a Python flowchart. This involves three things:
1) Boolean values
2) Comparison operators
3) Boolean operators
1) Boolean values: the Boolean data type has only two values, True and False. Integers and strings have an infinite number of different values.
Like any other value, Boolean values can be used in expressions and can be stored in variables.
Using expressions that evaluate to True or False (also called conditions) allows us to write programs that make decisions on what code to execute and what code to skip.
2) Comparison operators: used in expressions like any other operator. There are six comparison operators (operators and their meaning):
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Expressions with comparison operators evaluate to a Boolean value. Let's experiment in the interactive shell.
3) Boolean operators: there are three Boolean operators: and, or, and not.
The and operator evaluates an expression to True if both Boolean values are True; otherwise it evaluates to False.
Let's experiment with the and Boolean operator in the interactive shell.
>>> True and True
True
>>> True and False
False
The or operator evaluates an expression to True if either of the two Boolean values is True. If both Boolean values are False, an expression evaluates to False.
The not operator is a unary operator that operates on only one Boolean value or expression (True or False). The not operator simply evaluates to the opposite Boolean value.
Boolean operators and comparison operators are often mixed together in the same expression.
>>> myAge = 35
>>> myPet = 'lion'
>>> myAge > 25 and myPet == 'lion'
True
Flow control statements (if, else, elif)
The diamonds in the flowchart (What should one do if it is raining?) represent the flow control statements, and they are the actual decisions a program will make.
if statements
If the if statement's condition is True, Python will execute the code in the clause (the block following the if statement). If the statement's condition is False, the clause is skipped. In Python, an if statement consists of the following:
The indentation tells Python which part of the code is inside the if statement block. The standard for indentation in Python is four spaces for each block of code. If the condition in the if statement evaluates to True, the execution enters the indented code that follows. If the condition evaluates to False, the execution skips the indented code.
For example, let’s say you have some code that checks to see whether someone’s name is Goofy. Open a new script file and enter the following code.
name = 'Goofy'
if name == 'Goofy':
… print('Hi Goofy')
print('Lol')
When you run the above code, it prints out the following lines because the condition in the if statement evaluates to True.
Hi Goofy
Lol
Had the assigned value to the name variable been 'Hen' instead of 'Goofy', only Lol would be printed. (See Figure 2-2: The flowchart for an if statement in Automate the Boring Stuff with Python by Al Sweigart.)
else statements
An if clause can be followed by an else statement. The else clause is executed only when the if statement’s condition is False. An else statement consists of the following:
Returning to our Goofy example, let’s look at some code that uses an else statement to offer a different greeting if the person’s name is not Goofy.
name = 'Goofy'
if name == 'Hen':
... print('Hi Hen')
else:
... print('Hello stranger')
The above code will execute as:
Hello stranger
Only one of the blocks will be executed. The execution starts at the top. Then the condition in the if statement is checked. It is False, so the execution jumps to the else statement. (See Figure 2-3: The flowchart for an else statement in Automate the Boring Stuff with Python by Al Sweigart.)
elif statements
We may have a case where we want one of many possible clauses to execute, not just one clause as in the if or else statements. The elif statement is an else if statement that lets you provide as many additional conditions to check as you need.
The elif statement always follows an if or another elif statement. The elif statement provides another condition that is checked only if all of the previous conditions were False. An elif statement consists of the following:
In a chain of elif statements, only one or none of the clauses will be executed. Once one of the statements’ conditions is found to be True, the rest of the elif clauses are skipped.
Let's look at an example. Open a new file editor window and enter the following code. Save the file as elif_statement_example.py and run it. (See Figure 2-5: The flowchart for multiple elif statements in the vampire.py program in Automate the Boring Stuff with Python by Al Sweigart.)
领英推荐
Optionally, an else statement can follow the last elif statement. In this case it is certain that the last clause will be executed if the conditions in every if and elif statement are False.
Let’s modify the elif_statement_example.py program to use if, elif, and else clauses.
name = 'Goofy'
age = 666
if name == 'Hen':
… print('Bock bock bock bawk.')
elif age < 12:
… print('You are not Hen, Kiddo.')
else:
… print('You are not Hen, Goofy. But you are a chicken.')
The above program will run as:
You are not Hen, Goofy. But you are a chicken.
Truthy and Falsey values
Some values in other data types beside Boolean are considered equivalent to True and False. 0, 0.0, and the empty string ' ' are considered False when used in conditions, while all other values are considered True.
Look at the following program - try it in a new file editor window:
print('Enter a name.')
name = input()
if name:
… print('Thank you for entering a name.')
else:
… print('You did not enter a name.')
This code will execute as follows if the user Alice entered her name:
Enter a name.
Alice
Thank you for entering a name.
Notice the if condition. The name variable is set to whatever the user inputs. Input will return a string value not a True or False value. Yet this code works because a condition can use Truthy or Falsey values. In this case, user input is Truthy (not blank).
For strings, the blank string is a Falsey value. If the condition evaluates to the blank string it is considered to be the same as the False Boolean value. That said, it is better to be more explicit and change the code as follows.
print('Enter a name.')
name = input()
if name != '':
... print('Thank you for entering a name.')
else:
... print('You did not enter a name.')
You can use the bool() function to return the equivalent Boolean value of whatever value you pass.
>>> bool(0)
False
>>> bool(666)
True
>>> bool('Hello')
True
>>> bool('')
False
Key takeaways
Lessons in this "pre-DevNet" Python series
Key references
Automate the Boring Stuff with Python – Al Sweigart free online book (free to read under a CC license)
Automate the Boring Stuff with Python – Al Sweigart YouTube playlist