You don't need a computer-science degree to script attacks and defences — you need about six Python building blocks. This lesson teaches them through the lens of security, so every idea comes with a reason a hacker cares.
Variables and strings: targets and payloads
Everything you work with — an IP, a URL, a password guess — is data in a variable.
target = '127.0.0.1'
port = 80
print(f'Scanning {target}:{port}')
That f'...' is an f-string — it drops variables straight into text. You'll use it constantly to build URLs and log lines.
Lists: hosts, ports and wordlists
A list holds many values in order — perfect for a batch of ports.
ports = [21, 22, 80, 443, 8080]
for port in ports:
print(f'Checking port {port}')
The for loop is the heart of automation: do the same thing to every item without repeating yourself.
Conditionals: deciding what matters
status = 'open'
if status == 'open':
print('Found something!')
else:
print('Closed, move on')
A scanner is really just a loop plus an if: try each port, and if it answers, flag it.
The six things to remember
| Block | What it does | Hacker use |
|---|---|---|
| Variable | Stores a value | Hold a target IP or hash |
| f-string | Text you can build | Assemble URLs, payloads |
| List | Ordered collection | Ports, hosts, wordlists |
for loop | Repeat over items | Scan every port |
if / else | Make a decision | Is this port open? |
| Function | Reusable block | Call scan(ip) many times |
Tip: Python groups code by indentation (4 spaces), not braces. A misaligned line is the number-one beginner bug — if you see an
IndentationError, check your spaces first.
Master these six and you can read most of the security scripts on GitHub.