Logical operators

Name

Symbol

Syntax

Explanation

And operator

and 

val > 0 and val <= 5

Returns True if both conditions are True

Or operator

or 

val_1 < 5 or val_2 < 5

Returns True if one of the conditions is True

Not operator

not 

not (val_1 == 5)

Returns the opposite of the condition

Let’s use test values so that we can dry run some examples of this code. We’ll set num_one to 6 and num_two to 3. Applying logical operators on certain numerical conditions would give the following results:

The and operator

True if both num_one and num_two are true; otherwise, it’s False.

Expression: 6 is greater than or equal to 0 and less than 5, which is False.

The or operator

True if either num_one is greater than 5 or num_two is less than 3; False if both are False.

Expression: 6 is greater than 5, or 3 is less than 3, which is True.

The not operator

True if num_one is not equal to 10; False if num_one is True.

Expression: 6 is not equal to 10, which is True.

Code

We can put this effectively into Python code, and you can even change the numbers and experiment with the code yourself! Click the “Run” button to see the output.

Press + to interact
num_one = 6
num_two = 3
result_and = num_one >= 0 and num_one < 5
print(result_and)
result_or = num_one > 5 or num_two < 3
print(result_or)
result_not = not num_one == 10
print(result_not)

Logical operators can be combined to form complex conditions that are dependent on more than one variable.

Press + to interact
my_list = [1, 2, 3, 4, 5]
is_list_not_empty = bool(my_list)
first_element_is_one = my_list[0] == 1
contains_odd_numbers = any(i% 2 != 0 for i in my_list)
nested_conditions_result = (is_list_not_empty and first_element_is_one) or (not contains_odd_numbers)
print(nested_conditions_result)

The above code will return True if either one of the following conditions is True, since the conditions are joined using an or operator.

  • The list is not empty, and the first element’s value is equal to 1.

  • The list does not contain odd numbers.

Since the first condition is True, the result is evaluated as True.