View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding Boolean Operators in Python with Examples

Updated on 20/05/20254,585 Views

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.

What Are Boolean Operators in Python?

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:

How Do Boolean Operators Work in Python?

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.

  • For the and operator: if the first value is False, Python stops and returns it.
  • For the or operator: if the first value is True, Python stops and returns it.
  • The not operator simply inverts the Boolean value.

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.

What Are the Types of Boolean Operators in Python?

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 in Python

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 in Python

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 in Python

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

How Do Boolean Operators in Python Work With Conditional Statements?

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.

Using Boolean Operators in Python if Statement

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.

Using Boolean Operators in Python while Loop

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.

How to Use Boolean Operators in Python With Expressions?

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

Using Boolean Operators With Relational Operators

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.

Combining Boolean Expressions in Python

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.

How to Mix Boolean Operators With Objects in Python?

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.

Truthy and Falsy Values in Python

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.

Evaluation Order and Precedence Rules

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.

Practical Examples of Boolean Operators in Python

Let’s explore how Boolean operators help in writing concise and readable logic.

Flattening Nested if Conditions

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.

Checking Numeric Ranges

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

Using Boolean Operators in Chained Function Calls

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

Conclusion

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.

FAQs

1. What are Boolean operators in Python used for?

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.

2. Can Boolean operators in Python work with non-Boolean values?

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.

3. What is short-circuit evaluation in Python Boolean operators?

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.

4. How does the and operator behave in short-circuiting?

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.

5. How does the or operator behave in short-circuiting?

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.

6. What is the role of the not operator in Python?

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.

7. Can you combine Boolean and relational operators in Python?

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.

8. What are truthy and falsy values in Python?

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 {}.

9. What is the difference between and and or in Python?

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.

10. How do Boolean operators affect function chaining in Python?

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.

11. When should you use Boolean operators with other logical constructs?

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.

12. Can Boolean operators help flatten nested conditions in Python?

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.

13. Are Boolean operators case-sensitive in Python?

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.

14. Can you use Boolean operators inside list comprehensions?

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.

15. Do Boolean operators return only True or False 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.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.