
Table of Contents(目次)
- What Is Python’s bool Type? The Basics of True and False
- Summary of Python Comparison Operators (==, !=, <, >, <=, >=)
- How Python Determines Truth Values
- Using the not Operator in Python
- Checking for Membership with in and not in in Python
- How to Use the is/is not Operators in Python
- How to Use Python's and/or Logical Operators
What Is Python’s bool Type? The Basics of True and False
So far, you have used True
and False
in if
statements and similar expressions, but in this lecture, we will take a closer look at how they actually work.
In statements like if
, which branch the program flow based on conditions, the subsequent flow of execution depends on whether the condition is true or false.
The bool
type has only two possible values: True
and False
.
# bool
True
False
Summary of Python Comparison Operators (==, !=, <, >, <=, >=)
Meaning and Usage of Python Comparison Operators
a == b
- Checks whether the values of a and b are equal: returns
True
if they are the same. =
is assignment, while==
compares values on both sides.- This is a common point of confusion for beginners.
- For numeric values, even if the types are different (e.g., int and float), it will return
True
if the values are considered equal.1 == 1.0
returnsTrue
.- However, comparing a number with a string, such as
1 == '1'
returnsFalse
.
- For strings, the result of
id()
may differ depending on how the string is created, but if the character sequence is the same,True
is returned.- String comparisons are case-sensitive.
- Checks whether the values of a and b are equal: returns
str1 = 'ABC'
str2 = f"A{'B'}C"
print(str1, id(str1)) # 'ABC' 2265151374416 (different id)
print(str2, id(str2)) # 'ABC' 2265158076096 (different id)
print(str1 == str2) # True because the sequence of characters is the same
a != b
- Checks whether both sides are different: returns
True
if they are not equal. - For strings, if even a single character differs, the result is
True
.'apple' != 'Apple'
returnsTrue
(case-sensitive).
- Checks whether both sides are different: returns
a < b
- Checks whether a is less than b: returns
True
if so. - When comparing magnitudes, comparing int/float with str is not allowed and raises a TypeError.
- This also applies to
a <= b
,a > b
, anda >= b
.
- This also applies to
- For numbers, comparison is based on their numeric values.
3 < 5
returnsTrue
.5 < 3
returnsFalse
.
- Strings can also be compared, but they are evaluated based on their assigned character codes (Unicode order).
'a' < 'b'
returnsTrue
(the Unicode value of 'a' is smaller).'A' < 'a'
returnsTrue
(uppercase letters come first—they have smaller assigned numbers).
- String comparisons behave similarly to dictionary index ordering.
'apple' < 'banana'
returnsTrue
.'apple' < 'Apple'
returnsFalse
.- (Since the Unicode value of
'A'
is smaller than that of'a'
,'Apple'
comes earlier alphabetically, so'apple' < 'Apple'
isFalse
.)
- (Since the Unicode value of
- Checks whether a is less than b: returns
a <= b
- Checks whether a is less than or equal to b: returns
True
if a is less than or equal to b. - This combines both
<
and==
conditions.3 <= 5
returnsTrue
.5 <= 5
also returnsTrue
.
- For strings, the same comparison is made according to Unicode order.
- Checks whether a is less than or equal to b: returns
a > b
- Checks whether a is greater than b: returns
True
if a is greater than b. - This is the reverse of
<
.7 > 3
returnsTrue
.3 > 7
returnsFalse
.
- For strings, comparison is based on Unicode order.
'z' > 'a'
returnsTrue
.'A' > 'a'
returnsFalse
.
- Checks whether a is greater than b: returns
a >= b
- Checks whether a is greater than or equal to b: returns
True
if a is greater or equal. - This combines both
>
and==
conditions.5 >= 5
returnsTrue
.10 >= 2
returnsTrue
.
- String comparisons follow the same Unicode-based ordering.
- Checks whether a is greater than or equal to b: returns
a < x < b
- You can also check whether a variable falls within a certain range, such as
0 < num <= 10
. - You can use
<
,>
,<=
, and>=
(comparison operators), but for readability, it is common to use combinations of<
and<=
.
- You can also check whether a variable falls within a certain range, such as
Data Types That Can and Cannot Be Compared in Python
Equality Comparison (== / !=)
Different types can still be compared (though the result may not be meaningful). Python attempts to determine whether the values on both sides are equal, but if their types differ, the result is usually False
.
Magnitude Comparison (<, >, <=, >=)
Different types cannot be compared (in Python 3, this causes an error). In particular, comparing numbers and strings by size is considered meaningless and results in a TypeError.
Comparisons are possible between values of the same type:
- Between numeric types (
int
,float
,Decimal
, etc.) - Between strings (compared by Unicode order)
Operator | Can compare values of different types? | Example (1 vs '1' ) | Result or Error |
---|---|---|---|
== | Yes (returns False) | 1 == '1' | False |
!= | Yes (returns True) | 1 != '1' | True |
< | No (raises error) | 1 < '1' | TypeError |
<= | No (raises error) | 1 <= '1' | TypeError |
> | No (raises error) | 1 > '1' | TypeError |
>= | No (raises error) | 1 >= '1' | TypeError |
How Python Determines Truth Values
True and False in Python Can Also Be Used as Integers
First, take a look at the following code:
int(True) # 1
int(False) # 0
True == 1 # True
False == 0 # True
In Python, when you convert True
or False
to an integer, True
becomes 1
and False
becomes 0
. In other words, the integers 1
and 0
can also be treated as boolean values.
For example, the following code works as expected: if 1:
evaluates to True
, while if 0:
evaluates to False
.
# True
if 1:
print('True')
else:
print('False')
# False
if 0:
print('True')
else:
print('False')
Truth Value Evaluation for All Python Objects
In Python, every object can be evaluated as either True
or False
. This applies not only to numbers but also to strings, lists, dictionaries, and other data types. In the following example, the variable greeting contains the value 'Hello'
, which is a non-empty string, so it is treated as True
. Therefore, the message “Evaluated as True” is displayed.
greeting = 'Hello'
if greeting:
print('Evaluated as True')
Values That Are Treated as False in Python
Let’s first remember which values behave like False
, since there aren’t many of them.
Values that behave like False
share some common traits: they represent “zero,” “empty,” or “nonexistent (None
).”
# False
0
0.0
'' # Empty string
[] # list with no elements
{} # dict with no elements
tuple() # tuple with no elements
set() # set with no elements
None # None (explicitly represents the absence of a value)
Values That Are Treated as True in Python
All other values are treated as True
. The key point is that a value is considered True
if it is “not empty.”
For example, in data structures like lists, even if the elements themselves are 0
or None
, the object will be treated as True
as long as it is not empty. The important thing is whether it contains elements.
# True
1
-1
0.0001
-0.0001
'0' # Any non-empty string
' ' # A whitespace character is also True
[None] # Even if elements are 0, None, or an empty string, a non-empty list is True (same applies to other containers below)
{0: None}
(0,)
{0}
As a practical example, consider checking whether a list has elements before calling pop()
. The pop()
method raises an error if the list is empty, so it’s important to verify that elements exist beforehand for stable execution.
While you can write something like if len(num_list) > 0:
(“perform an operation if the number of elements is greater than zero”), using if num_list:
is simpler and more readable. In this case, if num_list
has zero elements, the if
block will be skipped, and it will only run when one or more elements exist.
num_list = [1, 2, 3]
# Pop an element if the list has any items
if num_list:
result = num_list.pop()
print(num_list)
print(result)
Using the not Operator in Python
The not
operator represents logical negation. It turns True
into False
and False
into True
.
a = True
print(not a) # False
b = False
print(not b) # True
Using not
allows you to reverse a condition, expressing something like “if not ...”. For example, the following code means “if the list has no elements, add one.”
num_list = []
# Add an element if the list is empty
if not num_list:
num_list.append(None)
print(num_list)
Checking for Membership with in and not in in Python
You can write expressions like a in b
or a not in b
to check whether a
is “contained in” (in
) or “not contained in” (not in
) b
.
Checking Substrings in Python Strings
For strings, this checks whether a substring is contained within another string. This comparison is case-sensitive.
For instance, the expression 'can' in 'I can do it.'
checks whether the sequence of characters 'can'
appears within the string 'I can do it.'
. Since it does, the result is True
.
text = 'I can do it.'
print('can' in text) # True ('can' is included)
print("can't" not in text) # True ("can't" is not included, so True)
Checking Elements in Lists, Tuples, and Sets
For lists, tuples, and sets, the operator checks whether a given value exists among their elements.
num_list = [1, 2, 3]
print(1 in num_list) # True
print(4 in num_list) # False
print(1 not in num_list) # False
print(4 not in num_list) # True
Checking for Key and Value Existence in a Python dict
In a dict, you check for the existence of a key (values are not considered). However, you can check if a value exists after retrieving values with dict.values()
.
# Checking for the presence of keys
tmp_dict = {'key1':100, 'key2':200}
print('key1' in tmp_dict) # True
print(100 in tmp_dict) # False (No key '100' exists)
print('key1' not in tmp_dict) # False (The key 'key1' exists, so [not in] is False)
print(100 not in tmp_dict) # True (No key '100' exists, so True)
# Checking for the presence of values
tmp_dict = {'key1':100, 'key2':200}
print(100 in tmp_dict.values()) # True (Value 100 exists)
print(500 not in tmp_dict.values()) # True (Value 500 does not exist)
How to Use the is/is not Operators in Python
is
checks whether two variables reference the same object. This differs from ==
, which checks if the values are equal.
Checking Different Objects with the Same Value
In the following code, the variables a and b have the same visible value ('ABC'
), but id()
shows that they reference data stored at different locations.
Here, ==
returns True
, but is
returns False
. Use ==
or is
depending on whether you want to check the value or the reference.
a = 'ABC'
b = f"{'A'}{'B'}{'C'}"
id(a) # e.g., 139982392668688
id(b) # e.g., 139979347634776
a == b # True Values are the same
a is b # False Different objects
When Variables Reference the Same Object
If you make b
reference the same object as a
(e.g., b = a
), is
will return True
.
b = a
id(a) # e.g., 139982392668688
id(b) # e.g., 139982392668688 (same as a)
a == b # True Values are the same
a is b # True Same object reference
How to Use the is not Operator in Python
is not
means that the two variables do not reference the same object.
x = [1, 2, 3] # e.g., id: 2066161843712 (different id)
y = [1, 2, 3] # e.g., id: 2066161828672 (different id)
x == y # True Values are the same
x is y # False Different list objects
x is not y # True Not the same object
How to Use Python's and/or Logical Operators
and: Behavior and Evaluation Order
and
is a logical operator that returns True
only if both conditions are True
.
Consider the following code:
num = 5
if num > 0:
if (num % 2) == 1: # If the remainder of num % 2 is 1, the number is odd
print('Positive & Odd') # Printed if num = 5
The code above executes print('Positive & Odd')
only if num is positive and odd. The same logic can be written in one line using and
:
num = 5
if (num > 0) and ((num % 2) == 1):
print('Positive & Odd') # Printed if num = 5
As shown in the code above, even if each conditional expression is not enclosed in parentheses, the evaluation of conditions works correctly. In Python, operator precedence is defined, so operators with higher precedence are evaluated first, which means writing if num > 0 and num % 2 == 1:
evaluates as intended.
However, enclosing expressions in parentheses makes it easier to understand which conditions are being combined with and
, so for readability, the author prefers to write code using parentheses.
※ Naturally, if you want to evaluate expressions in an order different from Python’s default precedence, you need to control the order using parentheses.
Operator | Description |
---|---|
(expressions...) ,[expressions...] ,{key: value...} , {expressions...} | Binding or parenthesized expression, list display, dictionary display, set display |
x[index] , x[index:index] ,x(arguments...) , x.attribute | Subscription, slicing, call, attribute reference |
await x | Await expression |
** | Exponentiation [5] |
+x , -x , ~x | Positive, negative, bitwise NOT |
* , @ , / , // , % | Multiplication, matrix multiplication, division, floor division, remainder [6] |
+ , - | Addition and subtraction |
<< , >> | Shifts |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
in ,
not in ,
is ,
is not ,< , <= , > , >= , != , ==
| Comparisons, including membership tests and identity tests |
not x | Boolean NOT |
and | Boolean AND |
or | Boolean OR |
if – else | Conditional expression |
lambda | Lambda expression |
:= | Assignment expression |
The evaluation of and
works as follows:
- If the left-hand condition is
False
, the right-hand condition is not checked, and the result isFalse
- The result is
True
only if both conditions areTrue
print(True and True) # True (both conditions are evaluated)
print(True and False) # False (both conditions are evaluated)
print(False and True) # False (right-hand condition is not checked because the left-hand condition is False)
print(False and False) # False (right-hand condition is not checked because the left-hand condition is False)
Behavior and Evaluation Order of or
or
returns True
if either condition is True
. It only returns False
if both conditions are False
.
- If the left-hand condition is
True
, the right-hand condition is not checked andTrue
is returned - If the left-hand condition is
False
, the right-hand condition is evaluated and eitherTrue
orFalse
is returned
print(True or True) # True (right-hand condition is not checked because the left-hand condition is True)
print(True or False) # True (right-hand condition is not checked because the left-hand condition is True)
print(False or True) # True (both conditions are evaluated)
print(False or False) # False (both conditions are evaluated)
Example of Combining and
and or
For example, consider the conditions for using a sports club.
- Being a member or
- 18 years or older and having paid the daily fee
This condition can be written in Python as follows:
# User information
person = {
'member': True,
'age': 18,
'paid': True
}
# Check eligibility
if person['member'] or (person['age'] >= 18 and person['paid']):
print('You can use the sports club')
else:
print('You cannot use it')
- If
member
isTrue
, the right-hand condition is not checked, and access is allowed - If
member
isFalse
, the right-hand condition(age >= 18 and paid)
is evaluated
When and
and or
are mixed, using parentheses to structure the code makes the evaluation order clear.
If the condition is long, it can be split across multiple lines. When doing so, enclose the entire condition in parentheses.
(if a or b and c:
-> if (a or b and c):
)
if (person['member'] or
(person['age'] >= 18 and person['paid'])):
print('You can use the sports club')
By enclosing the entire condition in parentheses, it is evaluated correctly even when split across lines, and readability is improved.
There is no strict rule for the indentation of the continued line (line 2 of the code above); using 4 spaces is syntactically valid. However, 4 spaces may make it harder to distinguish the condition from the block.
if (person['member'] or
(person['age'] >= 18 and person['paid'])): # This line has the same indentation as the next line
print('You can use the sports club')
Therefore, according to Python's PEP 8(Code Lay-out), it is recommended to use 8 spaces (two levels of indentation) for improved readability. Alternatively, a comment at the beginning of the block can separate the condition from the block.
if (person['member'] or
(person['age'] >= 18 and person['paid'])): # Use two levels of indentation
print('You can use the sports club')
if (person['member'] or
(person['age'] >= 18 and person['paid'])):
# Add a comment (e.g., explaining the block) to separate the condition from the block
print('You can use the sports club')