6️⃣ Boolean
In programming booleans play important role. Booleans represents any one value from two values i.e. True or False. We have already studied that True and False are python keywords. True value represents correctness, similarly False value represents falseness in a condition or statement. Variables containing boolean values are of <class ‘bool’> type.
Below are some valid boolean datatypes examples
💻 Example:
1 2 3 4 | a=True
print(type(a))
b=False
print(type(b))
|
✅ Output:
<class 'bool'>
<class 'bool'>
Invalid boolean datatypes
💻 Example:
1 2 3 4 | a=true
print(a)
b=false
print(b)
|
✅ Output:
NameError: name 'true' is not defined
NameError:name 'false' is not defined
We know that python comparison operators also returns response in boolean values.
💻 Example:
1 2 3 4 5 | a=10
b=15
print(a>b)
print(a<b)
print(a==b)
|
✅ Output:
False
True
False
There is bool() method present in python which converts variable in to boolean form (True or False). Note: If a variable containing values like zero, None or empty datatype, then its boolean form will always be False.
Variable containing values:
💻 Example:
1 2 3 4 5 6 | a=10
print(bool(a))
b='hello'
print(bool(b))
mylist=['pen','book','ink']
print(bool(mylist))
|
✅ Output:
True
True
True
Variable containing empty datatypes
💻 Example:
1 2 3 4 5 6 7 8 9 10 | mylist=[]
print(bool(mylist))
mydict={}
print(bool(mydict))
myvar=None
print(bool(myvar))
b=''
print(bool(b))
marks=0
print(bool(marks))
|
✅ Output:
False
False
False
False
False
In this way we can convert any variables in to boolean form using bool() keyword.
Here are the quick notes on above topic:
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What is boolean in Python?
How do you create a boolean variable in Python?
What is the use of bool() function?