Skip to content

Latest commit

 

History

History
108 lines (78 loc) · 6.04 KB

File metadata and controls

108 lines (78 loc) · 6.04 KB

Python Comparison Operators

Comparison, logical, identity, and membership operators used to build conditions and control the flow of security scripts.

Part of the [[Readme|Python for Security Professionals]] course.

Overview

Comparisons are what turn raw data into decisions. In offensive and defensive tooling they drive scan logic (is this port open and in scope?), input validation (is this a legal port number?), response filtering (is the status a 2xx?), and allow/deny enforcement (is this token in the wordlist?). This module walks the operators from the simplest relational checks up through logical composition, identity, and membership.

Learning Objectives

  • Use >, <, ==, != and their inclusive variants correctly, including the boundary cases.
  • Express range checks cleanly with chained comparisons (e.g. 0 <= port <= 65535).
  • Combine conditions with and, or, not and exploit short-circuit evaluation for safe, fast gates.
  • Distinguish identity (is) from equality (==) and know when each is correct.
  • Test allow/deny lists and wordlists with in / not in using the right container.

Prerequisites

  • [[Python-Objects-and-Data-Structure-Basics/Readme|Python Objects & Data Structure Basics]] — the types being compared.
  • Familiarity with integers, strings, and the collection types.

Topics Covered

Work through these in order:

  1. [[Greater-Than-Operator]] — > threshold and upper-bound logic.
  2. [[Less-Than-Operator]] — < lower-bound and privileged-port checks.
  3. [[Equal-To-Operator]] — == exact matching (status codes, timing-safe token checks).
  4. [[Not-Equal-To-Operator]] — != anomaly and drift detection.
  5. [[Chained-Comparisons]] — range validation like 0 <= port <= 65535.
  6. [[Logical-Operators]] — and, or, not and short-circuit evaluation.
  7. [[Identity-Operators]] — is / is not vs ==, and the None idiom.
  8. [[Membership-Operators]] — in / not in for allowlists and wordlists.

Practical Exercises

  • Validate a user-supplied port with a chained comparison before opening a socket.
  • Classify a batch of HTTP status codes into success / redirect / client-error / server-error.
  • Gate an attack loop with compound and / not logic over in-scope, port-open, honeypot flags.
  • Screen a candidate password against a wordlist loaded into a set.

Security Applications

  • Port state and scope checks0 < port <= 65535 validates input before a socket is opened, and port < 1024 identifies privileged ports.
  • HTTP status classification200 <= status < 300 separates success from redirect and error, which is how content-discovery tools decide what counts as a hit.
  • Allowlists and blocklistshost in AUTHORIZED_SCOPE is the check that keeps a scan legal; using a set makes it O(1).
  • Short-circuit safety gatesif in_scope(host) and is_up(host): never probes a host that failed the scope check, because and stops at the first false value.
  • The None idiomif result is not None: correctly distinguishes "no result" from a legitimate empty or zero result.
  • Timing-safe comparison — plain == on secrets short-circuits at the first differing byte. Use hmac.compare_digest() for tokens, MACs, and password digests.

Common Mistakes

  • Using is instead of == for value comparison — is tests object identity and only works by accident for small integers and interned strings.
  • if x: when you mean if x is not None: — an empty list, an empty string, and 0 are all falsy, so a legitimate zero result is treated as missing.
  • Comparing str to int"443" == 443 is False; convert first.
  • Forgetting operator precedencenot a == b means not (a == b); parenthesise when in doubt.
  • Membership tests against a list where a set would be O(1).
  • Comparing floats with == — use math.isclose().
  • Comparing secrets with ==, leaking length and content through timing.

Best Practices

  • Use chained comparisons for range checks; they read like the mathematical notation.
  • Reserve is and is not for None, True, and False.
  • Order compound conditions so the cheapest and most restrictive test comes first.
  • Store allowlists and wordlists in a set for fast membership tests.
  • Use hmac.compare_digest() whenever comparing anything secret.
  • Extract complex boolean expressions into a well-named helper function.

Review Questions

  1. What is the difference between == and is, and when is each correct?
  2. When should you use a chained comparison rather than two conditions joined by and?
  3. What security issue can occur if a token is compared with == instead of hmac.compare_digest()?
  4. How would you troubleshoot a condition that unexpectedly treats a valid result of 0 as missing?
  5. Why is 443 in {80, 443} faster than 443 in [80, 443] on large collections?
  6. Write a Python example that validates a port number and rejects out-of-range input.

Commands

# Run any example script from this module
python3 example.py

# Quick REPL experiments with the operators
python3 -c 'print(0 <= 8080 <= 65535)'
python3 -c 'print(443 in {80, 443, 8080})'

References

Related Notes

  • [[Python-Statements-and-Control-Flow/Readme|Python Statements and Control Flow]] — where these conditions are used
  • [[Python-Objects-and-Data-Structure-Basics/Readme|Python Objects and Data Structure Basics]] — the types being compared
  • [[Readme|Python for Security Professionals]] — course home

Navigation

  • Previous: [[Python-Objects-and-Data-Structure-Basics/Readme|2. Python Objects & Data Structure Basics]]
  • Home: [[Readme|Course Home]]
  • Next: [[Python-Statements-and-Control-Flow/Readme|4. Python Statements & Control Flow]]