Python provides 3 logic operators named AND
, OR
, NOT
. These logic operators are provided by all major programming languages and are the base of computing. These logical operators are used to combine conditional statements. In this tutorial, we will learn and examine how these operators are used for different cases.
and Logic Operator
The “and” logic is used to check if all given statements are True. If all given statements are True the “and” logic returns True. If one of the given statements is False AND logic returns False. Let’s make some examples to understand the “and” logic operator better. As we can see below “and” logic operator can be used with multiple statements which can be more than 2.
# result is True
result = True and True
# result is False
result = True and False
# result is True
result = True and True and True
# result is False
result = True and True and True and False
We can use the “and” operator in order to check multiple conditions. In the following example, we check if the age is over 18 and lower than 65 by using the “and” operator.
if age>18 and age<65:
print("Age is higher than 18 and lower than 65")
or Logic Operator
The “or” logic is used to check multiple statements and returns Tue if at least one of them is True. If all of them are False the logic returns False. We can say that the or operator is very optimistic and try to return True by matching at least one True statement. Like and logic operator the OR logic operator can be used with two or more statements.
# result is True
result = True or True
# result is True
result = True or False
# result is False
result = False and False and False
# result is True
result = False and False and True and False
We can use the or
logic operator multiple times in a single statement. We separate every expression with the “or” keyword. For example “False and False and True and False” is evaluated True
as a single True that may change all False into True because of the “or” operation.
We can use the “or” Logic operator in order to compare numbers with multiple conditions. In the following example, we check the age value if it is lower than 18 or higher than 65.
if age<18 or age>65:
print("Age is lower than 18 or higher than 65")
not Logic Operator
The not logic operator is different from the and, or logic operators. The not logic operator is used to reverse the given logic value into reverse. There are two logic values called True, and False. So the not True is equal to False, not False is equal to True. Let’s make some examples to better understand the not logic operator.
# result is False
result = not True
# result is True
result = not False
if( 18 is not 19):
print("That is true 18 is not 19")
Multiple Operators
We can use the “and” , “or” and “not” operators in the same statement. In the following example, we check the age is not 18 but between 16 and 20.
if (age is not18) and (age>16 and age<20):
print("Age is between 16 and 20 bu not 18")