Objective. Students write Python 3 functions that accept parameters, handle common data types, and return values, demonstrating readable code style consistent with PEP 8.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Python 3 is the dominant scripting language in cybersecurity work. Security analysts use it to automate log parsing, build network scanners, interact with APIs, and process large datasets of indicators of compromise. Unlike compiled languages, Python lets you prototype a tool quickly and run it immediately, which matches the pace of incident response and penetration testing. If you already know Bash, you will find Python familiar in logic but more expressive for complex tasks.
Python uses indentation — not curly braces — to define blocks of code. Four spaces per indent level is the standard. A missed or extra space is a syntax error, so consistency matters from the start.
A simple comparison between Bash and Python shows the same idea in two styles:
```
if [ "$status" = "open" ]; then
echo "Port is open"
fi
if status == "open":
print("Port is open")
```
Both check a condition and print a message. Python reads more like plain English and eliminates bracket syntax.
Strings hold text. In cybersecurity, strings carry hostnames, IP addresses, log lines, and file paths. Python strings are enclosed in single or double quotes and are immutable — you cannot change a character in place; you create a new string instead.
Integers and floats hold numeric values. Port numbers, byte counts, and timestamps are often integers.
Lists are ordered, mutable collections. Use them when you need a sequence you can change — for example, a list of flagged IP addresses that grows as you scan a log file.
Dictionaries are key-value stores. They are ideal for representing structured data: a dictionary can hold an alert record with keys like `"severity"`, `"source_ip"`, and `"timestamp"`. Keys must be unique within one dictionary.
Booleans (`True` / `False`) control logic. Many security checks return a boolean: is the hash known-malicious? Is the port reachable?
A `for` loop iterates over any sequence — a list of log entries, a range of port numbers, or characters in a string:
```python
for port in [22, 80, 443]:
print(f"Checking port {port}")
```
A `while` loop repeats as long as a condition is true. Use it when you do not know in advance how many iterations you need — for example, retrying a connection until it succeeds or a timeout is reached. Always make sure a `while` loop has a clear exit condition to avoid an infinite loop.
Functions package reusable logic. Define a function with the `def` keyword, give it a descriptive name, list parameters in parentheses, and end the line with a colon:
```python
def check_port_status(host, port):
"""Return True if the port appears in the allowed list."""
allowed = [22, 80, 443]
return port in allowed
```
Call it later: `result = check_port_status("10.0.0.1", 80)`
Good functions do one thing, have a descriptive name (lowercase with underscores), and include a docstring — the triple-quoted string immediately after `def` that explains purpose, parameters, and return value. Docstrings are not optional decoration; they are how teammates and future-you understand the code.
PEP 8 is the official Python style guide maintained at python.org. Following it makes code readable by any Python developer. Key rules for this lesson:
Pylint is a static analysis tool that scores your script against PEP 8 and common error patterns. A score of 7.0 or above out of 10 is the minimum passing bar for this lesson's refactoring exercise. Run Pylint from the VS Code terminal: `pylint your_script.py`.
All coding in this course is done inside your isolated Ubuntu VM. Never run scripts you find online directly on your host machine or on any network you do not have explicit written permission to test. Scripts that probe ports or manipulate files can cause unintended harm to live systems. Keep your VM snapshots current before experimenting — a snapshot lets you restore to a clean state if a script corrupts a file or fills disk space. These habits mirror professional standards: security practitioners test in controlled environments first.
The CompTIA Security+, CompTIA CySA+, and ISC2 CC exams all test your understanding that automation and scripting are core analyst skills. CySA+ in particular covers using scripting to support threat detection workflows. Understanding Python syntax and clean coding practices builds the foundation for every tool you will write throughout this program.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.