In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values.
x = True y = False print(int(x)) print(int(y))
int() turns the boolean into 1 or 0.
Note: that any value not equal to ‘true’ will result in 0 being returned.
Ways to convert Boolean values to integer 0 1 in Python
Python program to convert given a boolean value into an integer value 0 and 1
Using int() method
x = True print("Initial value: ", x) print("Converted value: ", int(x))
x = True if x: x = 1 else: x = 0 print(x)
numpy boolean list
import numpy x = numpy.array([True, False]) x = numpy.multiply(x, 1) print(x)
Output: [1 0]
Using map() Method
Convert boolean list values into a 0 1.
x = [True, False] x = list(map(int, x)) print(x)
Output: [1, 0]
Python boolean addition
Since bool is a subclass of int, it can be calculated like integers.
print(True + True) print(True * 10)
Count the number
the list of
False using the built-in function
sum() which calculates the sum of the numbers stored in the list.
print(sum([True, False, True]))
Do comment if you have any doubts and suggestions on this Python true false topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.