Python: Logical Operators

OperatorDescription
and
or
not

Notes

and” and “or” do not always return boolean results.

If the operands are boolean then “and“, “or” return a boolean result. These operators return some value otherwise.

and

first = 1
second = 2
third = 0

print(f'{first} and {second} = {first and second}')
print(f'{first} and {third} = {first and third}')
print(f'{third} and {second} = {third and second}')
Python

Output:

1 and 2 = 2
1 and 0 = 0
0 and 2 = 0
Plaintext
str1 = "bigboxcode"
str2 = "test"
str3 = ""

print(f'{str1} and {str2} = {str1 and str2}')
print(f'{str3} and {str2} = {str3 and str2}')
print(f'{str2} and {str3} = {str2 and str3}')
Python

Output:

bigboxcode and test = test
 and test =
test and  =
Plaintext
bool1 = True
bool2 = True
bool3 = False
bool4 = False

print(f'{bool1} and {bool2} = {bool1 and bool2}')
print(f'{bool3} and {bool4} = {bool3 and bool4}')
print(f'{bool1} and {bool3} = {bool1 and bool3}')
Python

Output:

True and True = True
False and False = False
True and False = False
Plaintext

or

first = 1
second = 2
third = 0

print(f'{first} or {second} = {first or second}')
print(f'{first} or {third} = {first or third}')
print(f'{third} or {second} = {third or second}')
Python

Output:

1 or 2 = 1
1 or 0 = 1
0 or 2 = 2
Plaintext
str1 = "bigboxcode"
str2 = "test"
str3 = ""

print(f'{str1} or {str2} = {str1 or str2}')
print(f'{str3} or {str2} = {str3 or str2}')
print(f'{str2} or {str3} = {str2 or str3}')
Python

Output:

bigboxcode or test = bigboxcode
 or test = test
test or  = test
Plaintext
bool1 = True
bool2 = True
bool3 = False
bool4 = False

print(f'{bool1} or {bool2} = {bool1 or bool2}')
print(f'{bool3} or {bool4} = {bool3 or bool4}')
print(f'{bool1} or {bool3} = {bool1 or bool3}')
Python

Output:

True or True = True
False or False = False
True or False = True
Plaintext

not

Output:

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.