Boolean Datatype in Python


☞The result will be in True or False.

☞Non-zero number denotes True whereas Zero denotes False in boolean.

☞Non-empty string denotes True whereas Empty string denotes False in boolean.

☞Here we will learn about bool() datatype

Example :

a=bool(1)
b=bool(0)
c=bool(-35)
d=bool(97)
print(a,b,c,d)
print("------------------")
e=bool(1.0)
f=bool(0.0)
g=bool(-2.45)
h=bool(54.56)
print(e,f,g,h)
print("------------------")
i=bool('')
j=bool('ad')
k=bool(' ')
print(i,j,k)
print("------------------")
l=bool(1+4j)
m=bool(0+5j)
n=bool(5+0j)
p=bool(0+0j)
print(l,m,n,p)
Output
True False True True
------------------
True False True True
------------------
False True True
------------------
True True True False

Taking boolean value as an input

☞To take input from the user, we will use input() function and then convert it into boolean value using bool() function.

☞Remember : above mentioned point will work only with string.

☞Example : a = bool(input())

☞To convert number into boolean value, we will use input() function to take input as string and then convert it into number using int(), float() or complex() function according to its type, after that this number will pass through bool function.

☞Example : a = bool(int(input())); b = bool(float(input())); c = bool(complex(input()));

Example :

a = bool(input("Enter a string : "))
print(a)
print("------------------")
b = bool(int(input("Enter a number : ")))
print(b)
print("------------------")
c = bool(float(input("Enter a decimal number : ")))
print(c)
print("------------------")
d = bool(complex(input("Enter a complex number : ")))
print(d)
print("------------------")
Output
Enter a string : inspirewebsoft
True
------------------
Enter a number : 34
True
------------------
Enter a decimal number : 0.67
True
------------------
Enter a complex number : 0+0j
False
------------------

Boolean Value into Specific Type

☞If we will convert boolen values(True or False) into specific type, what will be the output? Let's see an example.

Example :

a=int(True)
b=int(False)
print(a,b)
print("-------------------")
c=float(True)
d=float(False)
print(c,d)
print("-------------------")
e=complex(True)
f=complex(False)
print(e,f)
print("-------------------")
g=str(True)
h=str(False)
print(g,h)
Output
1 0
-------------------
1.0 0.0
-------------------
(1+0j) 0j
-------------------
True False