
Concepts: Booleans
Representing on/off, yes/no, and true/false values with Python booleans.
Booleans in Python
A "boolean" is a type of data that can only have two possible values. Conceptually, many things can be reduced to a pair of possibilities:
- yes / no
- on / off
- true / false
- selected / not selected
- moving / not moving
- heads / tails
Python represents booleans with two values: True and False. Comparison operations in Python result in a boolean value being returned.
The most common comparison operation is checking for equality using the equality operator (==). The equality operator checks if the values to the left and right of it are equal to each other.
After the comparison is done, a True value is returned if the two values being compared are the same and False if they are not:
Note the examples below:
print(2 == 2)
> True
print(2 == 7)
> False
print(13.66 == 13.66)
> True
print("Hello" == "Hello")
> True
print("Hello" == "Hi")
> False
Practice: Booleans
Based on the information above. Complete the following steps:
-
Create a variable named
does_string_equal_numberand assign it the result of comparing the number value5with the string value"5". -
Print the boolean value in the
does_string_equal_numbervariable. -
Create a variable named
do_numbers_matchand assign it the result of comparing the number value5and the number value5. -
Print the boolean value in the
do_numbers_matchvariable. -
Create a variable named
does_casing_matchand assign it the result of comparing the string value"Hello"and the string value"hello". -
Print the boolean value in the
does_casing_matchvariable.HINT*: Click here for a hint
> False
> True
> False
SOLUTION*: Click here for an example solution
does_string_equal_number = 5 == "5" print(does_string_equal_number) do_numbers_match = 5 == 5 print(do_numbers_match) does_casing_match = "Hello" == "hello" print(does_casing_match)
When you have completed the above and understand that boolean values are returned from comparison operations, you are ready to go to the next exercise!