Notes
Categories

Logical Operators in Python [ English ]

< Prev Next >

1. Introduction

Logical operators in Python are used to combine multiple conditions and evaluate them as a single expression. They return a Boolean value (True or False).

They are mainly used in:

2. Types of Logical Operators

Python has three logical operators:

Operator Name Description
and Logical AND True if both conditions are True
or Logical OR True if at least one condition is True
not Logical NOT Reverses the result

3. Logical AND (and)

Definition

Returns True only if both conditions are True.

Truth Table

A B A and B
True True True
True False False
False True False
False False False

Example

a = 10

print(a > 5 and a < 20)
print(a > 5 and a < 8)

Output

True
False

4. Logical OR (or)

Definition

Returns True if at least one condition is True.

Truth Table

A B A or B
True True True
True False True
False True True
False False False

Example

a = 10

print(a > 5 or a < 8)
print(a < 5 or a < 8)

Output

True
False

5. Logical NOT (not)

Definition

Reverses the Boolean value.

Truth Table

A not A
True False
False True

Example

a = 10

print(not(a > 5))

Output

False

6. Using Logical Operators in Conditions

age = 20

if age >= 18 and age <= 60:
    print("Eligible")

7. Short-Circuit Evaluation

Python uses short-circuiting:

Example

print(False and True)   # second condition not checked
print(True or False)    # second condition not checked

8. Logical Operators with Non-Boolean Values

Logical operators can return actual values (not just True/False).

print(0 and 5)
print(5 and 10)

print(0 or 5)
print(5 or 10)

Output

0
10
5
5

9. Practical Example

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid credentials")

10. Important Points

11. Summary

< Prev Next >