Computers make decisions about what to do next by asking questions. These questions usually involve comparing two values. For instance, is one number bigger than the other? If it is, the computer might skip a block of code that it would otherwise have run.
Create a new file called boolean_example.
Let's now create two integer variables, monsters and
coins.
The questions that computers ask only have two possible answers: True or False.
Python calls these two values Boolean
values, and they must always start with
a capital letter. You can store a Boolean value in a variable.
Let's now compare our two variables, monsters and coins and store that in a variable called compare:
Notice the symbol we're placing between coins and monsters: >. This symbol means "greater than" and is called a
Boolean Operator. Think of it as a math operation like + or -, except it can only be used to equal True or False rather than a number.
Below are the other boolean operators and their meanings:
Symbol | Meaning |
---|---|
> | greater than |
< | less than |
== | equal to |
!= | not equal to |
The above code we ran included a Boolean Expression.
A boolean expression is a comparison. It contains variables and values and uses logical operators. Can you point out which line of code above is a boolean expression?
In Python, you can also combine more than one comparison by using the logical operators and and or. Add this code to your file:
**When using or, only
one of the comparisons
needs to be correct for the
Boolean value to be True
When using and, both
the comparisons need
to be correct for the
Boolean value to be True
What do and-compare and or-compare equal when you run the code?
Play around with the values for monsters and coins, change ==
to another boolean operator (see table above), and
turn and into or and vice versa and see what output you get.
Sometimes you need to make decisions when
playing a game. Should you turn right to
investigate the library or turn left to look at
the kitchen? Computer programs often contain
code that runs only in certain situations. This
means the computer makes decisions about
which parts of the code to run.
Copyright © KX Technology Group, LLC. All Rights Reserved.