Skip to content

Latest commit

 

History

History
107 lines (79 loc) · 6.03 KB

File metadata and controls

107 lines (79 loc) · 6.03 KB

Python Statements & Control Flow

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.

Overview

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.

Learning Objectives

  • 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 for loops.
  • Build retry loops, listeners, and polling logic with while.
  • Generate numeric spans (port ranges, subnet octets) with range().
  • Control loop flow with break, continue, and pass.
  • Dispatch on data shape with the match statement (Python 3.10+).

Prerequisites

  • [[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.

Topics Covered

  • [[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

Practical Exercises

  • 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, and time.sleep().
  • Read a wordlist, continue past comment/blank lines, and request each remaining path.
  • Route a JSON command dict with a match statement in a mock C2 handler.

Security Applications

  • Iterating over targets — a for loop 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 while loop with a bounded attempt counter is how you handle a flaky target without hammering it.
  • Early exit on scope violationbreak and continue let a loop skip an out-of-scope host or stop entirely when a stop condition is hit.
  • Rate limiting — a for loop with a deliberate delay keeps a scan quiet and avoids degrading the target.

Common Mistakes

  • 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; use range(1, 1025) for ports 1–1024.
  • while loops with no exit condition — always bound retries with a counter or a timeout.
  • Deeply nested conditionals — prefer early return or continue to flatten the logic.
  • Using else on a loop without knowing what it means — it runs when the loop finishes without break, which surprises most readers.
  • Building a huge list in a comprehension when a generator expression would stream it.
  • Forgetting that continue skips the rest of the body, including any counter increment.

Best Practices

  • Prefer for item in iterable over indexing with range(len(...)).
  • Use enumerate() when you need the index, and zip() 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 while loops with a maximum attempt count or a deadline.
  • Use break/continue to reduce nesting rather than adding another indent level.
  • Add an explicit delay in any loop that generates network traffic.

Review Questions

  1. What is the difference between a for loop and a while loop, and when is each appropriate?
  2. When should you use a list comprehension rather than an explicit loop?
  3. What security issue can occur if a retry loop has no upper bound on attempts?
  4. How would you troubleshoot a loop that appears to skip every other element of a list?
  5. What does the else clause on a for loop do?
  6. Write a Python example that iterates over a port range and skips any port outside the authorized set.

Commands

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

References

Related Notes

  • [[List-Comprehensions|List Comprehensions]]
  • [[Readme|Python for Security Professionals]]

Navigation

  • Previous: [[Python-Comparison-Operators/Readme|3. Python Comparison Operators]]
  • Home: [[Readme|Course Home]]
  • Next: [[Methods-and-Functions/Readme|5. Methods & Functions]]