11.1 Python Essentials for the Cyber Test
Key Takeaways
- Python uses indentation (not braces) to define blocks — wrong indent is a syntax error or silent logic bug
- Lists are ordered and mutable (`append`, index, slice); dictionaries map keys to values with `d[key]` / `d.get(key)`
- Strings are immutable sequences — indexing and slicing work like lists, but you cannot assign into a character position
- Slice syntax is `seq[start:stop]` (stop exclusive) and `seq[start:stop:step]`; omit ends to mean start or end of the sequence
- On the Cyber Test, expect short trace questions: predict printed output or the final value of a list/dict after a few operations
The Cyber Test’s programming domain mixes language-agnostic ideas (variables, loops, functions) with language-flavored questions. Python appears often because its syntax is compact and because cyber workflows use it for scripting, parsing logs, and quick automation. You do not need to be a professional Python developer. You do need to read short snippets, respect indentation, and predict what lists, dictionaries, and strings do under a few operations.
This section focuses on the Python surface that shows up on aptitude-style items: structure by indentation, core collections, string handling, slicing, and tracing output. Pair it with Chapter 10 (variables, control flow, functions) — those concepts transfer; here the syntax and data structures are Python-specific.
Why Python Shows Up on a Cyber Aptitude Test
Cyber operators and defenders script repetitive tasks: pull fields from a CSV of alerts, filter IP addresses, rename files, call an API. Python is a common teaching and tooling language for that work. The exam is not asking you to write a full program from a blank page under a style guide. It is asking whether you can follow a short script the way you would follow a procedure — what happens on line 3, what is in the list after the loop, what does this slice return.
Treat every snippet as a tiny machine: inputs → operations → printed or returned result. Mentally step line by line. That habit is more valuable than memorizing obscure standard-library names.
Indentation Defines Structure
In many languages, curly braces { } mark blocks. In Python, indentation marks blocks. A for, if, while, def, or class line ends with a colon (:), and the following indented lines belong to that block.
x = 3
if x > 0:
print("positive")
x = x - 1
print("done")
Both print("positive") and x = x - 1 run only when the condition is true, because they share the same indent level under if. The final print("done") is dedented, so it always runs.
Exam traps around indentation
- Mixed indent under one header — If one statement under an
ifis indented and the next is not, only the indented line is conditional. - Empty block — Python requires at least one statement in a block; placeholders use
pass. - Tabs vs spaces — Mixing them can cause
IndentationError. On paper items, assume consistent spaces; on real systems, pick one style and stick to it.
Wrong indentation is not a style nit on this exam — it changes meaning or makes the snippet invalid.
Lists: Ordered, Mutable Sequences
A list holds an ordered collection of values. Create one with square brackets:
ports = [22, 80, 443]
hosts = ["web", "db", "jump"]
mixed = [1, "ok", True]
Indexing
Positions start at 0. ports[0] is 22; ports[2] is 443. Negative indices count from the end: ports[-1] is 443.
Common mutations
| Operation | Effect |
|---|---|
ports.append(8080) | Adds 8080 at the end |
ports[1] = 443 | Replaces the value at index 1 |
del ports[0] or ports.pop(0) | Removes the first element |
len(ports) | Number of elements |
Lists are mutable: the same list object can change contents over time. That matters for traces — after append, later lines see the longer list.
Trace example: list through a loop
nums = [1, 2, 3]
for n in nums:
nums.append(n * 10)
if len(nums) > 5:
break
print(nums)
Walk it carefully: start [1, 2, 3]. First iteration n=1, append 10 → [1, 2, 3, 10]. Next n=2, append 20 → [1, 2, 3, 10, 20]. Next n=3, append 30 → [1, 2, 3, 10, 20, 30], then len > 5 breaks. Printed result: [1, 2, 3, 10, 20, 30]. Modifying a list while iterating it is risky in real code; on exams it appears to test whether you simulate state instead of guessing.
Dictionaries: Key → Value Maps
A dictionary (dict) maps keys to values:
service = {"ssh": 22, "http": 80, "https": 443}
print(service["http"]) # 80
print(service.get("ftp", 21)) # 21 (default because key missing)
- Keys are typically strings or numbers; values can be any type (including lists or nested dicts).
service["ftp"]raisesKeyErrorif that key is absent;.get(key, default)returns the default instead.- Assign to add or update:
service["dns"] = 53. "http" in servicetests key membership (not values).
Trace example: dict updates
counts = {}
for ch in "aaba":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
After the loop: {'a': 3, 'b': 1} (key order in modern Python follows insertion order, but many exam items care about values, not print order).
Dictionaries shine in cyber-flavored vignettes: port → service name, username → role, IP → hit count. Recognize that lookup is by key, not by position like a list.
Strings: Immutable Text Sequences
Strings are sequences of characters. You can index and slice them like lists, but you cannot assign to an index (s[0] = "X" is illegal). To “change” a string, you build a new one.
msg = "ALERT"
print(msg[0]) # 'A'
print(msg.lower()) # 'alert' (new string; msg unchanged)
print("AL" in msg) # True
parts = "a,b,c".split(",") # ['a', 'b', 'c']
joined = "-".join(parts) # 'a-b-c'
Useful methods that appear in short items: .lower(), .upper(), .strip(), .split(), .startswith(), .endswith(), .replace(old, new).
Because strings are immutable, chaining methods always works on returned values:
raw = " Port 22 "
clean = raw.strip().lower()
# clean is "port 22"; raw still has spaces and capitals
Slicing: start, stop, step
Slice syntax works on lists and strings:
seq[start:stop] # from start up to (but not including) stop
seq[start:stop:step] # same, taking every step-th item
seq[:stop] # from the beginning
seq[start:] # through the end
seq[:] # shallow copy of a list / copy of a string
seq[::-1] # reverse
Worked slices
data = [10, 20, 30, 40, 50]
print(data[1:4]) # [20, 30, 40]
print(data[:3]) # [10, 20, 30]
print(data[2:]) # [30, 40, 50]
print(data[::2]) # [10, 30, 50]
print(data[::-1]) # [50, 40, 30, 20, 10]
word = "cyber"
print(word[1:4]) # 'ybe'
print(word[-3:]) # 'ber'
Stop is exclusive. The slice data[1:4] includes indices 1, 2, 3 — three elements, not four. That single rule causes many wrong answers.
Putting It Together: A Mini Trace
logs = ["ok", "fail", "ok", "fail", "ok"]
bad = []
for i, entry in enumerate(logs):
if entry == "fail":
bad.append(i)
label = "errors:" + str(len(bad))
print(label)
print(bad[:2])
print(logs[::2])
Simulation:
badcollects indices where the entry is"fail"→[1, 3].labelbecomes"errors:2".bad[:2]is[1, 3](both elements; stop 2 is exclusive but there are only two).logs[::2]takes even indices →["ok", "ok", "ok"].
If an item asks “what is printed last?”, answer ['ok', 'ok', 'ok'] (representation may use single or double quotes).
Exam Strategy for Python Snippets
- Draw a state table — columns for each variable; update row by row.
- Watch off-by-one on slices and ranges —
range(3)→ 0,1,2; slice stop exclusive. - Separate mutation from rebinding —
x.append(1)changes the list;x = x + [1]builds a new list (and may leave other aliases unchanged). - Read prints carefully — multiple
printcalls mean multiple lines of output; some questions ask only for the final print. - Do not invent libraries — if the snippet only uses lists and dicts, the answer will not require NumPy or pandas knowledge.
Master these patterns and Python items become systematic rather than mystical. The next section contrasts C++ syntax and debugging mindset — same aptitude goal, different surface syntax and error categories.
What does the following Python slice return for s = "NETWORK"? s[1:4]
After this code runs, what is the value of d? d = {"a": 1} d["b"] = d.get("b", 0) + 2 d["a"] = d["a"] + 1
Which statement about Python lists and strings is correct?
What is printed? vals = [2, 4, 6] vals.append(vals[0] + vals[-1]) print(vals[1:])