BooleansSlide solved ✓
It is often necessary to have your program check if two values are the same.
This is done using two equals signs:
Note that a single equals sign is different: it is used to create a variable.
Example of comparing values
The code below compares some values. Run it to continue.
Try comparing values
To try using
==, write a program that calculates whether
42 == 42 and
prints the result.
Try comparing values again
Write a program that checks if
8*13+9 is equal to
When you compare two values with
==, the result is either
False are Python values, just like
"a string" and
You can store
False in variables, print them, and compare them,
just like any other value:
print(True) x = False y = True print(x == y)
The type of True and False
False have a different type from "string" and
"integer": they are Booleans. (They are
named after a mathematician, George Boole.)
False are written with an initial uppercase letter! If
you forget this and write
true, you are referring to the variable named
true, which can get confusing.
Sometimes you want to test if two values are different from each other. In
other words, you want to test for inequality. You do this using
which is pronounced "not equals".
Here is an example:
print(1 != 2)
The result is
2 are indeed different.
Try testing if
4 are different using
Try testing if
"abc" are different using
You can use the keywords '
and' and '
or' to combine Boolean values. Here is an
example of using
is_important_birthday = (age == 18 or age == 21)
Here is an example of using
can_concentrate = (well_fed and got_sleep)
Example of and
The code below combines two boolean variables using
and. What do you expect
the program to print?
Here's another way to view the question: if someone is well fed and they did
not get sleep, then is it the case that they are both well fed and got sleep?
No. Therefore the answer is
Run the code to confirm this.
Try using and
The code below uses
and to combine
False. Change the code so
that it instead combines
True. What do you expect the output to
Try using and from scratch
Write code that combines two boolean values using
and. Print the result.
It's up to you whether you use
False for the booleans. You can
even generate them using
!= if you prefer.
Try using or
The program below defines two boolean variables. Combine them using
print the result.
Use or from scratch
Write code that combines two or more booleans using
or. Print the result.
Sometimes you want to flip
True. You can use
the built-in function
not to do this:
x = not(True) print(x)
In this example,
x will be False.
not on a Boolean value and printing the result below.
Casting to Boolean
Remember how you can use
str to cast values to integers and
You can similarly use
bool to cast values to Booleans. For example:
x = bool(0) y = bool(1)
Add two calls to
The first call should print
x and the second call should print
y, so that
you can see for yourself what the
bool function does.