Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

boolean
bool
python

What is boolean in Python?

Educative Answers Team

The python data type bool is used to store two values i.e True and False.

Bool is used to test whether the result of an expression is true or false.

Syntax

To check the boolean value of an expression or a variable, pass it as a parameter to the bool function:

print(bool(expression))

or

print(expression)
svg viewer

Where to use bool?

Bool can be used when there is a need to compare two or more values.

Comparison Operators

Here is the list of various comparison operators:

x == y  # x is equal to y
x != y  # x is not equal to y
x > y   # x is greater than y
x < y   # x is less than y
x >= y  # x is greater than or equal to y
x <= y  # x is less than or equal to y
#check if x and y are equal
print(3==4) 
print(bool(3==4))

#check if x and y are not equal
print(3!=4) 
print(bool(3!=4))

#check if x is greater than y
print(3>4) 
print(bool(3>4))

#check if x is less than y
print(3<4) 
print(bool(3<4))

#check if x is greater than or equal to y
print(3>=4)
print(bool(3>=4)) 

#check if x is less than equal to y
print(3<=4)
print(bool(3<=4)) 

Note: If an empty list, empty array, empty sequence, None, False, 0 or 0.0 is passed as a parameter to bool function it will always return false.

Simple application of bool

The following code checks if the number passed to the bool function is divisible by 3. It returns true if the value is divisible by 3 and false otherwise.

x=9
if(bool(x%3==0)):
  print(x,"is divisble by 3")
else:
   print(x,"is not divisble by 3")

RELATED TAGS

boolean
bool
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring