UnixDroid

Lesson 3 of 12 · 7 min

Python basics through a hacker's lens

You don't need a CS degree to script security tools. Here are the six Python building blocks that matter, each with a reason a hacker cares.

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

BlockWhat it doesHacker use
VariableStores a valueHold a target IP or hash
f-stringText you can buildAssemble URLs, payloads
ListOrdered collectionPorts, hosts, wordlists
for loopRepeat over itemsScan every port
if / elseMake a decisionIs this port open?
FunctionReusable blockCall 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.

Try it yourself
  1. Make a list of five ports and loop over them, printing each.
  2. Add an if that prints 'web port!' when the port is 80 or 443.
  3. Rewrite the print using an f-string that shows the port number.
No Linux machine? Practise in the free online terminal

Quick check

What does Python use instead of curly braces to group a block of code?

Need a hint?

It's about the spaces at the start of a line.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →