In Python, a Boolean value represents a True or False value.
Use a Boolean value: Boolean values are used in conditional statements or comparisons to control the flow of a program.
In Python, the Boolean data type is called bool, with the values True and False.
Note:- True behaves exactly like the integer 1, and False behaves exactly like the integer 0
There are only two Boolean values:
- True
- False
Booleans can be created in several ways:
1. Direct Assignment: You can directly assign a Boolean value.
is_user_active = True
is_completed = False
2. Using Comparison Operators:
- ==: Checks if two values are equal.
- !=:Checks if two values are not equal.
- >:Greater than.
- <: Less than.
- >=: Greater than or equal to.
- <=: Less than or equal to.
Example:
a = 25
b = 30
print(a == 5) # True
print(a > b) # False
3. Using Logical Operators:
and: If both conditions are true, then returns True.
or: If at least one condition is true, then return True.
not: Reverses the Boolean value.
Example:
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
What are Truthy and Falsy Values
In Python, many values can be implicitly converted to True or False in a Boolean context:
False values:
If the values are None, 0, 0.0, ‘ ‘ (empty string), [] (empty list), () (empty tuple), {} (empty dictionary).
True values:
If the values are not considered false, like non-zero numbers, non-empty strings, and collections.
Example:
if []:
print("This won't be printed because an empty list is Falsy.")
else:
print("This will be printed.")
Python Boolean – Interview Questions
Q 1: What is a Boolean in Python?
Q 2: Which Boolean values are supported in Python?
Q 3: What function is used to check Boolean values?
Q 4: Can non-Boolean values return Boolean results?
Q 5: Are Boolean values case-sensitive?
Python Boolean – Objective Questions (MCQs)
Q1. What are the two Boolean values in Python?
Q2. What will be the output of the following code?
x = 10
y = 5
print(x > y)
Q3. What is the data type of the result of a comparison operation in Python?
Q4. What will be the output of the following code?print(bool(0))
Q5. Which of the following values is considered False in a Boolean context?