🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Cybersecurity › Scripting for Cybersecurity › Lesson 4
TEC-CYBE44-05 · Lesson 4 · 14 clock hours · theory

Python Fundamentals: Syntax, Data Types, and Functions

Objective. Students write Python 3 functions that accept parameters, handle common data types, and return values, demonstrating readable code style consistent with PEP 8.

⚠ Pending professional review

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 Fundamentals: Syntax, Data Types, and Functions

Why Python for Cybersecurity?

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 Syntax Basics

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.

Common Data Types

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?

Control Flow: for and while Loops

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.

Defining and Calling Functions

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: Python's Style Standard

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`.

Safe Lab Practices

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.

Connecting to Security Certifications

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.

Key terms8

PEP 8The official Python style guide that specifies formatting rules such as indentation, naming conventions, and line length to make code consistently readable.
DocstringA triple-quoted string placed immediately after a function or module definition that describes its purpose, parameters, and return value.
ImmutableA data type whose value cannot be changed after it is created; Python strings and tuples are immutable, so operations on them produce new objects.
DictionaryA Python built-in data type that stores key-value pairs; keys must be unique and are used to retrieve their associated values quickly.
snake_caseA naming convention in which words are lowercase and separated by underscores, used in Python for function names and variable names per PEP 8.
PylintA static code analysis tool for Python that checks source code against PEP 8 style rules and common programming errors, producing a numeric score out of 10.
Return valueThe data a function sends back to the caller using the return statement; allows the result of a function's logic to be stored or used elsewhere in the program.
ParameterA variable listed inside the parentheses of a function definition that receives a value when the function is called, allowing the function to work with different inputs.
In class: Instructor-led walkthrough comparing equivalent Bash and Python snippets side-by-side so students transfer concepts rather than starting from zero. · Coding drills: students complete a structured set of 10 short exercises covering strings, lists, dictionaries, for loops, while loops, and function definitions — each with an automated assert-based test to self-check. · Refactoring exercise: students are given a working but poorly formatted Python script and must rename variables to be descriptive, add docstrings, and apply PEP 8 spacing rules, then explain their changes in a one-paragraph written reflection.
Materials: Ubuntu VM, Python 3 documentation (docs.python.org), PEP 8 style guide, VS Code with Pylint extension, course lab guide chapter 4
Check: Students pass all 10 automated assert tests and submit a refactored script with docstrings and PEP 8-compliant formatting confirmed by Pylint score of 7.0 or higher; both conditions required to pass.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Security+ — General Security Concepts / Scripting and Automation
1. Which of the following variable names is compliant with PEP 8 naming conventions for a local variable in Python?
CySA+ — Security Operations / Scripting and Automation
2. A security analyst writes a Python function that processes a list of log entries. What is the correct purpose of adding a docstring immediately after the def line?
Security+ — General Security Concepts / Scripting and Automation
3. A Python script contains the following code: ips = {"host_a": "192.168.1.10", "host_b": "192.168.1.20"} print(ips["host_a"]) What data type is ips, and what will print?
ISC2 CC — Security Concepts in Practice
4. Which statement best describes why Python strings are called immutable?
CySA+ — Security Operations / Scripting and Automation
5. An analyst has a Python script that works correctly but receives a Pylint score of 4.5 out of 10. Which of the following changes is most likely to raise the score toward the 7.0 passing threshold?
Security+ — General Security Concepts / Scripting and Automation
6. A while loop in a security scanning script has no exit condition other than a flag variable that is never updated inside the loop. What is the result?
ISC2 CC — Security Concepts in Practice
7. During a lab exercise, a student wants to test a Python network-scanning script. According to safe lab practices, what should the student do before running the script?
CySA+ — Security Operations / Scripting and Automation
8. A cybersecurity student writes the following function: def chk(h,p): a=[22,80,443] return p in a Which two PEP 8 and best-practice violations are present? (Choose the answer that identifies both.)
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.