= True myBool
4 Boolean Variables and Conditional Execution
4.1 Boolean Variables
We have learned about three types of variables in Python: ints, floats, and strings. Another variable type is a boolean, which can be one of two values: True
or False
. You can assign a boolean variable in the same way that you assign numbers or string, using =
True
must be capitalized so don’t try true
or it won’t be a boolean
= true myBool
4.1.1 Boolean Logic
Often you will want to check to see if some condition is true. For example, maybe you want to know if the radius of a certain satellite’s orbit is bigger or smaller than Mercury’s orbit. To perform this check, there are several boolean operators that will return True
or False
. Take note of the boolean operators shown in the cell below along with the comments added to explain what they do.
= 3.5e8
r1 = 2.7e6
r2
> r2 # Is r1 greater than r2
r1 < r2 # Is r1 less than r2
r1 >= r2 # Is r1 greater than or equal to r2
r1 <= r2 # Is r1 less than or equal to r2
r1 != r2 # Is r1 not equal to r2
r1 == r2 # Is r1 equal to r2 r1
False
A word of caution about comparing Python floats using ==
is in order here. Python floats are stored as a 53-digit, base-2 binary number(that’s a mouthful). If you’re interested in what that means, we can talk more. If you’re not that interested, just know that when you define a float in Python, the number that is stored in the computer is not exactly the number that you think it is. This can cause problems when you are comparing two numbers that you think should be equal but actually aren’t equal in the computer.1 The code below illustrates this problem.
= 0.1
a = 3 * a
b = 0.3
c print(b==c) # Are they the same number? You would think they would
# be right?
print(" {:.5f} ".format(b)) # They sure look the same.
print(" {:.5f} ".format(c)) # They sure look the same.
print(" {:.45f} ".format(b)) #b--- out to 45 decimal places
print(" {:.45f} ".format(c)) #c--- out to 45 decimal places
False
0.30000
0.30000
0.300000000000000044408920985006261616945266724
0.299999999999999988897769753748434595763683319
The first two print statements display the value of b
and c
to five decimal places. The second two print statements force Python to display the value of b
and c
out to 45 decimal places. Notice that the true value of b
is not exactly equal to 0.3. This is why the statement print(b==c)
returns False
. The take home message here is that comparing two floats to see if they are equal is always a bad idea. A better way to check to see if two floats are equal (or close enough that we can say they are equal) is to check if the absolute value of their difference is very small, like this:
= 0.1
a = 3 * a
b = 0.3
c print(abs(b - c) < 1e-10)
True
4.1.2 Compound Comparisons (Logical Operators)
Comparisons like those shown above can be chained together to make compound comparisons using the and
, or
, and not
operators.
Operator | Description |
---|---|
and | Tests for both being True |
or | Tests for either being True |
not | Tests for False |
The and
operator requires both inputs to be True
in order to return True
while the or
operator requires only one input to be True
in order to evaluate at True
. The not
operator is different in that it only takes a single input value and returns True
if and only if the input is False
. It is a test for False
.
Truth tables are a good way to visualize the output from compound comparisons.
p | q | p and q | p or q |
---|---|---|---|
True |
True |
True |
True |
True |
False |
False |
True |
False |
True |
False |
True |
False |
False |
False |
False |
As a simple example, suppose you know the density (\(\rho\)) and speed of light (c) for two materials and you’d like to know if both values are bigger for material 1 or material 2.
To Do:
- Predict the output for each compound comparison given below. Add your guess as a comment.
- Now add appropriately-placed print statements to check your guesses.
- Modify your guess as needed and discuss any questions with a neighbor.
= 2.5e8
c1 = 2.48e8
c2 1 = 450
ρ2 = 580
ρ
> c2 and ρ1 > ρ2
c1 < c2 and ρ1 < ρ2
c1 > c2 and ρ1 < ρ2
c1 < c2 and ρ1 > ρ2
c1
> c2 and not ρ1 > ρ2
c1 < c2 and not ρ1 < ρ2
c1
> c2 or ρ1 > ρ2
c1 < c2 or ρ1 < ρ2 c1
True
4.1.3 Tests for Inclusion
You can check for inclusion using the Python in
operator. This provides an easy way to see if a character (or word) is present in a long string. Let’s say you have a long string that contains the names of Jupyter’s moons (there are 79 of them!!) and you want to see if a certain moon is included in the list. The in
statement let’s us quickly test to see if it is in the list. (see example below)
= "Metis,Adrastea,Amalthea,Thebe,Io,Europa,Ganymede,Callisto,Themisto,Leda,Himalia,Lysithea,Elara,Dia,Carpo,Euporie,Thelxinoe,Euanthe,Helike,Orthosie,Iocaste,Praxidike,Harpalyke,Mneme,Hermippe,Thyone,Ananke,Herse,Aitne,Kale,Taygete,Chaldene,Erinome,Aoede,Kallichore,Kalyke,Carme,Callirrhoe,Eurydome,Pasithee,Kore,Cyllene,Eukelade,Pasiphae,Hegemone,Arche,Isonoe,Sinope,Sponde,Autonoe,Megaclite"
jupytermoons
"Cyllene" in jupytermoons
True
4.2 Conditions
Conditions allow the user to specify if and when certain lines or blocks of code are executed. Specifically, when a condition is true, the block of indented code directly below it will run.
4.2.1 if
statement
The if
statement is used to control when a block of code runs. Its usage is shown below ending in a colon and the block of code below indented with four spaces. Using the Tab key will also produce four spaces.
= "Metis,Adrastea,Amalthea,Thebe,Io,Europa,Ganymede,Callisto,Themisto,Leda,Himalia,Lysithea,Elara,Dia,Carpo,Euporie,Thelxinoe,Euanthe,Helike,Orthosie,Iocaste,Praxidike,Harpalyke,Mneme,Hermippe,Thyone,Ananke,Herse,Aitne,Kale,Taygete,Chaldene,Erinome,Aoede,Kallichore,Kalyke,Carme,Callirrhoe,Eurydome,Pasithee,Kore,Cyllene,Eukelade,Pasiphae,Hegemone,Arche,Isonoe,Sinope,Sponde,Autonoe,Megaclite"
jupytermoons
if "Cyllene" in jupytermoons:
= True
found print("Found Cyllene in the list")
if "Matis" in jupytermoons:
= True
found print("Found Matis in the list")
Found Cyllene in the list
If the boolean statement after if
is true, the indented code below it will run. If the statement is false, Python just skips the indented lines below. The end of an if
code block is determined by the indentation; to signal the end of the block, simply step back the indentation.
4.2.2 else
Statement
Sometimes there will be an alternate block of code that you want to run if the if
statement evaluates to False
. The else
statement is used to specify this block of code, as shown below.
= "Metis,Adrastea,Amalthea,Thebe,Io,Europa,Ganymede,Callisto,Themisto,Leda,Himalia,Lysithea,Elara,Dia,Carpo,Euporie,Thelxinoe,Euanthe,Helike,Orthosie,Iocaste,Praxidike,Harpalyke,Mneme,Hermippe,Thyone,Ananke,Herse,Aitne,Kale,Taygete,Chaldene,Erinome,Aoede,Kallichore,Kalyke,Carme,Callirrhoe,Eurydome,Pasithee,Kore,Cyllene,Eukelade,Pasiphae,Hegemone,Arche,Isonoe,Sinope,Sponde,Autonoe,Megaclite"
jupytermoons
if "Cyllene" in jupytermoons:
= True
found print("Found Cyllene in the string")
else:
= False
found print("Did not find Cyllene in the string")
if "Matis" in jupytermoons:
= True
found print("Found Matis in the string")
else:
= False
found print("Did not find Matis in the string")
Found Cyllene in the string
Did not find Matis in the string
Notice that the else
statement must be followed by a colon and the block of code to be executed is indented, just as in the if
block.
There is an additional statement called the elif
statement, short for “else if”, which is used to add extra conditions below the initial if
statement. The block of code below the elif
statement only runs if the if
statement is false and the elif
statement is true. An example is given below.
= "Metis,Adrastea,Amalthea,Thebe,Io,Europa,Ganymede,Callisto,Themisto,Leda,Himalia,Lysithea,Elara,Dia,Carpo,Euporie,Thelxinoe,Euanthe,Helike,Orthosie,Iocaste,Praxidike,Harpalyke,Mneme,Hermippe,Thyone,Ananke,Herse,Aitne,Kale,Taygete,Chaldene,Erinome,Aoede,Kallichore,Kalyke,Carme,Callirrhoe,Eurydome,Pasithee,Kore,Cyllene,Eukelade,Pasiphae,Hegemone,Arche,Isonoe,Sinope,Sponde,Autonoe,Megaclite"
jupytermoons
if "Matis" in jupytermoons:
= True
foundMatis print("Found Matis in the string")
elif "Cyllene" in jupytermoons:
= True
foundCyllene print("Found Cyllene in the string.")
else:
= False
foundCyl = False
foundMatis print("Did not find Cyllene or Matis in the string")
Found Cyllene in the string.
It is worth noting that else
statements are not required. If you leave the else
statement off and the if
statement is false, no code block will execute.
There is a library called
Decimal
that will fix a lot of these problems.↩︎