bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Python/Foundations
Python•Foundations

Python Logical Operators

Logical operators are used to combine conditional statements. Python has three logical operators:

  • and - Returns True if both statements are true
  • or - Returns True if one of the statements is true
  • not - Reverses the result, returns False if the result is true

The and Operator

The and keyword is a logical operator, and is used to combine conditional statements. Both conditions must be true for the entire expression to be true.

a

The or Operator

The or keyword is a logical operator, and is used to combine conditional statements. At least one condition must be true for the entire expression to be true.

a

The not Operator

The not keyword is a logical operator, and is used to reverse the result of the conditional statement.

a

Combining Multiple Operators

You can combine multiple logical operators in a single expression. Python evaluates not first, then and , then or .

and

Truth Tables

Understanding how logical operators work with different values:

and Operator Truth Table

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or Operator Truth Table

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Using Parentheses for Clarity

When combining multiple logical operators, use parentheses to make your intentions clear and control the order of evaluation.

Example

temperature = 25

is_raining = False

is_weekend = True

if (temperature > 20 and not is_raining) or is_weekend:

  print("Great day for outdoor activities!")

Previous

Python Shorthand If

Next

Python Nested If