Conditionals, loops, and comprehensions — the decision-making and iteration constructs that drive every Python scanner and automation script.
Part of the [[Readme|Python for Security Professionals]] course.
Control flow is the backbone of offensive tooling: you loop over a port range, break on the first open port, retry a connection until it comes online, and dispatch on the shape of a response. This module works through Python's conditionals (if/elif/else, nesting, and structural pattern matching) and its loops (for, while, range, and the break/continue/pass control statements), plus list comprehensions as a compact iteration idiom.
- Branch on scan results, status codes, and banners with
if/elif/else. - Structure dependent decisions cleanly and avoid deep nesting.
- Iterate hosts, ports, wordlists, and file lines with
forloops. - Build retry loops, listeners, and polling logic with
while. - Generate numeric spans (port ranges, subnet octets) with
range(). - Control loop flow with
break,continue, andpass. - Dispatch on data shape with the
matchstatement (Python 3.10+).
- [[Python-Comparison-Operators/Readme|Python Comparison Operators]] — the conditions that drive branching.
- [[Python-Objects-and-Data-Structure-Basics/Readme|Python Objects & Data Structure Basics]] — the collections you will iterate over.
- [[If-Statements|If Statements]] — the basic decision point
- [[Elif-Statements|Elif Statements]] — multi-way classification
- [[Else-Statements|Else Statements]] — default / fallback branches
- [[Nested-Conditionals|Nested Conditionals]] — dependent, layered decisions
- [[For-Loops|For Loops]] — iterate hosts, ports, and lines
- [[While-Loops|While Loops]] — retry loops and listeners
- [[Range-Function|Range Function]] — numeric spans and port ranges
- [[Loop-Control|Loop Control]] — break, continue, pass
- [[Match-Statement|Match Statement]] — structural pattern matching
- [[List-Comprehensions|List Comprehensions]] — compact iteration idiom
- Write a first-open-port scanner that
breaks on the first open port and prints "none open" via loop-else. - Build a bounded connection retry loop with
while, a counter, andtime.sleep(). - Read a wordlist,
continuepast comment/blank lines, and request each remaining path. - Route a JSON command dict with a
matchstatement in a mock C2 handler.
- Iterating over targets — a
forloop across an expanded CIDR is the backbone of any sweep; pair it with [[Ipaddress-Module|ipaddress]] rather than building addresses by string. - Processing scan results — branching on port state, service banner, or HTTP status to decide what to report and what to probe further.
- Filtering discovered assets — a list comprehension reduces a raw result set to just the in-scope, responsive hosts in one readable line.
- Retry and backoff loops — a
whileloop with a bounded attempt counter is how you handle a flaky target without hammering it. - Early exit on scope violation —
breakandcontinuelet a loop skip an out-of-scope host or stop entirely when a stop condition is hit. - Rate limiting — a
forloop with a deliberate delay keeps a scan quiet and avoids degrading the target.
- Mutating a list while iterating over it — elements are silently skipped. Iterate over a copy, or build a new list.
- Off-by-one with
range()—range(1, 1024)stops at 1023; userange(1, 1025)for ports 1–1024. whileloops with no exit condition — always bound retries with a counter or a timeout.- Deeply nested conditionals — prefer early
returnorcontinueto flatten the logic. - Using
elseon a loop without knowing what it means — it runs when the loop finishes withoutbreak, which surprises most readers. - Building a huge list in a comprehension when a generator expression would stream it.
- Forgetting that
continueskips the rest of the body, including any counter increment.
- Prefer
for item in iterableover indexing withrange(len(...)). - Use
enumerate()when you need the index, andzip()to walk two sequences together. - Keep loop bodies short; extract the work into a named function.
- Use a comprehension when it fits on one or two lines, and a loop when there is branching or error handling.
- Always bound
whileloops with a maximum attempt count or a deadline. - Use
break/continueto reduce nesting rather than adding another indent level. - Add an explicit delay in any loop that generates network traffic.
- What is the difference between a
forloop and awhileloop, and when is each appropriate? - When should you use a list comprehension rather than an explicit loop?
- What security issue can occur if a retry loop has no upper bound on attempts?
- How would you troubleshoot a loop that appears to skip every other element of a list?
- What does the
elseclause on aforloop do? - Write a Python example that iterates over a port range and skips any port outside the authorized set.
python3 script.py # run a control-flow script
python3 -c "print(list(range(20, 26)))" # inspect a range
python3 --version # confirm 3.10+ for match/case- Python docs — More Control Flow Tools
- Python docs — match statements
- Real Python — Conditional Statements
- [[List-Comprehensions|List Comprehensions]]
- [[Readme|Python for Security Professionals]]
- Previous: [[Python-Comparison-Operators/Readme|3. Python Comparison Operators]]
- Home: [[Readme|Course Home]]
- Next: [[Methods-and-Functions/Readme|5. Methods & Functions]]