Python Working With Boolean Data Type

Python Working With Boolean Data Type

Boolean data type is a one of the data types in python programming language. Boolean data has only two values True and False. It is mostly used to check whether the given statement is correct or not. It is the most used data type in any programming languages. Boolean data intended to use for Boolean Algebra . In python we mostly use it conditional statements (if...elif...else).

Working with logical "and" operator

x and y Returns
True and True True
True and False False
False and True False
False and False False

Above truth table represents how the operator "and" works with Boolean values. "and" will return "True" if and only if two operands have "True" value. Let's see some examples with code.

a = 10
b = 30
c = 20
# Case1
result = a > b and b < c
print(result)
# Output: False
# Case2
result = a < b and b > c
print(result)
# Output: True

From above code,

In Case1, a > b returns False because 10 > 30 is invlaid and we have "and" operator. In "and" operator to get True both the operands needs to have value True. In our case it's not. so, it will return False irrespective of the value b < c.

In Case2, a < b returns True, because 10 < 30 is valid and we have "and" operator. First operand has value "True" so, lets check for the second operand. b > c returns "True", because 30 > 20 is valid. If we replace both truth values then "a < b and b > c" will become "True and True", from above truth table the returning value is "True".

Working with logical "or" operator

x or y Returns
True or True True
True or False True
False or True True
False or False False

Consider variables "x" and "y". It will return "True" if any one of the variables contains the value "True" otherwise it returns "False".

# a number is a lucky number if it's divisible by 5 or 7
number = 21
is_lucky = (number % 5 == 0) or (number % 7 == 0)
print(is_lucky)
# Output: True
if (is_lucky):
    print("I'm lucky")
else:
    print("Better luck next time")

In python the execution of statement is from left to right and it executes the statements inside brackets first. so, it executes "(number % 5 == 0)" and it returns "False" after it executes "(number % 7 == 0)" and returns "True" then the statement becomes "False or True". From the above truth table the result is True.

Working with logical "not" operator

not x Returns
not True False
not False True

Consider a variable "x". If value of "x" is "True" then "not x" will return "False" otherwise if value of "x" is "False" then "not x" will return "True".

Working with "==" operator

x == y Returns
True == True True
True == False False
False == True False
False == False True

== is called as a equality operator. If we have two variables x, y. when we apply "==" on x, y like "x == y" then it checks that both "x", "y" have the same value or not. If it have same value then it returns "True" otherwise it returns "False".