bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Python/Foundations
Python•Foundations

Python Logical Operators

Overview

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.

Example

Test if a

is greater than b, AND if c is greater than a

Formula

a = 200 b = 33 c = 500 if a > b and c > a:
print("Both conditions are True")

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.

Example

Test if a

is greater than b, OR if a is greater than c

Formula

a = 200 b = 33 c = 500 if a > b or a > c:
print("At least one of the conditions is True")

The not Operator

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

Example

Test if a

is NOT greater than b

Formula

a = 33 b = 200 if not a > b:
print("a is NOT greater than b")

Combining Multiple Operators

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

Example

Combining and, or, and not

age = 25 is_student = False has_discount_code = True if (age < 18 or age > 65) and not is_student or has_discount_code:
print("Discount applies!")

Truth Tables

Understanding how logical operators work with different values: and Operator Truth Table

Condition 1

Condition 2

Result

True

True

True

True

False

False

False

True

Previous

Python Else Statement

Next

Python Match