CodesCompiler
๐Ÿ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact ๐Ÿš€ Get Started Free

PYTHON - Booleans

Python - Booleans

Python Booleans (bool)

In Python,boolis a sub-type ofint type. A bool object has two possible values, and it is initialized with Python keywords,TrueandFalse.

Example

PYTHON CODE
>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)

A bool object is accepted as argument totype conversionfunctions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version ofcomplex()function.

If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.

Example

PYTHON CODE
a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)

On running this code, you will get the followingoutputโˆ’

PYTHON CODE
bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)

Python Boolean Expression

Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves acomparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison.

PYTHON CODE
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.

Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter.

Example

PYTHON CODE
# Check true
a = True
print(bool(a))
# Check false
a = False
print(bool(a))
# Check 0
a = 0.0
print(bool(a))
# Check 1
a = 1.0
print(bool(a))
# Check Equality
a = 5
b = 10
print(bool( a==b))
# Check None
a = None
print(bool(a))
# Check an empty sequence
a = ()
print(bool(a))
# Check an emtpty mapping
a = {}
print(bool(a))
# Check a non empty string
a = 'CodesCompiler'
print(bool(a))