#Why this matters
Security engineers rarely rely on manual point-and-click work alone. You might write a 15-line Python script to scan lab logs for failed logins, automate an encoding check, or read an unfamiliar script left behind on a system.
Before you ever run a script you found, you must be able to read it and predict what it does. Every imperative program rests on three building blocks: variables to hold data, control flow to make decisions and repeat work, and functions to organise logic cleanly.
#Variables, types and expressions
A variable gives a readable name to a value in memory. In Python, = assigns a value to a name, while == tests whether two values are equal.
| Type | Example | Purpose |
|---|---|---|
int |
443 |
Whole numbers for ports, counts and sizes |
str |
"https" |
Text enclosed in quotes |
bool |
True or False |
Logical states used in decisions |
list |
[22, 80, 443] |
Ordered collection of items |
Types matter because operators behave differently depending on the type. Adding two integers (80 + 1) gives 81, whereas adding two strings ("80" + "1") joins them into "801". Mixing int and str with + raises a TypeError.
port = 443
service = "https"
is_encrypted = True
allowed_ports = [22, 80, 443]#Control flow: branching and loops
Programs normally run top to bottom, one line after another. Conditionals (if, elif, else) pick a branch based on a boolean expression using comparisons (==, !=, <, >=) and logical operators (and, or, not). Python groups the code inside each branch by indentation (typically four spaces).
- Read failed_countCheck if >= 5
- True -> return "lock"False -> check >= 3
- True -> return "warn"False -> return "allow"
Loops repeat a block of code without copying and pasting it:
- A
forloop steps through every element in a sequence, such as a list of ports or log lines. - A
whileloop repeats as long as its condition remainsTrue. You must update the variable checked bywhileinside the loop, or the loop runs forever.
Inside either loop, continue skips to the next iteration and break exits the loop early.
ports = [22, 80, 8080, 443]
for port in ports:
if port < 1024:
print(port, "privileged")
else:
print(port, "unprivileged")This loop checks four ports in order and classifies each one without repeating the if/else block four times.
#Functions, parameters and return values
A function wraps a task under a name using def. Inputs listed in parentheses are parameters, and the return keyword sends a result back to the caller and ends the function immediately.
def classify_attempts(failed_count):
if failed_count >= 5:
return "lock"
elif failed_count >= 3:
return "warn"
return "allow"
for count in [1, 3, 6]:
action = classify_attempts(count)
print(count, "->", action)Notice the difference between return and print():
print(action)displays text in the terminal for a human, then discards it.return "warn"hands the string back to the caller so the rest of the program can store it inaction, compare it or pass it to another function. If a function reaches its end withoutreturn, Python returnsNone.
Variables created inside a function belong to local scope and exist only while that function runs, keeping helper functions from accidentally overwriting variables elsewhere in your script.
#Common mistakes
- Using
=instead of==:=assigns a value, while==compares values. Writingif x = 5:causes aSyntaxErrorin Python (and silently overwrites variables in languages like C). - Printing instead of returning: Writing
print("lock")inside a helper function leaves callers receivingNone, which breaks later comparisons likeif action == "lock":. - Off-by-one thresholds: Confusing
>with>=, or forgetting thatrange(5)produces0, 1, 2, 3, 4rather than1to5, causes missed boundary checks. - Unchecked input types: Input read from a file or user prompt arrives as a
str. Comparing"443" < 1024raises aTypeErrorunless you convert it withint()first. - Running untrusted scripts to see what they do: Always trace control flow and function calls first in an isolated lab rather than executing unknown code on your host.
#Summary
- Variables bind names to typed values (
int,str,bool,list), and mismatched types change or break operations. - Conditionals (
if/elif/else) choose a path, whileforandwhileloops repeat actions cleanly. - Functions package reusable logic with parameters and pass results back to callers via
returnrather thanprint(). - Tracing code line by line lets you catch boundary bugs and understand unfamiliar scripts before running them.