GIAC GPYC Exam Dumps & Practice Test Questions
Which two Python data types are immutable, meaning their contents cannot be changed once initialized?
A. List
B. Tuple
C. Set
D. String
E. Dictionary
Correct Answers: B, D
In Python, understanding the distinction between mutable and immutable data types is essential for writing robust, error-free code. Mutable objects can be modified after they are created, while immutable objects cannot be changed once they are initialized. This property affects how variables behave when passed to functions, stored in sets, or used as dictionary keys.
Let’s examine the immutable types among the choices:
Tuples (Option B) are a classic example of immutable data types. A tuple is an ordered sequence, much like a list, but once it is created, you cannot add, remove, or modify its elements. This makes tuples ideal for storing fixed collections of items such as coordinates, configuration options, or static datasets. Due to their immutability, tuples are also hashable, which means they can be safely used as keys in dictionaries and elements in sets.
Strings (Option D) are also immutable. When you attempt to modify a string—for example, through concatenation or replacement—Python doesn't change the original string. Instead, it creates a new string object in memory and assigns it to the variable. For example:
The original "data" remains unchanged. This immutability helps improve performance and memory safety.
Now let’s explore the mutable data types:
List (Option A): Lists are mutable. You can append, delete, or change elements dynamically. While versatile, they cannot be used as dictionary keys or stored in sets, as mutability disqualifies them from being hashable.
Set (Option C): Sets store unique items and are also mutable. Elements can be added or removed, making them unfit for use as keys or for caching in hash-based data structures.
Dictionary (Option E): Dictionaries are mutable as well. Their key-value pairs can be added, removed, or altered. Although the keys in a dictionary must be immutable (like strings or tuples), the dictionary itself can be freely modified.
In conclusion, Tuples and Strings are the two immutable data types among the listed options. Their fixed nature makes them reliable and efficient in scenarios where data integrity and performance are critical.
Which two Python constructs are commonly involved in managing exceptions within a try-except block?
A. try()
B. except()
C. finally()
D. raise()
E. catch()
Correct Answers: C, D
Python handles runtime errors using structured exception handling via keywords like try, except, finally, and raise. This allows developers to detect and gracefully recover from unexpected conditions, such as file errors or invalid input. Understanding which of these constructs are part of exception control flow is key for writing resilient code.
Let’s start with finally (Option C). Although it is not a function—despite being written here with parentheses—it is a crucial keyword in Python's exception-handling architecture. The finally block contains code that should always execute, whether or not an exception occurred in the preceding try block. This is especially useful for cleanup activities such as closing a file, releasing network connections, or logging execution status. Here’s a simple example:
raise (Option D) is another integral part of Python’s error-handling system. Unlike finally, raise is a function-like keyword that is used to manually trigger exceptions. You can use it to halt execution and alert the program that an error has occurred. This is particularly useful for enforcing constraints:
This line stops execution and transfers control to an appropriate except block if one exists.
Now, why are the other options incorrect?
try() (Option A) and except() (Option B) are invalid because try and except are keywords, not functions. They are used without parentheses to denote blocks of code that may raise or handle exceptions.
catch() (Option E) is not even part of Python syntax. While familiar to developers from Java or C++, Python uses except instead of catch.
In summary, although Python’s exception-handling architecture uses keywords, the only construct among the options that acts like a function (triggering exceptions) is raise, and finally is essential for cleanup operations. Therefore, C and D are the correct answers.
Which two Python libraries are most commonly used for making HTTP requests and interacting with web APIs? (Choose two.)
A. http
B. requests
C. json
D. urllib
E. smtp
Correct Answers: B, D
Explanation:
When working with web APIs or external web services in Python, developers need reliable libraries that support HTTP communication, such as sending GET or POST requests, handling responses, and managing headers or cookies. The two most widely used libraries for this purpose are requests and urllib.
Option B (requests) is a powerful and widely adopted third-party library designed to simplify HTTP interactions. It abstracts much of the complexity involved in sending HTTP requests and interpreting responses. With requests, tasks such as form submissions, file uploads, and authentication become more straightforward. For instance:
The requests library also handles session persistence, redirects, and content encoding automatically. Because of its simplicity and readability, it’s a favorite among Python developers and is commonly used in production systems.
Option D (urllib) is part of Python's standard library and offers lower-level HTTP capabilities via modules like urllib.request and urllib.parse. Although less elegant than requests, urllib remains a valid choice for developers looking to avoid external dependencies. A basic example of its usage looks like this:
Option A (http) refers to Python’s http.client module. While technically usable for HTTP communication, it's considered too low-level and is rarely preferred for typical use cases due to the complexity involved in manually managing connections and headers.
Option C (json) is used for parsing and generating JSON data—common in API responses—but it doesn't make HTTP requests. It is often used alongside requests or urllib, but not as a networking tool.
Option E (smtp), short for smtplib, is intended for sending emails using the Simple Mail Transfer Protocol. It serves an entirely different purpose and is unrelated to HTTP or API requests.
In summary, requests and urllib are the most suitable and widely-used libraries in Python for sending HTTP requests and interacting with web services. Requests is especially preferred for its user-friendliness, while urllib offers a no-dependency alternative from the standard library.
What are two effective techniques to defend a Python web application against code injection attacks? (Choose two.)
A. Use parameterized SQL queries
B. Manually escape user input
C. Use the eval() function for dynamic code operations
D. Validate and sanitize all user-supplied input
E. Skip input validation for better user experience
Correct Answers: A, D
Explanation:
Code injection is a serious threat to the security of web applications, including those written in Python. Attackers attempt to inject malicious code through input fields, URLs, or headers with the goal of executing unintended commands on the server. Two best practices that directly counter this threat are parameterized queries and input validation/sanitization.
Option A refers to using parameterized queries (also known as prepared statements) when interacting with a database. Rather than dynamically building SQL strings with user input—which exposes the application to SQL injection—parameterized queries separate the SQL logic from the data. For example:
This approach ensures that user input cannot be interpreted as part of the SQL command, effectively neutralizing a primary injection vector.
Option D, which emphasizes validating and sanitizing user input, is another critical defense layer. Validation involves checking that input matches expected formats—such as ensuring an email contains “@” or that a number falls within a certain range. Sanitization involves cleaning the input to remove or escape harmful characters. Together, these steps minimize the risk of attackers inserting executable code or scripts into fields that are later rendered or executed.
On the other hand:
Option B (manually escaping input) might seem useful, but it’s risky. Manual escaping is prone to human error and inconsistencies. It's much better to use frameworks or libraries that handle escaping automatically and consistently.
Option C (using eval()) is dangerous. It executes any string passed to it as Python code, so using it with unsanitized input is like handing full control of your application to an attacker. It should be avoided unless absolutely necessary and only with trusted input.
Option E (ignoring input validation) is a critical mistake. Even if it may seem to enhance user convenience, it exposes the application to a wide range of vulnerabilities, including code injection, cross-site scripting (XSS), and data corruption.
To summarize, parameterized queries and input validation/sanitization are industry-standard practices that provide strong, layered defense against code injection attacks in Python web applications.
Which two Python data structures are specifically designed to handle collections of items with unique values? (Select two.)
A. List
B. Tuple
C. Set
D. Dictionary
E. String
Correct Answers: C, D
Explanation:
When working with collections in Python, ensuring uniqueness can be a key requirement in many applications—such as removing duplicates or maintaining unique identifiers. Python offers several data structures, but Set and Dictionary are the two that enforce uniqueness naturally and by design.
Set (Option C) is a built-in data structure explicitly designed for storing unordered collections of unique elements. If you attempt to insert duplicate values into a set, Python automatically filters them out. For instance:
Sets are useful for operations such as union, intersection, and difference, which rely on unique membership. Because of their internal implementation using hash tables, sets offer fast membership testing, making them a practical choice when uniqueness and performance are both important.
Dictionary (Option D), though typically used for storing key-value pairs, enforces uniqueness of keys. While the values can be duplicated, each key in a dictionary must be unique. If the same key is used more than once, the last assignment overwrites the earlier one:
This ensures that each identifier (key) maps to a single value, maintaining a unique reference model.
Now let’s examine the incorrect options:
List (Option A) is ordered and mutable but allows duplicates. Lists do not offer any built-in enforcement of uniqueness, and extra logic (like converting to a set) is needed to remove duplicates.
Tuple (Option B) is immutable and ordered, but it also allows duplicate elements. While it’s useful for fixed collections, it doesn't provide any mechanism for ensuring unique items.
String (Option E) is an immutable sequence of characters. Like lists and tuples, it does not restrict repeated elements (e.g., repeated letters) and is not used for unique collections.
In conclusion, when managing collections where uniqueness is a core requirement, Set and Dictionary are the most appropriate structures in Python. Sets enforce uniqueness of elements, while dictionaries enforce uniqueness of keys.
Which two Python functions are used to directly perform file system operations such as modifying or creating files and directories? (Select two.)
A. os.path.join()
B. os.remove()
C. file.write()
D. os.mkdir()
E. str.format()
Correct Answers: B, D
Explanation:
Manipulating the file system in Python involves operations like creating directories, removing files, renaming, or checking for file presence. Python’s built-in os module provides several such utilities that allow programs to interact directly with the operating system’s file structure.
os.remove() (Option B) is one such function that allows you to delete files from the system. This function takes the file path as its argument and removes the corresponding file. If the file does not exist or if the path refers to a directory rather than a file, it raises an error. It is commonly used in scripts that clean up temporary or obsolete files.
os.mkdir() (Option D) is used to create a new directory. This function also requires a path as its argument and creates a directory at that location. If the specified directory already exists or if intermediate directories in the path are missing, it raises an exception unless handled properly. This function is critical when organizing file storage into structured folders for logging, user uploads, or project output.
Let’s explore the incorrect choices:
os.path.join() (Option A) is helpful for constructing valid file paths, ensuring platform independence. While essential for working with file systems, it does not create or modify files or directories—it merely builds paths as strings.
file.write() (Option C) is not a standalone function but rather a method used after opening a file with open(). It writes content to a file but does not manipulate the file system structure itself (e.g., does not create directories or delete files).
str.format() (Option E) is a string manipulation method used to insert variables into formatted strings. It has no role in file system management but might be useful in naming files or directories dynamically.
In summary, os.remove() and os.mkdir() are the correct answers because they directly manipulate the file system by allowing the creation and deletion of files and directories.
Which two modules in Python are used for performing regular expression pattern matching? (Choose 2.)
A. os
B. re
C. regex
D. string
E. json
Correct Answers: B, C
Explanation:
Regular expressions are a key part of many programming tasks involving pattern recognition in text, such as validating input, parsing logs, or extracting structured data from unstructured content. Python offers robust support for regular expressions through both its standard library and external modules.
Option B, re, is correct because it is the built-in module for regular expressions in Python. It provides a comprehensive set of functions such as search(), match(), findall(), and sub() to work with string patterns. Since it is part of the standard library, you do not need to install anything extra to use it. For example:
This functionality is more than adequate for most basic to intermediate regex tasks.
Option C, regex, is also correct. It is an external module (installable via pip install regex) that extends the capabilities of the built-in re module. It supports advanced features like Unicode properties, named capture groups with duplicate names, and fuzzy matching, which are not available in the re module. For example, it allows matching based on Unicode character classes like \p{L} for letters, making it ideal for internationalization.
Let’s now address the incorrect options:
Option A, os, is for operating system-level tasks such as file path handling and environment variables. It does not support regular expression operations.
Option D, string, includes constants like ascii_letters or functions like capwords(), but it does not provide regex matching tools.
Option E, json, is used for encoding and decoding JSON data structures and has no capabilities related to regular expressions.
Therefore, the two modules best suited for handling regular expressions in Python are re and regex, making B and C the correct answers.
Which two functions are commonly used to modify or add elements to a list in Python? (Choose 2.)
A. append()
B. join()
C. insert()
D. dict()
E. pop()
Correct Answers: A, C
Explanation:
Lists are a foundational data structure in Python, used to store collections of data. They are mutable, meaning they can be altered after creation by adding, removing, or modifying elements. Several methods are available to perform these actions, and knowing the right ones is critical for efficient list manipulation.
Option A, append(), is correct. This function adds a single item to the end of a list. It's frequently used when you need to dynamically build a list based on input or process flow. For example:
Option C, insert(), is also correct. This method allows you to add an element at a specific position in the list. It requires two arguments: the index where you want to insert the item, and the item itself. For example:This is especially useful when order matters.
Now let's look at the incorrect options:
Option B, join(), is a string method, not a list method. It is used to join elements of a list into a single string but does not modify the list itself.
Option D, dict(), is used for creating dictionaries, which are key-value data structures unrelated to list operations.
Option E, pop(), while technically a list method, is used for removing elements, not adding or modifying them. Although pop() is useful for manipulation, it doesn't align directly with the creation or addition focus implied in the question. Therefore, it's not selected as one of the two best answers.
In conclusion, append() and insert() are the most direct and essential functions for adding elements to a list, making A and C the correct answers.
Which two features are essential for implementing object-oriented programming (OOP) in Python?
A. class
B. object()
C. def
D. lambda
E. __init__()
Correct Answers: A, E
Explanation:
Object-Oriented Programming (OOP) in Python is based on the concept of "objects," which are created from "classes." This paradigm emphasizes encapsulation, inheritance, and polymorphism to structure programs. In Python, the key building blocks of OOP are classes and methods, particularly the constructor method __init__().
The class keyword (Option A) is fundamental to defining a new class. A class serves as a blueprint for creating objects (instances). Inside the class, we typically define attributes and methods that describe the state and behavior of the objects. For example:
Here, Vehicle is a class, and it can be used to create multiple instances such as car = Vehicle("Toyota").
The __init__() method (Option E) is a special built-in method known as the constructor. It gets automatically called when a new object is instantiated from a class. Its primary role is to initialize the object's attributes with provided values. Without __init__(), you would have to manually assign attributes after object creation, which breaks the principle of encapsulation.
Now, let’s eliminate the incorrect options:
B. object(): While every class in Python inherits from object (explicitly or implicitly), calling object() directly is not how OOP is implemented. It’s a part of the internal class hierarchy and not directly useful for creating custom classes or objects.
C. def: This is a general-purpose keyword used to define functions. Although methods within classes use def, it is not exclusive to OOP and can be used in procedural programming as well. Hence, it is not a defining feature of object orientation in Python.
D. lambda: Lambda functions are anonymous one-liner functions commonly used in functional programming for simple operations. They do not support OOP features like class instantiation, inheritance, or method overriding.
To summarize, the class and __init__() constructs are the most direct and essential components for implementing object-oriented programming in Python, making A and E the correct answers.
Which two of the following practices can enhance the performance of Python programs?
A. Replace loops with list comprehensions
B. Use eval() for faster execution
C. Reduce dependency on global variables
D. Insert print() statements throughout your code
E. Avoid using Python's built-in functions
Correct Answers: A, C
Explanation:
Improving Python performance requires optimizing how code is written and how memory is managed. Two well-recognized approaches include using list comprehensions instead of traditional loops and minimizing global variable usage.
Option A, list comprehensions, offer a more concise and often faster alternative to loops when generating lists. Python's interpreter can optimize list comprehensions internally, leading to significantly better performance compared to appending elements in a loop. For instance:
This executes faster and is more readable than using a loop with .append(). Because it reduces function calls and context switching, it speeds up execution and simplifies the codebase.
Option C, avoiding global variables, is also key to performance. Global variables require Python to perform scope resolution at runtime, which is slower than using local variables. Furthermore, they can lead to unintended side effects and harder-to-maintain code. Python's interpreter accesses local variables faster, and they are confined to a specific function or block, making the code more predictable and efficient.
Now let’s examine the incorrect answers:
B. eval() is not a performance-enhancing function. While it can dynamically execute Python expressions from a string, it's insecure and slow due to the overhead of parsing the string at runtime. It also exposes programs to code injection vulnerabilities.
D. print() statements are helpful for debugging but degrade performance, especially when used in loops or large datasets. Printing to the console is an I/O operation, which is relatively slow and should be avoided in performance-sensitive sections.
E. Avoiding built-in functions is counterproductive. Python’s built-in functions (like sum(), max(), sorted()) are written in C and highly optimized. Replacing them with user-defined equivalents usually results in slower execution.
In conclusion, using list comprehensions for efficient iterations and avoiding global variables for faster scope resolution are two reliable techniques for optimizing Python code. Thus, the correct answers are A and C.
Site Search:
SPECIAL OFFER: GET 10% OFF
Pass your Exam with ExamCollection's PREMIUM files!
SPECIAL OFFER: GET 10% OFF
Use Discount Code:
MIN10OFF
A confirmation link was sent to your e-mail.
Please check your mailbox for a message from support@examcollection.com and follow the directions.
Download Free Demo of VCE Exam Simulator
Experience Avanset VCE Exam Simulator for yourself.
Simply submit your e-mail address below to get started with our interactive software demo of your free trial.