Python Basics: 08 logical or boolean operations

Introducing logical or boolean operations in python

Suwes Muhammad Hafiz
3 min readMar 12, 2022

Logical or boolean operations are usually used in the determination of the comparison of several values ​​or data. Logical operations are widely used in control flow equations to take a decision on a program flow.

This time, we will study the logic operations that exist in the python programming language. There are 4 logical operators in python, namely NOT, OR, AND and XOR. The logical operators we usually call in the course lessons are truth tables. We will discuss them one by one.

Pay attention to the following table:

Truth tables — suweshafiz
explanation

NOT (reverse)

The NOT operator is used to return a value.

OR (added)

The OR operator returns true if one of them is true

AND (multiplied)

The AND operator returns true if both are true

XOR (Or Exclusive)

The XOR operator will return true if one of the values ​​is true, the rest will be false

Let’s try to program a logic operation:

# logical operators NOT, OR, AND, XOR

# NOT (reverse)
a = True
b = not a
print(“====== NOT ====”)
print(“a=”,a)
print(“ — — — -NOT”)
print(“b=”,b)

# OR (added, if one is true then the result will be true)
a = False
b = False
c = a or b
print(“====== OR ====”)
print(a,”or”,b,”=”,c)
a = False
b = True
c = a or b
print(a,”or”,b,”=”,c)
a = True
b = False
c = a or b
print(a,”or”,b,”=”,c)
a = True
b = True
c = a or b
print(a,”or”,b,”=”,c)


# AND (multiplied, if both are true then the result will be true)
a = False
b = False
c = a and b
print(“====== AND ====”)
print(a,”and”,b,”=”,c)
a = False
b = True
c = a and b
print(a,”and”,b,”=”,c)
a = True
b = False
c = a and b
print(a,”and”,b,”=”,c)
a = True
b = True
c = a and b
print(a,”and”,b,”=”,c)

# XOR (if one is true then the result is true, the rest is false)
a = False
b = False
c = a ^ b
print(“====== XOR ====”)
print(a,”xor”,b,”=”,c)
a = False
b = True
c = a ^ b
print(a,”xor”,b,”=”,c)
a = True
b = False
c = a ^ b
print(a,”xor”,b,”=”,c)
a = True
b = True
c = a ^ b
print(a,”xor”,b,”=”,c)

the output

===== NOT =====
a = True
— — — — NOT
b = False
===== OR =====
False or False = False
False or True = True
True or False = True
True or True = True
===== AND =====
False and False = False
False and True = False
True and False = False
True and True = True
===== XOR =====
False xor False = False
False xor True = True
True xor False = True
True xor True = False

NOTE: Logical operators can also use more than 3 values, according to the needs that exist in the program that we make.

The key to understanding logical operators is to understand the truth table in question, please try and understand.

--

--

No responses yet