For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Debugging logical errors in Python often leads you straight to expressions that don’t behave as expected. This is where understanding Boolean Operators in Python becomes critical. Whether you're checking multiple conditions, filtering values, or managing control flow, these operators control the very logic that drives your code.
Pursue Online Software Development Courses from top universities!
Boolean logic forms the backbone of decision-making in any Python program. From writing clean conditional statements to optimizing complex logical expressions, mastering Boolean operators equips you to write smarter, more efficient code. In this guide, we’ll explore these operators in-depth, backed by clear examples, truth tables, and real-world usage patterns.
Boolean operators are used to combine or modify Boolean values—True and False. They form the core of Python logical operations, making them crucial in decision-making expressions. Python supports three primary Boolean operators: and, or, and not.
These operators return Boolean results based on the truth values of the expressions they evaluate. When used in conditional statements or logical checks, they determine whether certain blocks of code should execute.
Let’s now look at their syntax and behavior. Python Boolean operators follow this simple syntax:
# and operator
condition1 and condition2
# or operator
condition1 or condition2
# not operator
not condition
They work with both Boolean values and general objects in Python. You can use them in if, while, and other control structures.
Level up your AI and Data Science skills with these awesome programs:
Python evaluates Boolean expressions using a concept known as short-circuit evaluation. This means it may skip evaluating the second operand if the first operand already determines the result.
Let’s understand this with some examples:
# Short-circuit with 'and'
x = False and print("Will not print")
# Short-circuit with 'or'
y = True or print("Will not print either")
print(x)
print(y)
Output:
False
True
Explanation: In the first expression, False and ... returns False immediately, skipping the print() call. Similarly, in the second line, True or ... returns True and skips the second operand. This behavior saves computation and prevents unwanted side effects.
There are three core Boolean operators in Python:
Operator | Description |
and | Returns True if both operands are True |
or | Returns True if at least one operand is True |
not | Inverts the Boolean value |
Let’s analyze each alongside examples, outputs, truth tables, and explanations.
The and operator checks two conditions and returns True only if both are true. It evaluates from left to right and short-circuits if the first operand is false. In such cases, it skips the second operand entirely. This makes it ideal when all conditions must be satisfied before continuing.
a = 5
b = 10
print(a > 0 and b > 0)
Output:
True
Explanation: Both a > 0 and b > 0 are True. The and operator returns True.
Truth Table for and:
A | B | A and B |
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
The or operator returns True if at least one of the conditions is true. It starts evaluating from the left and stops as soon as it finds a truthy value. If both operands are false, it returns the last one. This is useful when any one of multiple conditions can be acceptable.
x = -5
y = 15
print(x > 0 or y > 0)
Output:
True
Explanation: x > 0 is False, but y > 0 is True. Since one is True, the whole expression evaluates to True.
Truth Table for or:
A | B | A or B |
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
The not operator simply inverts the Boolean value of an expression. If the input is True, the result becomes False, and vice versa. It helps in reversing conditions or creating opposite logic paths. This operator always returns a clear Boolean result: True or False.
flag = True
print(not flag)
Output:
False
Explanation: The value of flag is True, but not negates it, so the output is False.
Truth Table for not:
A | not A |
TRUE | FALSE |
FALSE | TRUE |
Boolean operators power control flow. When combined with if and while, they decide which blocks of code should execute based on logic.
Let’s see how that works.
age = 20
has_id = True
if age >= 18 and has_id:
print("Eligible to vote")
else:
print("Not eligible")
Output:
Eligible to vote
Explanation: Both conditions are True, so the if block executes. This is a practical use of the and operator.
x = 1
while x < 5 and x != 3:
print(x)
x += 1
Output:
1
2
Explanation: The loop runs while x < 5 and x != 3. When x becomes 3, the second condition fails and the loop exits.
Boolean operators also work directly with expressions, especially those involving relational operators. These expressions often compare values using operators like >, <, ==, !=, >=, or <=. By combining such expressions with and, or, and not, you can build complex conditions that evaluate multiple criteria at once.
Using Boolean logic in expressions is common in conditionals, loops, and return statements. It lets you write more expressive, readable, and concise conditions that reflect real-world logic in a clean way.
Must Explore: How to Use While Loop Syntax in Python: Examples and Uses
Let’s look at some combinations using a table:
Expression | Result |
10 > 5 and 5 > 2 | TRUE |
4 < 3 or 2 < 5 | TRUE |
not (7 == 7) | FALSE |
print(10 > 5 and 5 > 2)
print(4 < 3 or 2 < 5)
print(not (7 == 7))
Output:
True
True
False
Explanation: These expressions mix relational and Boolean logic. Python evaluates each comparison and then combines the results using Boolean operators.
score = 85
attendance = 90
if score >= 80 and attendance >= 75:
print("Eligible for certificate")
Output:
Eligible for certificate
Explanation: Here, both conditions are combined with and. This kind of logic is common in grading and eligibility systems.
Python allows Boolean operators to work with general objects, not just Boolean values. This flexibility comes from how Python evaluates expressions in a logical context. When using and, or, or not, Python checks the "truthiness" of each operand instead of expecting only True or False.
Mixing objects with Boolean logic is powerful but requires care. It's essential to know what each operator returns and how Python short-circuits the evaluation. By mastering these details, you can write more expressive and efficient code.
Python treats certain values like 0, None, '', and [] as falsy. Understanding these helps avoid unexpected outcomes in conditional logic.
name = "Ankita"
if name and len(name) > 3:
print("Valid name")
Output:
Valid name
Explanation: Non-empty strings are truthy. Python treats them as True. An empty string, 0, None, or an empty list is falsy.
Python follows operator precedence rules. Among Boolean operators:
not is evaluated first
Then and
Then or
result = not True or False and True
print(result)
Output:
False
Explanation: First, not True becomes False, then False and True is False, and finally False or False is False.
Let’s explore how Boolean operators help in writing concise and readable logic.
This approach improves readability by reducing indentation. It helps maintain clear and concise control flow. Let’s look at an example:-
marks = 78
passed = True
if passed and marks >= 75:
print("Distinction")
Output:
Distinction
Explanation: Instead of writing nested if blocks, the and operator flattens the logic into one clean line.
Boolean operators simplify range checks into a single line. This avoids multiple if statements and makes conditions more expressive. Here’s an example for better understanding:-
number = 15
if 10 <= number <= 20:
print("In range")
Output:
In range
Explanation:: This is a chained comparison. Python evaluates it as 10 <= number and number <= 20.
Do check out: Operator Precedence in Python
Chaining logical checks with functions ensures only necessary calls are executed. It also prevents runtime errors through short-circuit evaluation. Check out this example for a clearer understanding:-def is_even(n):
return n % 2 == 0
def is_positive(n):
return n > 0
num = 8
if is_even(num) and is_positive(num):
print("Even and positive")
Output:
Even and positive
Explanation: Functions return Boolean values. Boolean operators combine their results for decisions.
Also Explore: Bool in Python
Mastering Boolean Operators in Python is key to writing reliable and logical programs. Whether you're building conditional checks, validating inputs, or simplifying complex decisions, these operators help structure code that reacts precisely to different scenarios. Understanding how and, or, and not behave, especially with short-circuiting and truthy/falsy values -can prevent hidden bugs and make your logic more predictable.
As you write more Python code, you'll find Boolean logic deeply integrated into loops, conditionals, and function evaluations. With practice, combining expressions using Boolean operators becomes second nature. Always remember to test edge cases and understand how evaluation order affects outcomes. That’s how you move from writing code that works to writing code that’s clean, safe, and smart.
Boolean operators in Python are used to combine or evaluate conditions in logical expressions. They help control program flow, especially in if, while, and loop statements, by returning either True or False.
Yes, Boolean operators can work with non-Boolean values. In such cases, Python evaluates the truthiness of the values, returning the actual operand instead of a strict Boolean True or False.
Short-circuit evaluation means Python stops checking further conditions once the result is determined. For example, in a and b, if a is False, b won’t be evaluated because the result is already False.
The and operator short-circuits if the first operand is false. It doesn’t evaluate the second operand since the final result will be false regardless of the second condition’s outcome.
The or operator short-circuits when the first operand is true. It immediately returns the first truthy value without evaluating the second operand, optimizing performance and avoiding unnecessary computation.
The not operator inverts the truth value of an expression. It turns True into False and vice versa, making it useful for creating negated conditions in logical checks or conditional branches.
Yes, you can combine Boolean and relational operators to form complex logical conditions. These combinations are common in if statements and loops to evaluate multiple relationships simultaneously.
Truthy values evaluate to True, and falsy values evaluate to False in a Boolean context. Common falsy values include 0, None, '', and empty collections like [] or {}.
and returns the first falsy operand or the last operand if all are truthy. or returns the first truthy operand or the last operand if all are falsy. Both follow short-circuit evaluation.
Boolean operators allow conditional chaining of function calls. Using and or or, you can control which functions get executed based on previous outcomes, reducing code complexity and avoiding deep nested if blocks.
Use Boolean operators with constructs like if, while, and ternary expressions to simplify conditional logic. They improve readability and reduce nested conditions when used effectively with expressions and truthy values.
Yes, combining Boolean operators can flatten deeply nested if statements. This makes code cleaner by replacing multiple if-else blocks with a single compound logical expression.
No, Boolean operators like and, or, and not are Python keywords and must be written in lowercase. Writing them in uppercase will result in a syntax error during execution.
Yes, Boolean operators can be used inside list comprehensions to filter items based on multiple conditions. This enhances the power and expressiveness of comprehensions in Python.
Not always. When used with non-Boolean operands, they return the actual operand based on truthiness evaluation. This behavior is often used in expressions for setting defaults or evaluating objects conditionally.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.