Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 2 - Control Flow operators Python Python Basics Python Programming: From Zero to Real-World Applications

Comparison and Logical Operators in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • All comparison operators
  • and, or, not with truth tables
  • Short-circuit evaluation

Comparison Operators

Terminalpython
5 == 5     # True
5 != 3     # True
5 > 3      # True
5 < 3      # False
5 >= 5     # True
5 <= 4     # False

# String comparison (alphabetical)
"apple" < "banana"   # True
"apple" == "apple"    # True

Logical Operators - Truth Tables

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

Short-Circuit Evaluation

Short-circuit
Python evaluates and left-to-right and stops at the first False. For or, it stops at the first True. This is useful for safe checks.
Terminalpython
# Safe division - avoids ZeroDivisionError
x = 0
if x != 0 and 10 / x > 1:  # x != 0 is False, so 10/x is never evaluated
    print("Safe!")

# Default values with or
name = input("Name: ") or "Anonymous"
# If input is empty (falsy), uses "Anonymous"

Practical Exercise

Test: 5 > 3 and 2 < 8
Test: True or False
Test: not True
Try: 0 or "default" (returns default)

Key Takeaways

  • 6 comparison operators: == != > < >= <=
  • and: both True. or: either True. not: inverts.
  • Short-circuit: and stops at False, or stops at True.
  • Use or for default values: x = input() or 'default'.
  • Strings compare alphabetically.
Previously: Lesson 09 covered if/elif/else.
Today: You learned: All comparison and logical operators explained.
Next: Lesson 11 covers for loops.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments