Logical operators

Logical operators

In python we have the following Logical operators  :  

  • and
  • or
  • not

Logical operators in Python

Operator

Meaning

Example

and

True if both the operands are true

x and y

or

True if either of the operands is true

x or y

not

True if operand is false (complements the operand)

not x

“and” Logical (Boolean) 

“and” will result in True only if both the operands are True.

The truth table for and is given below:

Truth table for “and” operator

A

B

A and B

True

True

True

True

False

False

False

True

False

False

False

False

Example:

a=True and True
b=True and False
c=False and True
d=False and False
print(a)
print(b)
print(c)
print(d)

Output:

True
False
False
False

Example:

#1
a=10 and 20
print(a)
print(bool(a))
#2
b=0 and 20
print(b)
print(bool(b))
#3
c=10 and 0
print(c)
print(bool(c))
#4
c=0 and 0
print(c)
print(bool(c))

Output:

20
True
0
False
0
False
0
False
>>>

“or” Logical (Boolean)

or will result in True if any of the operands is True. The truth table for or is given below:

The truth table for “or” operator

A

B

A or B

True

True

True

True

False

True

False

True

True

False

False

False

Example:

a=True or True
b=True or False
c=False or True
d=False or False
print(a)
print(b)
print(c)
print(d)

Output:

True
True
True
False
>>>

Example:

#1
a=10 or 20
print(a)
print(bool(a))
#2
b=0 or 20
print(b)
print(bool(b))
#3
c=10 or 0
print(c)
print(bool(c))
#4
c=0 or 0
print(c)
print(bool(c))

Output:

10
True
20
True
10
True
0
False
>>>

“not” Logical (Boolean)

not operator is used to invert the truth value. The truth table for not is given below:

The truth table for “not” Operator

A

not A

True

False

False

True

Example:

a=not True
b=not False
print(a)
print(b)

Output:

False
True
>>>

Example:

#1
x=10
print(x)
print(bool(x))
b= not x
print(b)
#2
y=0
print(y)
print(bool(y))
b=not y
print(b)

Output:

10
True
False
0
False
True
>>>