Open In App

Python Boolean

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions.

Example

Input: 1==1
Output: True

Input: 2<1
Output: False

Python Boolean Type

The boolean value can be of two types only i.e. either True or False. The output <class ‘bool’> indicates the variable is a boolean data type.

Python3




a = True
type(a)
  
b = False
type(b)


Output:

<class 'bool'>
<class 'bool'>

Evaluate Variables and Expressions

We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure. 

Syntax:

bool([x])

Python bool() Function

We can also evaluate expressions without using the bool() function also. The Boolean values will be returned as a result of some sort of comparison. In the example below the variable res will store the boolean value of False after the equality comparison takes place.

Python3




# Python program to illustrate
# built-in method bool()
  
# Returns False as x is not equal to y
x = 5
y = 10
print(bool(x==y))
  
# Returns False as x is None
x = None
print(bool(x))
  
# Returns False as x is an empty sequence
x = ()
print(bool(x))
  
# Returns False as x is an empty mapping
x = {}
print(bool(x))
  
# Returns False as x is 0
x = 0.0
print(bool(x))
  
# Returns True as x is a non empty string
x = 'GeeksforGeeks'
print(bool(x))


Output

False
False
False
False
False
True

Boolean value from the expression

In this code, since a is assigned the value 10 and b is assigned the value 20, the Python comparison a == b evaluates to False. Therefore, the code will output False.

Python3




# Declaring variables
a = 10
b = 20
  
# Comparing variables
print(a == b)


Output:

False

Integers and Floats as Booleans

Numbers can be used as bool values by using Python’s built-in bool() method. Any integer, floating-point number, or complex number having zero as a value is considered as False, while if they are having value as any positive or negative number then it is considered as True.

Python3




var1 = 0
print(bool(var1))
  
var2 = 1
print(bool(var2))
  
var3 = -9.7
print(bool(var3))


Output:

False
True
True

Boolean Operators

Boolean Operations in Python are simple arithmetic of True and False values. These values can be manipulated by the use of boolean operators which include AND, Or, and NOT. Common boolean operations are –

  • or
  • and
  • not
  • == (equivalent)
  • != (not equivalent)

Boolean OR Operator

The Boolean or operator returns True if any one of the inputs is True else returns False.

A B A or B
True True True
True False True
False True True
False False False

Python Boolean OR Operator

In the example, we have used a Python boolean with an if statement and OR operator that checks if a is greater than b or b is smaller than c and it returns True if any of the conditions are True (b<c in the above example).

Python3




# Python program to demonstrate
# or operator
  
a = 1
b = 2
c = 4
  
if a > b or b < c:
    print(True)
else:
    print(False)
  
if a or b or c:
    print("Atleast one number has boolean value as True")


Output

True
Atleast one number has boolean value as True

Boolean And Operator

The Boolean operator returns False if any one of the inputs is False else returns True.

A B A and B
True True True
True False False
False True False
False False False

Python Boolean And Operator

In the first part of the code,  the overall expression a > b and b < c evaluates to False. Hence, the code will execute the else block and print False. Whereas in the second part, a is 0, conditions a and b, and c will evaluate to False because one of the variables (a) has a boolean value of False. Therefore, the code will execute the else block and print “At least one number has a boolean value as False”.

Python3




# Python program to demonstrate
# and operator
  
a = 0
b = 2
c = 4
  
if a > b and b<c:
    print(True)
else:
    print(False)
      
if a and b and c:
    print("All the numbers has boolean value as True")
else:
    print("Atleast one number has boolean value as False")


Output

False
Atleast one number has boolean value as False

Boolean Not Operator

The Boolean Not operator only requires one argument and returns the negation of the argument i.e. returns the True for False and False for True.

A Not A
True False
False True

Python Boolean Not Operator

The code demonstrates that when the value of a is 0, it is considered falsy, and the code block inside the if statement is executed, printing the corresponding message.

Python3




# Python program to demonstrate
# not operator
  
a = 0
  
if not a:
    print("Boolean value of a is False")


Output

Boolean value of a is False

Boolean == (equivalent) and != (not equivalent) Operator

Both operators are used to compare two results. == (equivalent operator returns True if two results are equal and != (not equivalent operator returns True if the two results are not same.

Python Boolean == (equivalent) and != (not equivalent) Operator

The code assigns values to variables a and b and then uses conditional statements to check if a is equal to 0, if a is equal to b, and if a is not equal to b. It prints True for the first and third conditions.

Python3




# Python program to demonstrate
# equivalent an not equivalent
# operator
  
a = 0
b = 1
  
if a == 0:
    print(True)
      
if a == b:
    print(True)
      
if a != b:
    print(True)


Output

True
True

Python is Operator

The is keyword is used to test whether two variables belong to the same object. The test will return True if the two objects are the same else it will return False even if the two objects are 100% equal.

Python is Operator

The code first assigns the value 10 to variables x and y. It then compares x and y using the “is” operator and prints True because they refer to the same object. Next, it assigns two separate lists to x and y. It then compares x and y using the “is” operator and prints False because the lists are different objects in memory. 

Python3




# Python program to demonstrate
# is keyword
  
  
x = 10
y = 10
  
if x is y:
    print(True)
else:
    print(False)
  
x = ["a", "b", "c", "d"]
y = ["a", "b", "c", "d"]
  
print(x is y)


Output

True
False

Python in Operator

in operator checks for the membership i.e. checks if the value is present in a list, tuple, range, string, etc.

Python in Operator

The code creates a list of animals and checks if the string “lion” is present in the list. If “lion” is found in the list, it prints “True”.

Python3




# Python program to demonstrate
# in keyword
  
# Create a list
animals = ["dog", "lion", "cat"]
  
# Check if lion in list or not
if "lion" in animals:
    print(True)


Output

True


Previous Article
Next Article

Similar Reads

Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python | Contiguous Boolean Range
Sometimes, we come across a problem in which we have a lot of data in a list in the form of True and False value, this kind of problem is common in Machine learning domain and sometimes we need to know that at a particular position which boolean value was present. Let's discuss certain ways in which this can be done. Method #1 : Using enumerate() +
6 min read
Python | Boolean list initialization
Many times in programming, we require to initialize a list with some initial values. In Dynamic programming, this is used more often and mostly the requirement is to initialize with a boolean 0 or 1. Let's discuss certain ways in which this can be achieved. Method #1: Using list comprehension This can easily be done with the naive method, hence, ca
4 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.char.endswith(input_numpy_array,'substring') Parame
2 min read
Python program to fetch the indices of true values in a Boolean list
Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list. Let's see certain ways to do this task. Method #1: Using itertools [Pythonic way] itertools.compress() function checks for all the elements in list and returns the list of indices with True values. C/C++ Code # Python program to fe
5 min read
Python | Ways to convert Boolean values to integer
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task. Convert Boolean values to integers using int() Converting bool to an integer using Python typecasting. C/C++ Code # Initialising Values bool_val = True # Printing initial Values print(
3 min read
Python | Filter list by Boolean list
Sometimes, while working with a Python list, we can have a problem in which we have to filter a list. This can sometimes, come with variations. One such variation can be filtered by the use of a Boolean list. Let's discuss a way in which this task can be done. Using Numpy to Filter list by Boolean list Here, we will use np.array to filter out the l
5 min read
Python | Boolean List AND and OR operations
Sometimes, while working with Python list, we can have a problem in which we have a Boolean list and we need to find Boolean AND or OR of all elements in it. This kind of problem has application in Data Science domain. Let's discuss an easy way to solve both these tasks. Method #1 : AND operation - Using all() The solution to this problem is quite
3 min read
Python - False indices in a boolean list
Boolean lists are often used by the developers to check for False values during hashing. These have many applications in developers daily life. Boolean list is also used in certain dynamic programming paradigms in dynamic programming. Also in Machine Learning preprocessing of values. Lets discuss certain ways to get indices of false values in list
7 min read
Python - Test Boolean Value of Dictionary
Sometimes, while working with data, we have a problem in which we need to accept or reject a dictionary on the basis of its true value, i.e all the keys are Boolean true or not. This kind of problem has possible applications in data preprocessing domains. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is
9 min read
three90RightbarBannerImg