Everything You Need To Know About Booleans in python

Booleans are most important aspects of programming languages.

Topics: ,

Booleans are the most important aspects of programming languages. Because they give codes the power to make decisions. It is only right to learn everything about them. When we compare two values in Python, we get a boolean answer.

In Python, booleans can have two values.

  • True
  • False

In Python, only True and False are Boolean class values.

Python
Python
Python
## get class names of Boolean value  True and False
print(type(True))
print(type(False))
Output
<class 'bool'>
<class 'bool'>
Python

Substitute Booleans

  • Python has a unique take on boolean values, you can use any class objects as boolean values.
  • In a conditional statement, if any return type or value of an object is not 0, False, None, or Empty then everything else is True.
Python
Python
Python
# Use bool to turn values into boolean.
  False values                                        Output
print('False Values')                              False Values
print('bool(0) \t',end='')             
print(bool(0))                                     bool(0) 	False
print('bool(False) \t',end='')         
print(bool(False))                                 bool(None) 	False  
print('bool() \t',end='')
print(bool())                                      bool(None) 	False
print('bool(None) \t',end='')
print(bool(None))                                  bool(None) 	False
Python
Python
Python
  True values                                          Output
print('True Values')                               True Values 
print('bool(1) \t',end='')                      
print(bool(1))                                     bool(1) 	True
print('bool(True) \t',end='')
print(bool(True))                                  bool(True) 	True
print('bool("this is a string") \t',end='')
print(bool('this is a string'))                    bool('this is a string') 	True
lis=[1,2,3]
print(f'{bool(lis)} \t',end='')
print(bool(lis))                                   bool([1,2,3])

Numbers are used as boolean values.

Python offers numbers to be used as boolean values; any number other than 0 is considered True.

Python
Python
Python
# True is greater than 10                        Output
print(True>10)                                   False 
# False is equal to ,is equal to -1
print(False==-1)                                 False 
# True is equal to ,is equal to 1
print(True==1)                                   True     
# False is equal to ,is equal to 0
print(False==0)                                  True
Python
Python
Python
# false plus false is zero                    Output
print(False+False)                              0
# true adds to true equals to two.
print(True+True)                                2

Numbers in Conditional Statements

Let’s use numbers as boolean values in conditional statements.

  • As previously stated, when it comes to numbers, a boolean value of ‘0’ is False.
  • Any number other than 0 is True.
Python
Python
Python
# use 0 as false
if 0:
    print('True')
else:
    print('False')
Output
False
Python
Python
Python
Python
# use any number but 0 as false
if 1:
    print('True')
else:
    print('False')
Output
True
Python
Python
Python
Python
# 25 as true
if 25:
    print('True')
else:
    print('False')
Output
True
Python
Python
Python
Python
# -120 as true
if -120:
    print('True')
else:
    print('False')
Output
True
Python

Boolean Operators

  • not operator
  • and operator
  • or operator
ABnot Anot BA and BA or B
TrueTrueFalseFalseTrueTrue
TrueFalseFalseTrueFalseTrue
FalseTrueTrueFalseFalseTrue
FalseFalseTrueTrueFalseFalse

As you can see, the above operators operate on boolean values.

Let’s look at some examples of these operators.

Python
Python
Python
# see how or is used
print('  A       B   \tResult')
print('True or False \t',end='')
print(True or False)
# use true or true  with or operator
print('True or True \t',end='')
print(True or True)
# use false or false  with or operator
print('False or False \t',end='')
print(False or False)
Output
  A       B   	Result
True or False 	True
True or True 	True
False or False 	False
Python
Python
Python
Python
# see how and is used 
print('  A       B   \tResult')
print('True and False\t',end='')
print(True and False)
print('False and False\t',end='')
print(False and False)
print('True and True\t',end='')
print(True and True)
Output
  A       B   	Result
True and False	False
False and False	False
True and True	True
Python

“not” is used to negate a statement’s value.

Python
Python
Python
# see how to use not.
print('Statement\tOutput',end='')
print('not True\t',end='')
print(not True)
print('not False\t',end='')
print(not False)
print('not (False and False)\t',end='')
print(not(False and False))
Output
Statement               Output 
not True	        False
not False	        True
not (False and False)	True
Python

Comparison Operator

  1. Equal to ==
  2. Not Equal to !=
  3. Greater than >
  4. Lesser Than <
  5. Greater than or Equal to >=
  6. Lesser than or Equal to <=
  7. is operator
  8. in operator

A boolean value is returned by comparison operators. When a statement is executed, it returns a boolean value.

1. is equal to (==) operator

Python
Python
Python
# 'Apple' is equal to 'Apple'
print('Apple'=='Apple')
# 'Apple' is equal to 'Cherry Blossom'
print('Apple'=='Cherry Blossom')
Output
True
False
Python

2. is not equal to (!=) operator

Python
Python
Python
# 'Apple' is not equal to 'Cherry Blossom'
print('Apple'!='Cherry Blossom')
# 4 is not equal to 5
print(4!=5)
Output
True
True
Python

3. Greater than (>) operator

Python
Python
Python
a=4
b=9
c=14
# b is greater than a 
b>a
# a is greater than b 
a>b
Output
True
False
Python

4. Less than (<) operator

Python
Python
Python
a=4
b=9
c=14
# b is lesser than a 
b<a
# a is lesser than c 
a<c
Output
False
False
Python

5. Greater than or equal to (>=) operator

Python
Python
Python
# c is greater than equal to a
a=4
b=9
c=14
c>=a
Output
True
Python

6. Lesser than or equal to (<= ) operator

Python
Python
Python
# c is lesser than equal to b
a=4
b=9
c=14
c<=b
Output
True
Python

7. in operator

In operator is used to find values in iterable objects.

Python
Python
Python
# find 'apple' in string
string='An apple a day, keeps the doctor away'
print('apple' in string)

# find 'banana' in string
print('banana' in string)

# confirm if there is not 'banana' in string
print('banana' not in string)
Output
True
False
True
Python

These statements can be used in code logic to control the flow of code.

Python
Python
Python
# use in operator to control flow of logic.
if 'apple' in string:
    print('Apple is present')
elif 'banana' in string:
    print('Banana is present')
if 'banana' not in string:
    print('banana is not present')
Output
Apple is present
banana is not present
Python

8. operator is

  • Unlike the symbol operator, this operator works on the identity of objects.
  • It returns True if the compared objects are identical.

operator is not

  • The is not operator is the inverse of is.
  • It returns True when the given objects are not identical.
Python
Python
Python
# find if a is b
a=5
b=5
c=4
print(a is b)
# find if a is not c
print(a is not c)
Output
True
True
Python
Python
Python
Python
a=[1,2,3,4,5]
b=[1,2,3,4,5]
# find if the list a is equal to b list
print(a is b)
# find if the list a is not equal to b list
print(a is not b)
Output
True
False
Python

Other data types, such as lists, sets, and tuples, can also be compared.

Python
Python
Python
a=[1,2,3,4,5]
b=[1,2,3,4,5]
# find if the list a is equal equal to b list
print(1,a==b)

a=(1,2,3,4,5)
b=(1,2,3,4,5,6)
# find if the tuple a is not equal to b tuple
print(2,a!=b)

a={1,2,3,4,5,6}
b={1,2,3,4,5}
# find if the set a is greater than b set
print(3,a>b)

a={1:1,2:2,3:3,4:4,5:5}
b={1:1,2:2,3:3,4:4,5:5}
# find if the dictionary a is equal to equal to b dictionary
print(4,a==b)
Output
1 True

2 True

3 True

4 True
Python

Chaining Comparison Operators

  • We can chain comparisons together.
  • For logic development, we can chain comparisons together and separate them with ‘and’/’or’ operators.
Python
Python
Python
# chain comparison operators
# 1 is less than 8 is greater than
print(1, 1 < 8 > 7)
# 1 is greater than 8 is greater than
print(2, 1 > 8 > 7)
# 1 is less than 8 is less than
print(3, 1 < 8 < 7)
# 1 is less than or 8 is less than
print(4, 1 < 8  or 8 < 7)
# 1 is less than or 8 is greater than
print(5, 1 < 8  and 8 > 7)

Output
1 True
2 False
3 False
4 True
5 True
Python

Range selection using comparison operators and chaining operators

Python
Python
Python
# create a list
num=[x for x in range(25)]
print(num)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Python

As you can see from the list above, there are 25 numbers. Let’s look at the Range selection.

Python
Python
Python
# print numbers greater than 10
for i in num:
    if i>10:
        print(i,end=' ')
Output
11 12 13 14 15 16 17 18 19 20 21 22 23 24 
Python
Python
Python
Python
# print numbers lesser than 10
for i in num:
    if i<10:
        print(i,end=' ')
Output
0 1 2 3 4 5 6 7 8 9 
Python

In the preceding examples, we saw ranges of greater than and less than ten. Let’s try picking a particular number from a group now.

Python
Python
Python
# print numbers greater than 10 and less than 18
for i in num:
    if i>10 and i<18:
        print(i,end=' ')
Output
11 12 13 14 15 16 17 
Python
Python
Python
Python
# print numbers less than 10 and great  than 4
for i in num:
    if i<10 and i>4:
        print(i,end=' ')
Output
5 6 7 8 9
Python

Be cautious when configuring range conditions.

Python
Python
Python
# print numbers greater than 10 and lesser  than 0
for i in num:
    if i>10 and i<0:
        print(i,end=' ')

Output
11 12 13 14 15 16 17 18 19 20 ..........
Python

Priority

  • When it comes to chaining with comparison operators, boolean operators, like arithmetic operators, have a defined precedence.
  • In this order: 1.’not’ 2.’and’ 3.’or’
Python
Python
Python
# create a list of prime and odd numbers
prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,  47]
odd=[x for x in range(51) if x%2==1]
print(prime)
print(odd)
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49
Python

Logic Chaining

Python
Python
Python
# create a large chain rule
not 1 < 8  and 8 < 7 or 1 > 7 and 1 < 8
Output
False
Python

Nested Chain Rule

Python
Python
Python
# create a large chain rule
not (1 < 8  and 8 < 7 or 1 > 7 and 1 < 8)
Output
True
Python

As shown in the preceding example, changing the order of these chains can result in a change in logic.

Exercise caution when constructing chains in your code.

Short Circuit

  1. As an efficiency measure in Python, operators are supposed to short circuit if their output is confirmed.
  2. The reason for the short circuit
  3. In a and statement, if the first value is False, the result is obviously False.
  4. Similarly, if the first value in an or statement is True, the result is True.

Check out the example below.

Python
Python
Python
# Creating a Short circuit example by avoiding an inevitable error
True or 1/0
Output
True
Python
  • In the preceding example, a divided by zero exception should have occurred, but it did not because the statement short-circuited.
  • Following will cause error because there is False or, first statement false will enable the compiler to check the next statement which is 1/0, and it will cause divided by zero error.
Python
Python
Python
# Creating a Short circuit example by avoiding an inevitable error
False or 1/0
Output
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-43-4197a8a91ebb> in <module>
      1 # Creating a Short circuit example by avoiding an inevitable error
----> 2 False or 1/0

ZeroDivisionError: division by zero
Python

This error is avoided because it is cut off by the obvious conclusion of “false” and being false.

  • False and False == False
  • False and True == False
Python
Python
Python
False and 1/0
Output
False
Python

The above statement didn’t cause an error because and requires both conditions to be True . So if there is one False statement other statement won’t matter whether it is true or false, the result will be False.

Sequenced Boolean datatypes

  • Python returns a True value if a sequenced datatype is not empty.
  • An empty datatype will return False.

Dictionary, List, Tuple, and Byte are used for creating boolean values.

Tuple

Python
Python
Python
# tuple as boolean
a=()
bool(a)
Output
False
Python

Bytes

Python
Python
Python
# bytes as boolean
a=bytes()
bool(a)
Output
False
Python
Python
Python
Python
# bytes as boolean
a=bytes()
bool(a)
Output
False
Python
Python
Python
Python
# bytes as boolean
a=bytes(123)
bool(a)
Output
O/P:
True
Python

Dictionary

Python
Python
Python
# dictionary as boolean
a={}
bool(a)
Output
False
Python
Python
Python
Python
# dictionary as boolean
a={1:2,3:4}
bool(a)
Output
True
Python
Python
Python
Python
# list as boolean
a=[1,2,3,4]
bool(a)
Output
True
Python

Boolean Values for Function Objects and Classes

  • If you use functions for booleans, they will always return True.
  • Classes are always True by default, but they can be programmed to be False.
Python
Python
Python
# create a hollow function
def function1():
    pass
# use function as bool value
bool(function1)
Output
True
Python

However, if you call a function, it will be dependent on what it returns.

  • function1 does not return a value, so it is None, and None in Python is false.
  • The only difference is the presence of parenthesis, which alters the output.
Python
Python
Python
# using function returntype as bool value.
def function1():
    pass
bool(function1())
Output
False
Python
Python
Python
Python
# using function returntype as bool value.
def function1():
    return True
bool(function1())
Output
True
Python
Python
Python
Python
# using function returntype as bool value.
def function1():
    return None
bool(function1())
Output
False
Python

How useful was this post?

Click on a star to rate it!

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Manova Quiz

    Solve this quiz for testing Manova Basics

  • Quiz on Group By

    Test your knowledge on pandas groupby with this quiz

  • Visualization Quiz

    Observe the dataset and try to solve the Visualization quiz on it

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

Instagram
WhatsApp
error: Content is protected !!