Google Cybersecurity Certificate, Course 7: Automate Cybersecurity Tasks with Python (Study Notes)

    Plain-English notes on Python basics, loops, functions, strings, regular expressions, files, debugging and automating log analysis. Includes practice questions with explanations.

    Independent study aid. Not affiliated with or endorsed by Google or Coursera. All explanations, code and questions are original. Confirm current course content on the official Coursera page.

    1. Course overview

    Security teams face huge volumes of repetitive work: scanning logs, checking lists of addresses, updating files. Python lets an analyst write short scripts that do this reliably in seconds. This course teaches enough Python to read data, make decisions in code, and automate a few everyday tasks.

    Core idea

    If you do a task more than a few times, a small script can do it for you.

    Builds on

    Log and incident ideas from Course 6.

    Study tip

    Type every example yourself and change one thing to see what breaks. Free practice: official Python tutorial.

    2. Weekly breakdown (study plan)

    A suggested four-part plan grouped by topic. Follow the official course order for graded work, as week titles may differ.

    Part 1: Python basics and decisions
    • A variable stores a value: user = "asha". Core data types: string (str), integer (int), float, boolean (True/False).
    • Operators: arithmetic (+ - * /), comparison (== != > <), logical (and or not). Note = assigns; == compares.
    • Conditionals choose a path:
    failed = 7
    if failed >= 5:
        print("Possible brute force")
    elif failed > 0:
        print("Watch")
    else:
        print("Normal")

    Python uses indentation (spaces) to show which lines belong together.

    Part 2: Loops, lists and functions
    • A list holds items in order: ips = ["10.0.0.5", "10.0.0.9"]. Count from zero: ips[0] is the first. Dictionaries pair keys with values.
    • A for loop repeats once per item; a while loop repeats while a condition is true (take care to avoid an endless loop).
    • A function is a reusable block with a name; it can take parameters and return a result.
    def is_suspicious(count, limit=5):
        return count >= limit
    
    for ip in ips:
        print(ip)

    Built-ins such as len(), print(), sorted(), and libraries you import (such as re, csv, os) save you from writing everything yourself.

    Part 3: Strings, regex and files
    • Strings are text. Useful methods: .lower(), .strip(), .split(","), .replace(), .startswith(). Indexing and slicing pick out parts.
    • Regular expressions (regex) describe text patterns. Python’s re module offers re.search and re.findall. Test patterns at regex101.
    PatternMatches
    \dOne digit
    \d+One or more digits
    \wLetter, digit or underscore
    .Any character
    [A-Z]One uppercase letter
    \d{1,3}One to three digits
    • Files: use with open("log.txt") as f: so the file closes automatically. Read by line with for line in f:; write using mode "w" (overwrite) or "a" (append).
    Part 4: Debugging and automating log analysis
    • Error types: syntax (broken grammar, code will not run), runtime (crashes while running, e.g. FileNotFoundError), logic (runs but gives wrong results).
    • Read the traceback from the bottom up: the last line names the error, the lines above show where.
    • Debug tactics: add print() checks, test small pieces, and use try/except to handle expected problems gracefully.
    • Automation pattern: read lines, extract fields with regex or split, count or compare against a list, print or save a summary.
    • Safety: test scripts on copies of data; never hard-code passwords; only run scripts on systems you are authorised to use.

    3. 15 must-know terms

    TermPlain meaning
    VariableNamed container for a value
    Data typeKind of value (text, number, True/False)
    StringText in quotes
    ListOrdered collection of items
    DictionaryCollection of key and value pairs
    Conditionalif/elif/else decision
    LoopRepeats code (for, while)
    FunctionReusable named block of code
    Parameter / argumentInput a function receives
    Return valueResult a function gives back
    Library / modulePre-written code you import
    Regular expressionPattern for matching text
    IterationOne pass through a loop
    ExceptionError raised while running
    DebuggingFinding and fixing mistakes

    4. Three worked examples

    Example 1: Update an allow list

    Scenario: remove retired devices from the list of approved IP addresses.

    allow_list = ["10.0.0.5", "10.0.0.9", "10.0.0.12"]
    remove_list = ["10.0.0.9"]
    
    for ip in remove_list:
        if ip in allow_list:
            allow_list.remove(ip)
    
    print(allow_list)   # ['10.0.0.5', '10.0.0.12']

    Why the check? .remove() raises an error if the item is missing, so test first with in.

    Example 2: Count failed logins by IP

    import re
    from collections import Counter
    
    pattern = r"Failed password.* from (\d{1,3}(?:\.\d{1,3}){3})"
    counts = Counter()
    
    with open("auth.log") as f:
        for line in f:
            match = re.search(pattern, line)
            if match:
                counts[match.group(1)] += 1
    
    for ip, n in counts.most_common(5):
        print(ip, n)

    How it works: the regex captures the IP after the words “Failed password”; Counter tallies each one; most_common(5) shows the top five. The exact pattern depends on your log format, so check a sample line first.

    Example 3: A reusable, safer script

    def flag_ips(counts, limit=5):
        return [ip for ip, n in counts.items() if n >= limit]
    
    try:
        with open("auth.log") as f:
            lines = f.readlines()
    except FileNotFoundError:
        print("Log file not found. Check the path.")
        lines = []

    Takeaway: a function with a default limit can be reused; try/except turns a crash into a clear message.

    5. Common mistakes

    • Using = instead of == in a condition.
    • Wrong indentation. Code that looks right can belong to the wrong block.
    • Off-by-one with lists. The first item is index 0, and the last of five is index 4.
    • Forgetting to convert types. Text read from a file is a string; use int() before comparing numbers.
    • Overwriting a file by accident. Mode "w" erases existing content; use "a" to add.
    • Over-trusting a regex. A pattern may match too much or too little; test on real sample lines.
    • Ignoring the traceback. The last line usually tells you the problem.

    6. 10 practice questions (tap to reveal)

    Q1. What is the difference between = and ==?

    = assigns a value to a variable; == compares two values and gives True or False.

    Q2. What does this print: x = 3 then if x > 5: print("A") else print("B")?

    B. 3 is not greater than 5, so the else branch runs.

    Q3. Given ips = ["a", "b", "c"], what is ips[1]?

    “b”. Indexing starts at 0.

    Q4. When would you use a while loop instead of a for loop?

    When you do not know in advance how many repeats are needed and want to continue until a condition changes, such as retrying until a task succeeds.

    Q5. Why write a function for a task you repeat?

    It avoids copying code, makes changes easy in one place, and gives the task a clear name.

    Q6. What does " admin ".strip().lower() return?

    “admin”. strip() removes surrounding spaces and lower() makes it lowercase.

    Q7. What does the regex \d{1,3} match?

    One to three digits in a row, such as 7, 42 or 255. It is a building block for matching parts of an IPv4 address.

    Q8. Why use with open(...) as f?

    The file is closed automatically, even if an error occurs, which avoids leaks and locked files.

    Q9. A script runs without errors but reports wrong totals. What kind of bug is that?

    A logic error. Add print() checks at each step and test with a tiny known input.

    Q10. Why might a log-analysis script wrap file reading in try/except?

    To handle expected problems such as a missing file or no permission, and to show a clear message instead of crashing.

    7. YouTube search links

    8. One-screen revision summary

    • Basics: variables, types (str, int, float, bool); = assigns, == compares.
    • Decisions: if/elif/else; indentation defines blocks.
    • Collections: lists (index from 0), dictionaries (key and value).
    • Loops: for (known items), while (until condition changes).
    • Functions: def, parameters, return; reuse and import libraries.
    • Strings: strip, lower, split, replace.
    • Regex: \d, \w, +, {n,m}, re.search, re.findall.
    • Files: with open; “r” read, “w” overwrite, “a” append.
    • Debug: read traceback bottom up; print checks; try/except.
    • Automation pattern: read, extract, count or compare, report.

    9. What you should be able to do

    ← Back to hub

    Educational summary for learners; not affiliated with Google or Coursera. Verify details against official course materials. Last reviewed: October 2026.