Python

In Python, Logical Operators are used to combine conditional statements. They allow you to perform complex checks by evaluating multiple expressions at once. Like comparison operators, logical operators always return a Boolean value (True or False).

They are the "connectives" of programming logic, essential for creating sophisticated decision-making structures in your code.

1. Theoretical Overview

There are three main logical operators in Python: and, or, and not.

The Three Logical Operators

OperatorDescriptionLogic
andReturns True if both statements are true.True and True $\rightarrow$ True
orReturns True if at least one statement is true.True or False $\rightarrow$ True
notReverses the result (True becomes False, and vice-versa).not(True) $\rightarrow$ False

Truth Table Reference

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

2. Key Concepts: Short-Circuit Evaluation

Python uses Short-Circuit Evaluation to optimize performance:

  • and Short-circuit: If the first expression is False, Python doesn't check the second one because the result is already guaranteed to be False.

  • or Short-circuit: If the first expression is True, Python doesn't check the second one because the result is already guaranteed to be True.

This is useful for preventing errors, such as checking if a number is not zero before dividing by it:

if count != 0 and (total / count) > 10:

3. Code Implementation

Python
# Sample Variables
has_license = True
age = 20
has_car = False

# Using 'and'
# Both conditions must be True
can_drive = age >= 18 and has_license
print(f"Can drive? {can_drive}")  # Output: True

# Using 'or'
# Only one condition needs to be True
needs_transport = has_car == False or age < 18
print(f"Needs transport help? {needs_transport}") # Output: True

# Using 'not'
# Flips the boolean value
is_weekend = False
print(f"Is it a working day? {not is_weekend}") # Output: True

# Combining multiple operators
# Logic: (True and True) or False -> True or False -> True
result = (age > 18 and has_license) or has_car
print(f"Complex Check: {result}")

4. Logical Operators with Non-Boolean Values

In Python, logical operators don't just work with True and False. They can work with any object. Python evaluates "empty" objects (like 0, "", [], None) as Falsy and almost everything else as Truthy.

  • x and y: Returns x if x is Falsy; otherwise, returns y.

  • x or y: Returns x if x is Truthy; otherwise, returns y.

Python
print(0 or "Python")    # Output: Python (because 0 is Falsy)
print("Hello" and 100)  # Output: 100 (because "Hello" is Truthy)
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now