Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free GIAC Python Coder GPYC Exam Questions

Last updated: · 12 practice questions with answers and explanations

Page: 1 / 8 Total 75 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Control Structures and Iteration

Skill tested: Select loop control flow that safely handles records and termination conditions.

A penetration tester is reviewing a Python script that reads one line at a time from a large scan-results file. Blank lines should be ignored, lines beginning with `#` should be skipped, and processing should stop at the first line containing the exact marker `END`. The file may not contain that marker. The current implementation uses nested conditionals and a numeric index, and it sometimes processes the marker as a result. Which approach most directly implements the required behavior while avoiding unnecessary index management?

Correct Answer: A. Iterate over the file object; break when a line, after removing its newline, equals `END`, and continue for blank or comment lines.
Explanation:

Direct iteration over a file processes lines sequentially without maintaining an index. `break` stops the loop as soon as the sentinel is reached, while `continue` skips only the current blank or comment line. Removing the line ending before comparison makes an exact marker comparison practical. The list-and-index approach adds memory and boundary risks, and `index

Question 2

New Single answer

Topic: Creation of Executables

Skill tested: Evaluate safe Python-to-Windows executable packaging and antivirus evasion claims.

A security team must deliver a Python-based Windows utility to an isolated lab workstation that does not have Python installed. The utility is authorized for internal testing, and the organization requires the build process to be reproducible and malware scanning to remain enabled. A colleague proposes changing executable bytes until antivirus products stop detecting the file, then distributing that version. Which response is the best engineering decision?

Correct Answer: C. Package the utility with a Windows executable-building workflow, test it in the target environment, and investigate detections through approved review rather than attempting signature evasion.
Explanation:

A packaging workflow can bundle a Python program and required runtime components for a target Windows environment, but the resulting executable still needs testing for dependencies, architecture, and deployment behavior. Antivirus detections should be handled through authorized analysis, code review, and approved security-vendor or organizational processes - not by altering bytes to evade detection. That proposal undermines the stated scanning requirement and is not a reliable or defensible build method. Renaming source does not compile or package it, and a batch file cannot supply a missing Python interpreter or dependencies.

Question 3

New Multiple answers

Topic: Data Analysis with Python

Skill tested: Use counters, sets, and frequency ranking to analyze log distributions.

An incident-response team has a text file containing one normalized source IP address per line, with occasional blank lines. Analysts need the number of distinct sources, the total number of recorded events, and the five most frequent sources, including counts. They want a concise in-memory analysis using Python's standard collection types; the file is small enough to fit in memory. Which two implementation choices meet the requirements? Select TWO.

Correct Answer: B. Build a `collections.Counter` from the nonblank addresses, use its length for distinct sources, and use its total count for events.; E. Build a `collections.Counter` from nonblank addresses and obtain the five highest-frequency entries with `most_common(5)`.
Explanation:

A `Counter` records each address's frequency. Its number of keys gives the distinct-source count, while summing its counts gives the total number of nonblank events. `most_common(5)` returns up to five address/count pairs in descending frequency order. A set discards duplicates and therefore cannot supply event totals or frequency rankings. Sorting raw addresses groups equal values but the final element is not necessarily the most frequent. Converting to a set before counting also loses the repeated events the analysis needs.

Question 4

New Single answer

Topic: Data Structures

Skill tested: Interpret byte indexing, UTF-8 decoding, and integer construction from binary data.

A packet-processing utility receives a two-byte unsigned field as `raw = bytes.fromhex("01 02")`. The protocol specifies that the field is big-endian. A developer needs the numeric value and must also produce the UTF-8 text represented by a separate byte sequence `b"caf\xc3\xa9"`. Which implementation correctly handles both requirements?

Correct Answer: D. Use `int.from_bytes(raw, "big")` and decode the text bytes with UTF-8.
Explanation:

`int.from_bytes(raw, "big")` interprets the first byte as the most significant byte, producing 258 for `01 02`. The separate bytes `b"caf\xc3\xa9"` contain the UTF-8 encoding of `café`, so UTF-8 decoding reconstructs that text. Little-endian interpretation produces a different integer, and Latin-1 would map the UTF-8 bytes individually rather than decode the multibyte character correctly. Decoding the numeric field treats binary data as text, while `int(raw)` does not perform the specified byte-order conversion.

Question 5

New Single answer

Topic: Database Interaction

Skill tested: Use parameterized SQL queries to safely filter database records.

A Python reporting script queries a SQLite database for events matching a source address entered by an analyst. The existing code constructs SQL by concatenating the address into the query string. The query must remain limited to matching records, support addresses containing punctuation, and avoid treating input as SQL syntax. Which change is most appropriate?

Correct Answer: A. Use a parameter placeholder in the SQL statement and pass the address separately through the database cursor's parameter argument.
Explanation:

Parameterized queries keep SQL structure separate from user-supplied values. With SQLite's Python interface, the program places a placeholder in the query and supplies the address as a separate parameter, allowing the driver to bind it as data. This handles punctuation safely and prevents input from changing the query's intended structure. Manual quote escaping is easy to implement incorrectly and varies with context. `repr()` is a Python representation, not a SQL-parameterization mechanism, and Base64 encoding neither binds the value nor makes concatenation safe.

Question 6

New Single answer

Topic: Exception Handling

Skill tested: Handle expected parsing errors without concealing unrelated program failures.

A log importer converts a field from each input row to an integer. Some rows are malformed, and the importer should record those rows as rejected while continuing with later rows. Database-write failures, programming errors, and other unexpected exceptions must not be silently treated as malformed input. Which exception-handling structure best meets this requirement?

Correct Answer: C. Catch `ValueError` around the integer conversion, record that row as rejected, and allow other exceptions to propagate or be handled at their proper boundary.
Explanation:

Converting an invalid numeric string with `int()` raises `ValueError`, so catching that specific exception around the conversion isolates the expected bad-input case. The importer can record the rejected row and proceed without masking failures from unrelated operations. Catching broad `Exception` around the whole importer may hide database and programming defects; catching `BaseException` is broader still and can intercept termination-related exceptions. A `finally` block runs for cleanup regardless of success or failure and is not an error-classification mechanism.

Question 7

New Multiple answers

Topic: Functions, Classes, and Objects

Skill tested: Design object behavior with instance state and correctly scoped methods.

A small analysis tool models network observations. Each observation should retain its own address and timestamp, while a method should return a formatted description for that particular observation. A developer has put the address in a class variable and written the formatter without an instance parameter, so observations overwrite one another and method calls fail. Which TWO changes correct the design using ordinary Python classes? Select TWO.

Correct Answer: A. Define the formatter as an instance method whose first parameter is `self`, and read the instance attributes through it.; E. Assign the address and timestamp to `self.address` and `self.timestamp` during instance initialization.
Explanation:

Per-observation data belongs on each instance, commonly assigned as `self.address` and `self.timestamp` in `__init__`. An instance method receives the instance as its first parameter, conventionally named `self`, and can format that instance's attributes. A class variable is shared unless shadowed, so it does not provide the intended independent state. A static method receives no automatic instance and cannot use `self` unless the instance is passed explicitly. Global state would couple observations and undermine the object's independent behavior.

Question 8

New Single answer

Topic: Network Interfaces

Skill tested: Implement reliable TCP client reads when responses may arrive in multiple segments.

A TCP client connects to an authorized test service that sends a response of a known length. The client currently calls `recv(expected_length)` once and assumes it receives the entire response. Under load, some responses appear truncated even though the server sends all bytes and keeps the connection open until the response is complete. Which client-side change addresses the root cause?

Correct Answer: D. Loop, requesting the remaining byte count and accumulating received chunks until the expected length is reached; treat an empty read as connection closure.
Explanation:

TCP provides a byte stream, not application-level message boundaries. A single `recv(n)` may return fewer than `n` bytes even when more data will arrive, so the client must accumulate chunks until it has the expected length. An empty byte string from `recv` indicates the peer has closed the connection, allowing the client to detect an incomplete response. Repeating the call only after an exception misses normal short reads. UDP does not provide TCP's reliable stream behavior, and nonblocking mode does not guarantee complete reads.

Question 9

New Multiple answers

Topic: Packet Analysis with Python

Skill tested: Use Scapy packet layers and filters to inspect captured traffic safely.

An analyst has a Scapy packet capture loaded as `pkts` and must report TCP packets whose destination port is 443, without sending or altering traffic. Some captured frames may not contain a TCP layer. The analyst also needs to inspect the destination IP address for each matching packet. Which TWO actions meet these requirements? Select TWO.

Correct Answer: B. Check that a packet has a TCP layer before accessing its TCP destination port, and access the IP layer when present to read its destination address.; E. Use a Scapy filter expression such as `tcp and dst port 443` to select the relevant captured packets.
Explanation:

Scapy's packet-filtering expressions can select packets matching TCP and destination port 443 from an existing capture. Layer checks such as testing for `TCP` before reading its fields prevent errors on packets without that layer; the analyst should similarly verify the relevant IP layer before accessing its destination address. Sending packets is unnecessary and would violate the requirement not to transmit or alter traffic. A packet list does not imply every frame contains TCP/IP, and `sr()` is an active send-and-receive operation rather than passive inspection.

Question 10

New Single answer

Topic: Python Basics

Skill tested: Manage file input and output reliably using context managers and explicit text encoding.

A command-line utility reads a UTF-8 text file containing hostnames, removes the line ending from each hostname, and writes normalized results to another file. The process may encounter an error while processing a line, but both files must still be closed. The utility must behave consistently on systems with different default text encodings. Which implementation choice is best?

Correct Answer: D. Open both files with `with`, specify UTF-8 encoding for text mode, and process lines inside the context-manager blocks.
Explanation:

A `with` statement ensures that file objects are closed when control leaves the block, including when an exception occurs. Explicitly selecting UTF-8 avoids behavior that depends on the host's default encoding. Text-mode iteration provides decoded strings, and removing the line ending can be done deliberately before writing normalized output. Without a context manager, an exception can bypass explicit close calls. Converting bytes with `str()` produces a representation such as `b'...'`, not the decoded hostname, while relying on platform defaults conflicts with the consistency requirement.

Question 11

New Single answer

Topic: Regular Expressions

Skill tested: Construct anchored regular expressions that validate complete IPv4 address strings.

A log-ingestion filter must accept only strings consisting of four decimal octets separated by literal periods. Each octet must be between 0 and 255, leading zeroes are permitted, and trailing text or whitespace must cause rejection. The filter is written with Python's `re` module. Which pattern best satisfies the requirements when used with `fullmatch()`?

Correct Answer: D. `r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}"`
Explanation:

The repeated octet expression in B constrains each decimal component to 0-255, and the escaped periods match literal separators. Repeating that component three times after the first yields exactly four octets; `fullmatch()` rejects any unmatched suffix or surrounding whitespace. Pattern A permits values such as 999. Pattern C uses unescaped dots, which match arbitrary characters, and does not restrict octet values. Pattern D describes only two octets. The selected octet expression permits `0` and leading-zero forms such as `00` under the stated requirements.

Question 12

New Multiple answers

Topic: Website Interaction

Skill tested: Maintain session cookies and submit form data through Python HTTP requests.

A web assessment script is authorized to interact with a staging application. It must first fetch a form page, retain the session cookie set by that response, then submit the form data to the supplied URL. The application may set additional cookies during the exchange. The team wants to use Python's `requests` library and avoid manually copying cookie headers between requests. Which TWO choices are appropriate? Select TWO.

Correct Answer: A. Create a `requests.Session`, use it for both the page request and form submission, and let it retain cookies.; C. Submit the form with the session's `post()` method and pass form fields using the `data` parameter.
Explanation:

A `requests.Session` persists cookies received from responses and uses them on subsequent requests to the same applicable scope, avoiding manual header handling. Sending form fields with the session's `post(..., data=...)` uses form-encoded request data, which is the conventional representation for standard HTML forms. Separate top-level calls do not share a global cookie jar. A `Set-Cookie` response header contains cookie-setting attributes and should not be copied wholesale as a request `Cookie` header. The `json` parameter sends JSON rather than ordinary form data.