In this section, we'll explore the concept of booleans and how they are used in Python to represent true or false values. We'll also delve into comparison operators, which are used to evaluate conditions and make decisions within your programs.
We'll learn about the following topics:
Booleans in Python are a fundamental data type that can only hold two values: True
and False
. They are often used to represent logical conditions or make decisions within your programs.
Name | Type in Python | Description |
---|---|---|
Booleans | bool | Logical value indicating True or False |
type(True), type(False)
(bool, bool)
These operators will allow us to compare variables and output a Boolean value (True or False).
Operator | Description | Example |
---|---|---|
== | If the values of two operands are equal, then the condition becomes true. | (a == b) is not true. |
!= | If values of two operands are not equal, then condition becomes true. | (a != b) is true |
> | If the value of left operand is greater than the value of right operand, then condition becomes true. | (a > b) is not true. |
< | If the value of left operand is less than the value of right operand, then condition becomes true. | (a < b) is true. |
>= | If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. | (a >= b) is not true. |
<= | If the value of left operand is less than or equal to the value of right operand, then condition becomes true. | (a <= b) is true. |
5 == 5
True
8 == 9
False
Note that ==
is a comparison operator, while =
is an assignment operator.
5 != 6
True
5 != 5
False
These two operations (==
!=
) can be done on lists, tuples, dictionaries, and sets.
{'key1':1, 'key2':2} != {'key2':2, 'key1':1}
False
[1, 2] == [2, 1]
False
6>4
True
2>3
False
2 < 6
True
5 < 2
False
3 >= 3
True
1 >= 7
False
4 <= 4
True
8 <= 4
False
An interesting feature of Python is the ability to chain multiple comparisons to perform a more complex test.
1 < 2 < 3
True
The above statement checks if 1 was less than 2 and if 2 was less than 3. We could have written this using an and statement in Python:
1<2 and 2<3
True
1 < 3 > 2
True
The above checks if 3 is larger than both of the other numbers, so you could use and to rewrite it as:
1<3 and 3>2
True
It's important to note that Python is checking both instances of the comparisons. We can also use or to write comparisons in Python. For example:
1==2 or 2<3
True
1==1 or 100==1
True