CCNA Devnet Software Dev Questions

74 questions · Devnet Software Dev topic · All types, answers revealed

1
MCQmedium

In a microservices architecture, which communication pattern is typically asynchronous and decoupled?

A.REST over HTTP
B.SOAP
C.gRPC
D.Event-driven architecture
AnswerD

Asynchronous and decoupled.

Why this answer

Event-driven architecture (D) is the correct answer because it is inherently asynchronous and decoupled: services communicate by publishing events to a message broker (e.g., Kafka, RabbitMQ) without needing to know about the consumers. This pattern allows the producer to emit an event and continue processing immediately, while consumers react to events at their own pace, achieving loose coupling and high scalability.

Exam trap

Cisco often tests the misconception that any HTTP-based communication (like REST) is inherently asynchronous, but REST over HTTP is synchronous by default unless combined with additional patterns like webhooks or message queues.

How to eliminate wrong answers

Option A is wrong because REST over HTTP is typically synchronous and tightly coupled: the client sends a request and waits for a response, creating a direct dependency between services. Option B is wrong because SOAP is a synchronous, tightly coupled protocol that relies on XML messaging over HTTP or other transports, often with strict contract definitions (WSDL) that create strong coupling. Option C is wrong because gRPC, while efficient with HTTP/2 and protobufs, is primarily designed for synchronous request-response communication (though it supports streaming, the default pattern is still coupled and blocking).

2
MCQhard

Which Python exception would be raised by the following code? my_dict = {'a': 1} value = my_dict['b']

A.KeyError
B.ValueError
C.IndexError
D.AttributeError
AnswerA

Correct.

Why this answer

Accessing a dictionary key that does not exist raises a KeyError in Python. In the code, my_dict['b'] attempts to retrieve the value for key 'b', which is not present in the dictionary {'a': 1}, so Python raises KeyError.

Exam trap

Cisco often tests the distinction between KeyError and IndexError, trapping candidates who confuse dictionary key access with list index access, especially when the code uses square brackets in both contexts.

How to eliminate wrong answers

Option B is wrong because ValueError is raised when a function receives an argument of the correct type but an inappropriate value (e.g., int('abc')), not for missing dictionary keys. Option C is wrong because IndexError is raised when accessing an index out of range in a sequence like a list or tuple, not for dictionary key access. Option D is wrong because AttributeError is raised when an invalid attribute reference or assignment is made (e.g., my_dict.append), not for missing dictionary keys.

3
MCQhard

A developer is using Git for version control. After creating a new feature branch 'feature-login' from 'main', they make several commits. Meanwhile, another developer has merged changes into 'main'. The developer wants to incorporate the latest main changes into 'feature-login' without creating a merge commit. Which Git command should they use?

A.git rebase main
B.git merge main
C.git pull --rebase origin main
D.git checkout main && git pull && git checkout feature-login && git merge main
AnswerC

This fetches and rebases the current branch onto main, incorporating changes without a merge commit.

Why this answer

Option C is correct because `git pull --rebase origin main` fetches the latest changes from the remote `main` branch and then rebases the current `feature-login` branch onto those changes. This incorporates the new commits from `main` without creating a merge commit, resulting in a linear history. The `--rebase` flag ensures that the developer's commits are replayed on top of the updated `main`, avoiding the extra merge commit that `git merge` would create.

Exam trap

Cisco often tests the distinction between `git merge` and `git rebase` in the context of avoiding merge commits, and the trap here is that candidates may choose `git rebase main` (Option A) without realizing it does not fetch remote changes, or they may choose `git merge main` (Option B) thinking it can be done without a merge commit, which is incorrect.

How to eliminate wrong answers

Option A is wrong because `git rebase main` would attempt to rebase the current branch onto the local `main` branch, but it does not first fetch the latest changes from the remote. If the local `main` is outdated, this command would not incorporate the latest remote changes, and it could also fail if the local `main` hasn't been updated. Option B is wrong because `git merge main` would create a merge commit, which the developer explicitly wants to avoid.

Option D is wrong because it uses `git merge main` at the end, which creates a merge commit, and the sequence is unnecessarily complex; it also does not use `--rebase` to avoid the merge commit.

4
Multi-Selectmedium

A developer is designing a Python script that needs to make multiple REST API calls to different endpoints sequentially. The script must handle the following requirements: (1) Use a variable timeout for each request, (2) Include an authorization token in every request, (3) Parse JSON responses. Which TWO features of the requests library should be used? (Choose two.)

Select 2 answers
A.Set the `data` parameter to JSON for request body.
B.Use the `timeout` parameter to specify a maximum wait time.
C.Use `verify=False` to speed up requests.
D.Set the `auth` parameter with a tuple (username, token).
E.Use the `headers` parameter to include the authorization token.
AnswersB, E

Prevents indefinite hanging.

Why this answer

Option B is correct because the `timeout` parameter in the requests library allows you to specify a maximum wait time (in seconds) for each request, directly addressing requirement (1) for a variable timeout. Option E is correct because the `headers` parameter is the standard way to include an authorization token (e.g., `{'Authorization': 'Bearer <token>'}`) in every request, satisfying requirement (2). Both features are essential for controlling request behavior and authentication in REST API calls.

Exam trap

Cisco often tests the distinction between the `auth` parameter (for Basic Auth) and the `headers` parameter (for bearer tokens), causing candidates to mistakenly choose Option D when they should use Option E.

5
MCQmedium

A Python function needs to accept a variable number of keyword arguments. Which parameter syntax should be used?

A.*kwargs
B.**kwargs
C.*args
D.&kwargs
AnswerB

**kwargs collects keyword arguments into a dict.

Why this answer

In Python, the **kwargs syntax allows a function to accept a variable number of keyword arguments by collecting them into a dictionary. This is the correct parameter syntax for handling arbitrary keyword arguments, as specified in Python's function definition rules.

Exam trap

Cisco often tests the distinction between *args (positional arguments) and **kwargs (keyword arguments), and candidates mistakenly choose *kwargs or confuse the syntax with other operators like &.

How to eliminate wrong answers

Option A is wrong because *kwargs is not valid Python syntax; the correct syntax for variable positional arguments is *args, not *kwargs. Option C is wrong because *args collects extra positional arguments into a tuple, not keyword arguments. Option D is wrong because &kwargs is not a valid Python operator or syntax; Python uses ** for dictionary unpacking and keyword argument collection, not &.

6
Multi-Selecteasy

A Python function needs to handle both expected and unexpected errors during file I/O. Which THREE constructs are essential for robust exception handling? (Choose three.)

Select 3 answers
A.except
B.else
C.try
D.raise
E.finally
AnswersA, C, E

Catches specific exceptions.

Why this answer

Option A (except) is correct because it is the block that catches exceptions raised during execution of the try block. Without an except clause, any error would propagate unhandled and crash the program. In file I/O, this is essential to catch specific exceptions like FileNotFoundError or PermissionError and respond appropriately.

Exam trap

Cisco often tests the distinction between constructs that handle exceptions (try, except, finally) versus those that control flow (else) or raise exceptions (raise), leading candidates to include optional or non-handling constructs as 'essential'.

7
Multi-Selecthard

A developer is implementing exception handling in Python for a function that makes an HTTP request. Which THREE exception types should be caught to handle common network and HTTP errors? (Choose three.)

Select 3 answers
A.requests.exceptions.ConnectionError
B.requests.exceptions.InvalidURL
C.requests.exceptions.Timeout
D.requests.exceptions.HTTPError
E.requests.exceptions.TooManyRedirects
AnswersA, C, D

Raised when a connection fails (e.g., DNS failure, refused connection).

Why this answer

Option A is correct because `requests.exceptions.ConnectionError` is raised when a network connection cannot be established, such as DNS resolution failure or refused TCP connection. This is a fundamental network error that must be handled in any HTTP client to ensure robust error recovery.

Exam trap

Cisco often tests the distinction between exceptions that represent recoverable runtime errors (ConnectionError, Timeout, HTTPError) versus exceptions that indicate programming bugs (InvalidURL) or edge-case behavior (TooManyRedirects), leading candidates to over-select or under-select the correct set.

8
Multi-Selectmedium

A Python script is interacting with a REST API that returns JSON. The script needs to handle potential errors gracefully. Which TWO practices should be implemented? (Choose two.)

Select 2 answers
A.Use response.raise_for_status() to raise exceptions for HTTP errors.
B.Use a single try/except block to catch all exceptions without differentiation.
C.Check response.status_code to determine success or failure.
D.Assume the request always succeeds; errors are rare.
E.Always parse the response body with json.loads() regardless of content type.
AnswersA, C

Convenient way to handle 4xx/5xx errors.

Why this answer

Option A is correct because `response.raise_for_status()` is a built-in method of the `requests` library that automatically raises an `HTTPError` exception for any 4xx or 5xx status code. This allows the script to handle HTTP errors in a structured way using try/except blocks, rather than manually checking each status code. It is a best practice for robust REST API interaction in Python.

Exam trap

Cisco often tests the distinction between using `response.raise_for_status()` versus manually checking `response.status_code` — the trap is that candidates think only one is correct, but both are valid and complementary practices for robust error handling.

9
MCQmedium

Which Git command is used to switch to an existing branch named 'feature-x' and update the working directory?

A.git merge feature-x
B.git branch feature-x
C.git switch -c feature-x
D.git checkout feature-x
AnswerD

Switches to the specified branch and updates the working directory.

Why this answer

Option D is correct because `git checkout feature-x` is the traditional Git command that switches the HEAD reference to the existing branch 'feature-x' and updates the working directory to match that branch's commit history. This command performs both the branch switch and the working tree update in one operation, which is the core requirement of the question.

Exam trap

Cisco often tests the distinction between `git checkout` for switching to an existing branch versus `git checkout -b` (or `git switch -c`) for creating and switching to a new branch, and candidates frequently confuse the `-c` flag as a switch-only option rather than a creation flag.

How to eliminate wrong answers

Option A is wrong because `git merge feature-x` integrates changes from 'feature-x' into the current branch, rather than switching to 'feature-x'. Option B is wrong because `git branch feature-x` creates a new branch named 'feature-x' from the current HEAD, but does not switch to it or update the working directory. Option C is wrong because `git switch -c feature-x` creates and switches to a new branch named 'feature-x', but the question specifies switching to an existing branch, and the `-c` flag is for creation, not for an existing branch.

10
MCQmedium

Which HTTP status code indicates that a POST request successfully created a new resource?

A.204 No Content
B.301 Moved Permanently
C.201 Created
D.200 OK
AnswerC

Correct: 201 Created indicates successful resource creation.

Why this answer

HTTP 201 Created is the standard response for a successful POST that creates a resource.

11
MCQeasy

What is the output of the following code? my_list = [1, 2, 3] for i in range(len(my_list)): my_list[i] += 1 print(my_list)

A.[2, 3, 4]
B.[1, 2, 3, 1]
C.[1, 2, 3]
D.Error
AnswerA

Correct, each element incremented by 1.

Why this answer

The code modifies each element by adding 1. So [1,2,3] becomes [2,3,4].

12
MCQhard

In a microservices architecture, which of the following is a key characteristic compared to a monolithic architecture?

A.Changes require rebuilding the entire application.
B.Services communicate via lightweight protocols such as HTTP/REST.
C.The entire application is deployed as a single unit.
D.All services share the same database.
AnswerB

Microservices typically communicate via HTTP/REST, messaging queues, etc.

Why this answer

Microservices are independently deployable, scalable, and developed by small teams, whereas a monolith is a single deployable unit.

13
MCQmedium

In the context of REST API design, which HTTP status code should be returned when a client sends a request that exceeds the API rate limit?

A.503 Service Unavailable
B.400 Bad Request
C.429 Too Many Requests
D.401 Unauthorized
AnswerC

This status code explicitly indicates the client has sent too many requests in a given time.

Why this answer

Option C (429 Too Many Requests) is correct because RFC 6585 defines this status code specifically for cases where a client has sent too many requests in a given time frame, exceeding the API's rate limit. REST APIs use this response to enforce throttling and inform the client to back off, often including a Retry-After header to indicate when to retry.

Exam trap

Cisco often tests the distinction between server-side errors (5xx) and client-side rate-limit errors (429), where candidates mistakenly choose 503 Service Unavailable because they confuse server overload with client rate limiting.

How to eliminate wrong answers

Option A is wrong because 503 Service Unavailable indicates the server is temporarily unable to handle the request due to overload or maintenance, not specifically due to client rate limiting. Option B is wrong because 400 Bad Request indicates a malformed request syntax or invalid parameters, not a rate-limit violation. Option D is wrong because 401 Unauthorized indicates missing or invalid authentication credentials, not exceeding a rate limit.

14
Multi-Selecthard

A Python developer is working on a microservices project where one service needs to communicate with another service that exposes a GraphQL API. Which THREE statements about GraphQL compared to REST are accurate? (Choose three.)

Select 3 answers
A.GraphQL allows clients to request exactly the fields they need.
B.GraphQL is a database query language.
C.GraphQL has a strongly typed schema that defines the API.
D.GraphQL typically uses multiple endpoints for different resources.
E.GraphQL uses HTTP POST for queries and mutations.
AnswersA, C, E

Reduces over-fetching and under-fetching.

Why this answer

GraphQL allows querying specific data, uses a single endpoint, and provides a schema.

15
MCQmedium

A Python function is designed to fetch device data from multiple sources. It uses *args to accept variable number of API endpoints and **kwargs for optional parameters like timeout. Which function definition correctly implements this?

A.def fetch_devices(**endpoints, *options):
B.def fetch_devices(endpoints, **options):
C.def fetch_devices(*endpoints, **options):
D.def fetch_devices(*endpoints, options):
AnswerC

Correct syntax: * for variable positional args, ** for keyword args.

Why this answer

Option C is correct because it uses *endpoints to accept a variable number of positional arguments (the API endpoint strings) and **options to accept any number of keyword arguments (like timeout=30). This matches the requirement for a function that can handle multiple sources with optional parameters, following Python's standard *args/**kwargs pattern.

Exam trap

Cisco often tests the distinction between *args (variable positional arguments) and **kwargs (variable keyword arguments), and the trap here is that candidates confuse the syntax or order, thinking **endpoints can appear before *options or that a simple parameter name like options can accept keyword arguments without the double asterisk.

How to eliminate wrong answers

Option A is wrong because it places **endpoints before *options, which is syntactically invalid in Python — keyword-only arguments must follow positional ones, and **kwargs must be the last parameter. Option B is wrong because it defines endpoints as a single positional parameter, not allowing a variable number of API endpoints; it would require the caller to pass a list or tuple explicitly. Option D is wrong because it uses *endpoints correctly but defines options as a regular positional parameter, not as **kwargs, so optional parameters like timeout cannot be passed as keyword arguments.

16
MCQmedium

Given the following Python code snippet: with open('config.json', 'r') as f: data = json.load(f) print(data['interfaces'][0]['name']) What is the expected output if config.json contains {"interfaces": [{"name": "GigabitEthernet0/1"}]}?

A.GigabitEthernet0/1
B.None
C.interfaces
D.Error: list indices must be integers
AnswerA

Correctly accesses the first interface's name.

Why this answer

json.load() reads the file and returns a dict; then accessing the nested structure yields 'GigabitEthernet0/1'.

17
MCQmedium

In version control with Git, which command creates a new branch and switches to it in one step?

A.git checkout -b <branch>
B.git checkout <branch>
C.git branch <branch>
D.git switch <branch>
AnswerA

Creates and switches.

Why this answer

git checkout -b <branch> creates and switches. git branch <branch> creates but does not switch. git switch -c is also valid but not listed.

18
MCQmedium

A Python script sends a PUT request to update a resource. The API returns a response with status code 204. What does this indicate?

A.The request was malformed.
B.The update was successful and no content is returned.
C.The resource was not found.
D.The update failed due to a server error.
AnswerB

204 No Content indicates success with no body.

Why this answer

204 No Content means the request succeeded, but there is no response body (common for PUT or DELETE).

19
Multi-Selecthard

Which THREE of the following are best practices when using Git for a collaborative project? (Choose three.)

Select 3 answers
A.Use feature branches for new work.
B.Rebase or merge regularly to incorporate upstream changes.
C.Commit directly to the main branch.
D.Write descriptive commit messages.
E.Avoid pulling from remote to prevent conflicts.
AnswersA, B, D

Isolate work.

Why this answer

A is correct because feature branches isolate new work from the stable main branch, enabling parallel development without disrupting the shared codebase. This practice aligns with Git's branching model and supports code review and continuous integration workflows.

Exam trap

Cisco often tests the misconception that committing directly to main is acceptable for small changes, but the exam emphasizes that all changes should go through feature branches to maintain a clean, reviewable history.

20
MCQmedium

Given the JSON string: '{"name": "Alice", "scores": [90, 85, 92]}', which Python code correctly extracts the second score (85)?

A.json.loads(json_str)['scores'][1]
B.json.dumps(json_str)['scores'][1]
C.json_str['scores'][1]
D.json.loads(json_str)['scores'][2]
AnswerA

Correct.

Why this answer

json.loads converts to dict, then access scores list index 1.

21
MCQhard

In a RESTful API, which HTTP method is idempotent but not safe?

A.GET
B.DELETE
C.POST
D.PUT
AnswerD

Idempotent but not safe.

Why this answer

PUT is idempotent (same result multiple times) but not safe (modifies resource). GET is safe. DELETE is idempotent.

22
MCQmedium

A Python function is defined as: def process(*args, **kwargs): return sum(args) + kwargs.get('offset', 0) What is the result of process(1, 2, 3, offset=10)?

A.6
B.16
C.Error
D.10
AnswerB

6 + 10 = 16.

Why this answer

*args captures positional arguments as tuple (1,2,3), sum is 6, kwargs dict includes {'offset':10}, .get returns 10, total 16.

23
MCQmedium

Which HTTP status code indicates that a POST request successfully created a new resource on the server?

A.200 OK
B.201 Created
C.204 No Content
D.202 Accepted
AnswerB

Indicates that the request succeeded and a new resource was created.

Why this answer

The 201 Created status code is the correct response for a POST request that successfully creates a new resource. According to RFC 7231, the server should respond with 201 and include a Location header pointing to the newly created resource's URI. This is the standard behavior for RESTful APIs when a POST operation results in resource creation.

Exam trap

Cisco often tests the distinction between 200 OK and 201 Created, trapping candidates who assume any successful POST returns 200 OK, when in fact 201 is the standard for resource creation.

How to eliminate wrong answers

Option A is wrong because 200 OK indicates a successful request but does not specifically signal that a new resource was created; it is typically used for GET requests or POST requests that return a representation without creating a new resource. Option C is wrong because 204 No Content indicates the server successfully processed the request but returns no response body, often used for DELETE operations or updates that return no content, not for resource creation. Option D is wrong because 202 Accepted means the request has been accepted for processing but the processing has not been completed; it is used for asynchronous operations, not for immediate resource creation.

24
MCQhard

A developer is using Git for a project with a feature branch strategy. They have completed work on a new feature in the branch 'feature-logging' and want to integrate it into the main development branch 'develop'. The team requires that all commits on the feature branch be squashed into a single commit before merging. Which sequence of Git commands achieves this?

A.git checkout feature-logging && git rebase develop && git checkout develop && git merge feature-logging
B.git checkout develop && git merge feature-logging --squash && git commit
C.git checkout develop && git pull feature-logging && git commit --amend
D.git checkout develop && git merge --no-ff feature-logging
AnswerB

Checks out develop, merges with squash, then commits the staged changes.

Why this answer

Squash merging combines all commits into one; using --squash option on merge accomplishes this.

25
MCQeasy

A developer is writing a Python script to iterate over a list of server hostnames. Which loop structure is most appropriate to process each hostname in the list?

A.for i, hostname in enumerate(hostnames): print(hostname)
B.while len(hostnames) > 0: print(hostnames.pop())
C.for i in range(len(hostnames)): print(hostnames[i])
D.for hostname in hostnames: print(hostname)
AnswerD

Directly iterates over each hostname, which is the recommended approach.

Why this answer

The 'for item in list' loop iterates directly over each element, making it the simplest and most readable for processing each hostname.

26
MCQhard

A Python script uses a list comprehension: [x**2 for x in range(20) if x % 2 == 0]. Which of the following is equivalent?

A.result = [] for x in range(20): if x % 2 == 0: result.append(x**2)
B.result = map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(20)))
C.result = [] for x in range(20): result.append(x**2)
D.result = [x**2 for x in range(20) if x % 2 != 0]
AnswerA

This loop explicitly does the same filtering and squaring.

Why this answer

Option A is correct because it directly translates the list comprehension into an equivalent for-loop with a conditional append. The comprehension `[x**2 for x in range(20) if x % 2 == 0]` iterates over numbers 0–19, filters for even numbers (x % 2 == 0), squares each, and collects the results in a list. Option A's explicit loop and conditional produce the exact same sequence of appended values.

Exam trap

Cisco often tests the distinction between list comprehensions with and without a filtering condition, and the trap here is that candidates may overlook the `if x % 2 == 0` filter and choose Option C, which omits the condition entirely.

How to eliminate wrong answers

Option B is wrong because it is actually functionally equivalent to the original comprehension (using `filter` and `map`), so it is not incorrect; however, the question asks for an equivalent among the options, and A is the direct translation. Option C is wrong because it appends `x**2` for every x in range(20) without filtering, so it includes odd numbers, producing a different list. Option D is wrong because it uses `x % 2 != 0`, which selects odd numbers instead of even numbers, yielding the squares of odd numbers only.

27
MCQmedium

A Python script sends a POST request to create a new network device resource. The API returns HTTP status code 201 and a JSON response with the device ID. How should the script correctly extract the device ID from the response?

A.device_id = response['id']
B.device_id = response.text['id']
C.device_id = response.json().get('id')
D.device_id = json.loads(response)['id']
AnswerC

response.json() returns a dict; .get() safely retrieves the 'id' key.

Why this answer

A 201 status indicates successful creation, and response.json() parses the JSON body into a Python dict.

28
MCQeasy

A developer is working on a Python script that performs CRUD operations on devices via a REST API. Which HTTP method should be used to update an existing device's configuration partially?

A.PATCH
B.POST
C.DELETE
D.PUT
AnswerA

PATCH applies partial modifications to a resource.

Why this answer

PATCH is used for partial updates, PUT for full replacement.

29
MCQmedium

A developer needs to parse a JSON string received from a REST API into a Python dictionary. Which function should they use?

A.json.dumps()
B.json.loads()
C.json.load()
D.json.dump()
AnswerB

loads parses JSON string to Python dict.

Why this answer

json.loads() converts a JSON string into a Python object (dict, list, etc.).

30
MCQhard

A Python script uses a try/except block to handle API errors. If the API returns a 429 status code, which mechanism should the script implement to handle the error appropriately?

A.Switch to a different API endpoint
B.Wait for the time specified in the Retry-After header and then retry
C.Log the error and continue without retrying
D.Immediately retry the same request without delay
AnswerB

Respecting the Retry-After header is the proper way to handle rate limiting.

Why this answer

A 429 status code indicates the client has sent too many requests in a given amount of time (rate limiting). The HTTP specification (RFC 6585) recommends including a Retry-After header in the response, which tells the client how long to wait before retrying. Implementing a wait based on this header and then retrying is the correct and respectful way to handle rate limiting, allowing the script to eventually succeed without overwhelming the server.

Exam trap

Cisco often tests the distinction between handling transient errors (like 429) versus permanent errors (like 404 or 500), and the trap here is that candidates may choose to immediately retry (D) or log and continue (C) without understanding that 429 specifically requires a delay before retry.

How to eliminate wrong answers

Option A is wrong because switching to a different API endpoint does not address the rate limit on the current endpoint; the client is still rate-limited and the new endpoint may also be affected or require separate authentication. Option C is wrong because logging the error and continuing without retrying means the script abandons the operation entirely, which is not appropriate when the error is transient and can be resolved by waiting. Option D is wrong because immediately retrying the same request without delay will almost certainly result in another 429 error, as the rate limit has not yet expired, and may worsen the situation by further exhausting the rate limit window.

31
MCQmedium

A network engineer writes a Python script to handle exceptions when making REST API calls. Which exception type should be caught to handle network connectivity issues (e.g., DNS failure, refused connection)?

A.requests.exceptions.RequestException
B.requests.exceptions.ConnectionError
C.requests.exceptions.HTTPError
D.requests.exceptions.Timeout
AnswerB

ConnectionError specifically indicates network problems like failed DNS or refused connection.

Why this answer

Option B is correct because `requests.exceptions.ConnectionError` is specifically raised when the underlying TCP connection fails, which includes scenarios like DNS resolution failures, refused connections, or the remote host being unreachable. This exception is a subclass of `RequestException` and directly maps to network-level issues at the transport layer, making it the precise exception to catch for connectivity problems.

Exam trap

Cisco often tests the distinction between the broad `RequestException` and the specific `ConnectionError`, trapping candidates who choose the base class thinking it covers all errors, when the question explicitly asks for network connectivity issues.

How to eliminate wrong answers

Option A is wrong because `requests.exceptions.RequestException` is the base class for all exceptions in the `requests` library; catching it would be too broad and would also handle non-connectivity errors like HTTP errors or timeouts, which is not the specific requirement. Option C is wrong because `requests.exceptions.HTTPError` is raised only when the server returns an HTTP error status code (e.g., 4xx or 5xx), which indicates an application-level issue, not a network connectivity failure. Option D is wrong because `requests.exceptions.Timeout` is raised when a request exceeds the specified timeout period, which is a timing issue rather than a fundamental network connectivity failure like DNS failure or refused connection.

32
MCQmedium

A developer is designing a microservices architecture for a network monitoring application. Which of the following is a key advantage of microservices over a monolithic architecture?

A.Lower latency due to in-process communication
B.Easier to maintain as a single codebase
C.Independent deployability and scalability of services
D.Simpler inter-service communication
AnswerC

Each microservice can be deployed and scaled independently, improving resource utilization.

Why this answer

Microservices architecture enables each service to be deployed, updated, and scaled independently without affecting other services. This is a key advantage over monolithic architectures, where any change requires rebuilding and redeploying the entire application. For a network monitoring application, independent scalability allows resource-intensive services (e.g., packet capture) to scale separately from lightweight services (e.g., alerting).

Exam trap

Cisco often tests the misconception that microservices simplify communication or reduce latency, when in reality they introduce network overhead and complexity, making independent deployability and scalability the primary advantage.

How to eliminate wrong answers

Option A is wrong because microservices typically use inter-process communication (e.g., HTTP/REST, gRPC, or message queues), which introduces higher latency compared to in-process function calls in a monolithic application. Option B is wrong because microservices split the codebase into multiple smaller repositories, each maintained by separate teams, making the overall system more complex to manage than a single monolithic codebase. Option D is wrong because inter-service communication in microservices is inherently complex, requiring handling of network failures, serialization, and service discovery (e.g., via Consul or Kubernetes DNS), unlike monolithic architectures where components communicate via direct function calls.

33
Multi-Selectmedium

Which TWO of the following are valid branching strategies in Git? (Choose two.)

Select 2 answers
A.GitFlow
B.Feature branching
C.Linear branching
D.Monolithic branching
E.Copy-on-write branching
AnswersA, B

A comprehensive branching model with master, develop, feature, release, and hotfix branches.

Why this answer

GitFlow is a valid branching strategy that defines a strict model for managing releases, hotfixes, and feature development using dedicated branches like 'develop', 'release/*', and 'hotfix/*'. It is widely used in enterprise environments to maintain a clean history and support parallel development.

Exam trap

Cisco often tests the distinction between actual branching strategies (like GitFlow and Feature branching) and Git's internal mechanisms (like copy-on-write) or non-standard terms (like linear or monolithic branching) to see if candidates confuse implementation details with workflow models.

34
Multi-Selectmedium

Which TWO of the following Python exception handling statements are valid? (Choose two.)

Select 4 answers
A.try:\n x = 1/0\nexcept ZeroDivisionError as e:\n print(e)
B.try:\n x = 1/0\nexcept ZeroDivisionError, e:\n print(e)
C.try:\n x = 1/0\nexcept ZeroDivisionError:\n print('error')\nexcept:\n print('other error')
D.try:\n x = 1/0\nexcept (ZeroDivisionError, TypeError) as e:\n print(e)
E.try:\n x = 1/0\nexcept:\n print('error')
AnswersA, C, D, E

Correct syntax with alias.

Why this answer

Option A is correct because Python's `except` clause uses the `as` keyword to bind the exception instance to a variable, allowing access to the error message via `e`. This syntax is valid and commonly used for logging or inspecting exception details.

Exam trap

Cisco often tests the Python 2 vs Python 3 syntax change, specifically the removal of the comma-based exception binding (`except Exception, e`) in favor of the `as` keyword, to catch candidates who are familiar with older Python versions.

35
MCQmedium

In software architecture, which pattern separates an application into three interconnected components: Model (data), View (UI), and Controller (input logic)?

A.MVC (Model-View-Controller)
B.Microservices
C.Event-driven
AnswerA

MVC separates data, presentation, and control logic.

Why this answer

The MVC pattern explicitly separates an application into three interconnected components: Model (data and business logic), View (user interface), and Controller (handles user input and updates the Model/View). This is the foundational architectural pattern for many web frameworks like Django, Ruby on Rails, and Spring MVC, where the Controller receives HTTP requests, interacts with the Model, and selects the appropriate View for rendering.

Exam trap

Cisco often tests that candidates confuse MVC with REST or Microservices because both involve separation of concerns, but MVC is specifically about internal component separation within a single application, not about service decomposition or API design.

How to eliminate wrong answers

Option B (Microservices) is wrong because it decomposes an application into independently deployable services, each with its own data and logic, rather than separating a single application into Model, View, and Controller components. Option C (Event-driven) is wrong because it relies on event producers and consumers communicating asynchronously via an event bus, not on a three-component separation of data, UI, and input logic. Option D (REST) is wrong because it is an architectural style for designing networked APIs using HTTP methods and stateless communication, not a pattern for structuring internal application components.

36
MCQhard

A developer uses the requests library to call an API. The API returns 429 Too Many Requests. What is the best practice to handle this?

A.Ignore the status code and proceed
B.Immediately retry the request
C.Use exponential backoff and retry
D.Wait a fixed amount of time and retry
AnswerC

Standard practice.

Why this answer

Implement retry with exponential backoff to respect rate limiting.

37
MCQmedium

A developer needs to update an existing resource via a REST API. The update should be partial, meaning only the fields provided in the request body should be changed. Which HTTP method should be used?

A.PATCH
B.DELETE
C.PUT
D.POST
AnswerA

PATCH is the standard HTTP method for partial modifications.

Why this answer

PATCH is used for partial updates to a resource, while PUT replaces the entire resource.

38
Multi-Selecteasy

Which TWO of the following are valid Python data types?

Select 2 answers
A.array
B.list
C.set
D.dict
E.map
AnswersB, D

List is a mutable sequence type.

Why this answer

Option B (list) is correct because Python's built-in list type is a mutable, ordered collection that can hold heterogeneous elements and is a fundamental data type in the language. Option D (dict) is correct because dict is a built-in mapping type that stores key-value pairs with unique keys, making it a core Python data type.

Exam trap

Cisco often tests the distinction between built-in data types (like list and dict) and modules or functions (like array and map) that are not data types themselves, causing candidates to confuse the array module or map function with actual data types.

39
MCQmedium

Which Git branching strategy typically involves a long-lived 'develop' branch where feature branches are merged, and releases are created from a 'release' branch?

A.GitFlow
B.GitHub Flow
C.Trunk-based development
D.Feature branch workflow
AnswerA

Involves develop and release branches.

Why this answer

GitFlow is correct because it defines a long-lived 'develop' branch for integrating feature branches, and a separate 'release' branch for preparing releases. This strategy uses dedicated branches for features, releases, and hotfixes, with strict merging rules back to 'develop' and 'main'.

Exam trap

Cisco often tests the distinction between GitFlow's multiple long-lived branches (develop, release, main) and simpler workflows like GitHub Flow or trunk-based development, where candidates mistakenly assume any workflow with feature branches is GitFlow.

How to eliminate wrong answers

Option B (GitHub Flow) is wrong because it uses a single long-lived 'main' branch with short-lived feature branches, and releases are created directly from 'main' without a dedicated 'release' branch. Option C (Trunk-based development) is wrong because it relies on a single trunk branch (often 'main' or 'trunk') with very short-lived feature branches, and no long-lived 'develop' or 'release' branches. Option D (Feature branch workflow) is wrong because it typically merges feature branches directly into a shared branch (e.g., 'main') without a separate long-lived 'develop' branch or a dedicated 'release' branch.

40
MCQmedium

A Python script reads a JSON configuration file named 'config.json' and needs to extract the value of a nested key 'api_key' under 'authentication'. The file structure is: {"authentication": {"api_key": "abc123", "method": "token"}, "timeout": 30}. Which code snippet correctly opens the file and retrieves the api_key value?

A.f = open('config.json'); data = json.load(f); key = data['authentication']['api_key']; f.close()
B.with open('config.json') as f: data = json.loads(f) key = data['authentication']['api_key']
C.with open('config.json', 'r') as f: data = json.load(f) key = data['authentication.api_key']
D.with open('config.json') as f: data = json.load(f) key = data['authentication']['api_key']
AnswerD

json.load() reads file and parses JSON; correct nested access.

Why this answer

Using the json module and context manager is the standard approach; the nested key is accessed via dictionary indexing.

41
Multi-Selecthard

A network automation script uses Git for version control. The developer wants to revert the last two commits on the current branch but keep the changes in the working directory for further modification. Which TWO Git commands can achieve this? (Choose two.)

Select 2 answers
A.git checkout HEAD~2
B.git reset --hard HEAD~2
C.git reset --soft HEAD~2
D.git remove HEAD~2
E.git revert HEAD~2..HEAD
AnswersC, E

Moves HEAD back two commits, keeps changes staged.

Why this answer

git reset --soft and git revert can be used; soft reset moves HEAD back but keeps changes staged; revert creates new commits undoing changes.

42
MCQeasy

What does the Git command 'git log --oneline' display?

A.A list of files changed in the last commit
B.The branches and their latest commits
C.The differences between the working directory and the last commit
D.A summary of each commit on one line
AnswerD

Correct: oneline format.

Why this answer

The --oneline flag condenses each commit to a single line showing the commit hash and message.

43
MCQmedium

A developer is implementing a Python function that makes an HTTP GET request to an API and returns the response time. Which code snippet correctly measures the elapsed time?

A.response = requests.get(url); return response.headers['Date']
B.response = requests.get(url); return response.elapsed.total_seconds()
C.start = time.time(); response = requests.get(url); return time.time() - start
D.import time; start = time.time(); response = requests.get(url); return time.time() - start
AnswerD

This correctly captures the start time, makes the request, and returns the difference.

Why this answer

Using time.time() before and after the request and subtracting gives the elapsed time in seconds.

44
MCQeasy

A developer writes a Python script to read a configuration file. Which code snippet correctly opens the file 'config.json' for reading and ensures the file is closed after use?

A.with open('config.json', 'r') as f:\n data = f.read()
B.open('config.json', 'r') as f:\n data = f.read()
C.with open('config.json', 'r') as f, data = f.read()
D.file = open('config.json', 'r')\ndata = file.read()\nfile.close()
AnswerA

Using with ensures proper acquisition and release of resources.

Why this answer

Option A is correct because it uses the `with` statement, which is a context manager that automatically calls `f.close()` when the block exits, ensuring the file is properly closed even if an exception occurs. The `'r'` mode opens the file for reading, and `f.read()` reads the entire contents into the `data` variable.

Exam trap

Cisco often tests the candidate's understanding of Python's context manager (`with` statement) versus manual file handling, expecting candidates to recognize that only the `with` statement guarantees automatic resource cleanup, while explicit `close()` calls are error-prone in the face of exceptions.

How to eliminate wrong answers

Option B is wrong because it uses `open('config.json', 'r') as f:` without the `with` statement, which is a syntax error in Python; the `as` clause is only valid inside a `with` statement. Option C is wrong because it uses a comma to separate the `with` statement and the assignment, which is invalid syntax; the correct syntax requires a colon and an indented block. Option D is wrong because while it does open the file and explicitly close it, it lacks the automatic cleanup provided by the `with` statement; if an exception occurs between `open()` and `file.close()`, the file may not be closed, leading to resource leaks.

45
MCQmedium

Which Python list comprehension correctly creates a list of squares for even numbers from 0 to 10?

A.[x**2 for x in range(11) if x % 2 == 0]
B.[x*2 for x in range(11) if x % 2 == 0]
C.[x**2 for x in range(10) if x % 2]
D.[x**2 for x in range(10) if x % 2 == 0]
AnswerA

Correct: filters even numbers and squares them.

Why this answer

Option A is correct because it uses list comprehension syntax with `x**2` to square each number, iterates over `range(11)` to include numbers 0 through 10, and applies the condition `if x % 2 == 0` to filter only even numbers. This produces the list `[0, 4, 16, 36, 64, 100]` as required.

Exam trap

Cisco often tests the subtle difference between `range(10)` and `range(11)` to see if candidates remember that `range(n)` generates numbers from 0 to n-1, and also tests the distinction between `x % 2` (odd filter) and `x % 2 == 0` (even filter).

How to eliminate wrong answers

Option B is wrong because it uses `x*2` (multiplication by 2) instead of `x**2` (squaring), so it creates a list of doubled even numbers, not squares. Option C is wrong because it uses `if x % 2` which evaluates to True for odd numbers (since odd numbers have remainder 1), thus filtering for odd numbers instead of even numbers, and also uses `range(10)` which excludes 10. Option D is wrong because it uses `range(10)` which generates numbers 0 through 9, missing the number 10, so the list will not include the square of 10 (100).

46
MCQmedium

A developer is building a REST API client in Python using the requests library. They need to send a JSON payload with authentication. Which code snippet correctly sends a POST request with a JSON body and a Bearer token?

A.requests.post(url, data=payload, auth=token)
B.requests.post(url, json=payload, headers={'Authorization': f'Bearer {token}'})
C.requests.post(url, data=json.dumps(payload), headers={'Authorization': token})
D.requests.post(url, params=payload, auth=('Bearer', token))
AnswerB

Correct: json= automatically sets content-type and serializes.

Why this answer

The correct way is to use json parameter for JSON body and headers for authorization.

47
MCQeasy

A developer wants to process a list of server hostnames and create a new list containing only hostnames that start with 'web'. Which Python list comprehension correctly accomplishes this?

A.[hostname.startswith('web') for hostname in servers]
B.[hostname for hostname in servers if 'web' in hostname]
C.[hostname for hostname in servers if hostname.startswith('web')]
D.[hostname if hostname.startswith('web') for hostname in servers]
AnswerC

Correct syntax for list comprehension with condition.

Why this answer

The list comprehension filters items based on the condition and produces a new list.

48
MCQhard

An automation engineer is writing a Python script to interact with a REST API that requires authentication. The API returns a 403 Forbidden status. Which scenario best explains this response?

A.The request was malformed and the server cannot process it.
B.The requested resource does not exist on the server.
C.The server is temporarily unavailable due to maintenance.
D.The authentication token is missing or invalid, and the request is not allowed.
AnswerD

403 Forbidden indicates that the server recognized the credentials but they do not have the required permissions.

Why this answer

A 403 Forbidden status code indicates that the server understood the request but refuses to authorize it. In the context of a REST API requiring authentication, this typically means the authentication token is missing, expired, or invalid, and the server is explicitly denying access. This aligns with RFC 7231, which defines 403 as a response when the server 'refuses to fulfill the request' due to insufficient authorization credentials.

Exam trap

Cisco often tests the distinction between 401 (Unauthorized) and 403 (Forbidden), where candidates mistakenly think any authentication failure results in 401, but 403 specifically applies when the server knows the identity but denies access due to insufficient permissions or a rejected token.

How to eliminate wrong answers

Option A is wrong because a malformed request (e.g., bad syntax or invalid JSON) would result in a 400 Bad Request, not 403. Option B is wrong because a non-existent resource returns a 404 Not Found, indicating the server cannot map the URI to a resource. Option C is wrong because temporary unavailability due to maintenance is represented by a 503 Service Unavailable, not 403.

49
Multi-Selectmedium

Which TWO of the following are valid branching strategies in Git? (Choose two.)

Select 2 answers
A.Rebase-only
B.Merge avoidance
C.Feature branching
D.Direct commit to main
E.GitFlow
AnswersC, E

Each feature is developed in its own branch.

Why this answer

Feature branching (C) is a valid Git branching strategy where each new feature is developed in its own branch, allowing isolated work without disrupting the main codebase. GitFlow (E) is another valid strategy that defines a strict branching model with master, develop, feature, release, and hotfix branches, commonly used for projects with scheduled releases.

Exam trap

Cisco often tests the distinction between Git operations (like rebase or merge) and actual branching strategies, so candidates mistakenly select 'Rebase-only' or 'Merge avoidance' as strategies when they are merely workflow tactics.

50
MCQhard

A developer is designing a microservices-based network management system. One requirement is that when a new device is discovered, multiple other services must be notified asynchronously to perform tasks like inventory update, monitoring setup, and log collection. Which architectural pattern best fits this requirement?

A.Event-driven architecture
B.Model-View-Controller (MVC)
D.Monolithic architecture
AnswerA

Event-driven architecture enables asynchronous communication via events, suitable for decoupled notification.

Why this answer

The event-driven architecture is correct because it enables asynchronous, decoupled communication between services. When a new device is discovered, an event (e.g., a message on a message broker like Kafka or RabbitMQ) is published, and multiple subscriber services (inventory, monitoring, logging) react independently without blocking the discovery service. This pattern directly supports the requirement for loose coupling and asynchronous notification.

Exam trap

Cisco often tests the distinction between synchronous (REST) and asynchronous (event-driven) communication patterns, and the trap here is assuming that RESTful APIs can be used for asynchronous notifications when they are inherently synchronous unless combined with additional mechanisms like webhooks or polling.

How to eliminate wrong answers

Option B (MVC) is wrong because it is a UI design pattern that separates an application into Model, View, and Controller components; it does not address inter-service asynchronous communication. Option C (RESTful API) is wrong because REST typically uses synchronous HTTP request-response calls, which would require the discovery service to wait for each notification to complete, violating the asynchronous requirement. Option D (Monolithic architecture) is wrong because it packages all functionality into a single deployable unit, which contradicts the microservices-based design and makes independent scaling and asynchronous notification difficult.

51
Multi-Selecthard

Which THREE of the following are characteristics of GraphQL compared to REST? (Choose three.)

Select 3 answers
A.Typically uses a single endpoint.
B.Strongly typed schema.
C.Client specifies exactly what data it needs.
D.Over-fetching of data is common.
E.Multiple endpoints for different resources.
AnswersA, B, C

/graphql endpoint.

Why this answer

GraphQL allows querying exactly needed data, uses a single endpoint, and clients specify fields.

52
MCQmedium

A developer needs to read a JSON configuration file and parse it into a Python dictionary. The file contains nested objects. Which code snippet correctly accomplishes this?

A.with open('config.json', 'r') as f: data = json.loads(f)
B.data = json.loads(open('config.json', 'r').read())
C.with open('config.json', 'r') as f: data = json.load(f)
D.with open('config.json', 'r') as f: data = json.dumps(f.read())
AnswerC

json.load() reads the file and parses it directly into a Python object.

Why this answer

The correct approach is to open the file with a context manager, read its contents, and use json.loads() to convert the JSON string to a dictionary.

53
MCQeasy

In Python, which data type is used to represent an unordered collection of unique elements?

A.set
B.tuple
C.list
D.dict
AnswerA

Set is unordered and contains only unique elements.

Why this answer

In Python, a set is the correct data type for representing an unordered collection of unique elements. Sets automatically enforce uniqueness by using a hash table internally, so duplicate values are ignored upon insertion. This makes them ideal for operations like membership testing and deduplication, where order is irrelevant.

Exam trap

The trap here is that candidates often confuse a set with a list or tuple because they think 'collection of items' implies order or mutability, but Cisco specifically tests the requirement for uniqueness and lack of order, which only the set satisfies.

How to eliminate wrong answers

Option B (tuple) is wrong because a tuple is an ordered, immutable collection that allows duplicate elements, not an unordered unique set. Option C (list) is wrong because a list is an ordered, mutable collection that permits duplicates and maintains insertion order. Option D (dict) is wrong because a dictionary stores key-value pairs with unique keys, but it is not a collection of elements; it maps keys to values and is unordered (in Python <3.7) or insertion-ordered (Python ≥3.7), not a simple set of unique items.

54
MCQeasy

In Python, which of the following is a valid way to define a function that accepts a variable number of positional arguments?

A.def func(args):
B.def func(args*):
C.def func(**kwargs):
D.def func(*args):
AnswerD

Yes, *args collects extra positional arguments.

Why this answer

Option D is correct because in Python, the `*args` syntax in a function definition allows the function to accept a variable number of positional arguments. The asterisk (`*`) collects all extra positional arguments into a tuple named `args`, enabling flexible argument handling.

Exam trap

Cisco often tests the distinction between `*args` (positional) and `**kwargs` (keyword) and may include syntactically invalid options like `args*` to catch candidates who misremember the asterisk placement.

How to eliminate wrong answers

Option A is wrong because `def func(args):` defines a function that accepts exactly one positional argument named `args`, not a variable number. Option B is wrong because `def func(args*):` is invalid Python syntax; the asterisk must precede the parameter name (i.e., `*args`), not follow it. Option C is wrong because `def func(**kwargs):` accepts a variable number of keyword arguments (collected into a dictionary), not positional arguments.

55
MCQeasy

When using the requests library in Python to send a POST request, which parameter should be used to send a JSON payload in the request body?

A.params=payload
B.files=payload
C.json=payload
D.data=json.dumps(payload)
AnswerC

The json= parameter handles serialization and header automatically.

Why this answer

The json= parameter automatically serializes the Python dictionary to JSON and sets the Content-Type header to application/json.

56
MCQeasy

Which HTTP status code indicates a successful POST request that created a resource?

A.200 OK
B.400 Bad Request
C.201 Created
D.204 No Content
AnswerC

Correct for resource creation.

Why this answer

201 Created is the standard response for a successful POST that creates a new resource.

57
MCQmedium

Which Git command is used to create a new branch and switch to it in one step?

A.git branch <branch>
B.git branch -d <branch>
C.git checkout <branch>
D.git checkout -b <branch>
AnswerD

This creates and switches to the new branch in one command.

Why this answer

The 'git checkout -b <branch>' command creates a new branch and switches to it immediately.

58
MCQeasy

A Python script uses the 'requests' library to make a POST request to create a new resource. Which HTTP status code indicates successful creation?

A.204 No Content
B.200 OK
C.301 Moved Permanently
D.201 Created
AnswerD

201 Created is the standard response for a successful POST request that creates a resource.

Why this answer

According to the REST API conventions, a successful POST request returns status code 201 Created.

59
Multi-Selecthard

Which THREE statements about RESTful APIs are true?

Select 3 answers
A.They require WebSockets for communication.
B.They use HTTP methods to perform CRUD operations.
C.They use SOAP as the message format.
D.They use stateless communication.
E.They expose resources via URLs.
AnswersB, D, E

GET, POST, PUT, DELETE map to read, create, update, delete.

Why this answer

Option B is correct because RESTful APIs use standard HTTP methods (GET, POST, PUT, PATCH, DELETE) to map directly to CRUD (Create, Read, Update, Delete) operations. For example, POST creates a resource, GET retrieves it, PUT/PATCH updates it, and DELETE removes it, aligning with the REST architectural constraint of uniform interface.

Exam trap

Cisco often tests the misconception that REST requires WebSockets for real-time communication or that REST is tied to SOAP, when in fact REST is protocol-agnostic but typically uses HTTP, and SOAP is a distinct, heavier-weight alternative.

60
Multi-Selecthard

Which THREE of the following are benefits of using event-driven architecture in a distributed system? (Choose three.)

Select 3 answers
A.Loose coupling between services
B.Real-time data processing
C.Scalability through independent processing
D.Eliminates the need for message brokers
E.Simpler debugging due to synchronous communication
AnswersA, B, C

Services communicate via events without direct dependencies.

Why this answer

Event-driven architecture promotes loose coupling, scalability, and real-time responsiveness.

61
Multi-Selectmedium

Which TWO HTTP status codes indicate client errors?

Select 2 answers
A.500 Internal Server Error
B.404 Not Found
C.400 Bad Request
D.200 OK
E.201 Created
AnswersB, C

The server cannot find the requested resource.

Why this answer

400 Bad Request and 404 Not Found are both client error statuses (4xx).

62
Multi-Selecteasy

A developer needs to create a Python script that makes a GET request to a REST API to retrieve a list of network devices. The API uses query parameters to filter by device type and status. Which TWO code snippets correctly include query parameters using the requests library? (Choose two.)

Select 2 answers
A.requests.get('https://api.example.com/devices', params={'type': 'router', 'status': 'active'})
B.requests.get('https://api.example.com/devices', data={'type': 'router', 'status': 'active'})
C.requests.get('https://api.example.com/devices?type=router&status=active')
D.requests.get('https://api.example.com/devices', json={'type': 'router', 'status': 'active'})
E.requests.get('https://api.example.com/devices', headers={'type': 'router', 'status': 'active'})
AnswersA, C

Correct use of params.

Why this answer

The params parameter accepts a dict; also can pass dict directly.

63
MCQmedium

A network automation script uses the requests library to retrieve device information from a REST API. The API requires authentication via a bearer token. Which code example correctly sets the Authorization header?

A.headers = {'Authorization': 'Token ' + token}\nresponse = requests.get(url, headers=headers)
B.response = requests.get(url, headers={'Authorization': token})
C.headers = {'Authorization': 'Bearer ' + token}\nresponse = requests.get(url, headers=headers)
D.response = requests.get(url, auth=('Bearer', token))
AnswerC

Correct usage of Bearer token authentication.

Why this answer

Option C is correct because it constructs the Authorization header using the 'Bearer' scheme, which is the standard method for passing OAuth 2.0 bearer tokens in HTTP requests. The requests library requires the header to be explicitly set as a dictionary, and the token must be prefixed with 'Bearer ' to comply with RFC 6750.

Exam trap

Cisco often tests the distinction between the 'Bearer' scheme and other authentication methods, and the trap here is that candidates confuse the auth parameter (which only supports Basic/Digest) with the need to manually set the Authorization header for bearer tokens.

How to eliminate wrong answers

Option A is wrong because it uses 'Token ' as the scheme prefix instead of 'Bearer ', which is the correct scheme for bearer tokens per OAuth 2.0 (RFC 6750). Option B is wrong because it passes only the token value without any scheme prefix, which will cause the API to reject the request as malformed. Option D is wrong because the requests library's auth parameter expects a tuple of (username, password) for Basic authentication, not a bearer token scheme.

64
MCQhard

A developer is writing a Python script that processes a large CSV file. The script uses 'with open(file, 'r') as f' to read the file. Why is this approach preferred over calling f = open(file) and then f.close()?

A.It automatically closes the file when the block exits, even if an exception is raised.
B.It allows the file to be opened in both read and write mode simultaneously.
C.It reduces memory usage by loading the file in chunks.
D.It increases the speed of file operations.
AnswerA

The context manager guarantees cleanup, which is the main advantage.

Why this answer

Option A is correct because the 'with' statement in Python implements a context manager that automatically calls the file object's __exit__ method when the block exits, ensuring the file is closed even if an exception occurs. This prevents resource leaks and is the recommended pattern for file I/O in Python, as explicitly calling f.close() may be skipped if an exception is raised before the close call.

Exam trap

Cisco often tests the distinction between a language feature (context managers) and unrelated performance or mode characteristics, so candidates may incorrectly associate 'with' with speed or chunking rather than its core purpose of guaranteed cleanup.

How to eliminate wrong answers

Option B is wrong because the 'with open(file, 'r')' opens the file in read-only mode, not both read and write simultaneously; to open in both modes you would use 'r+' or 'w+'. Option C is wrong because the 'with' statement does not inherently load the file in chunks; memory usage depends on how the file is read (e.g., using f.read() vs iterating line by line), not on the context manager itself. Option D is wrong because the 'with' statement does not increase the speed of file operations; it provides deterministic cleanup but does not affect I/O performance.

65
Multi-Selectmedium

Which TWO statements about the MVC pattern are correct? (Choose two.)

Select 2 answers
A.Model is dependent on the View.
B.Controller handles user input and updates the Model.
C.View displays data from the Model.
D.Model represents the user interface.
E.View directly modifies the Model.
AnswersB, C

Controller processes input.

Why this answer

MVC separates Model (data), View (UI), Controller (logic). Controller updates Model, View reflects Model.

66
MCQeasy

Which data structure in Python would be most appropriate for storing a collection of unique items and performing fast membership tests?

A.Tuple
B.Set
C.List
D.Dictionary
AnswerB

Sets are designed for unique elements and fast membership testing.

Why this answer

A set is the correct choice because it is implemented as a hash table in Python, which provides O(1) average-time complexity for membership tests using the `in` operator. Sets automatically enforce uniqueness, meaning duplicate items are not allowed, making them ideal for storing a collection of distinct elements. This directly matches the requirement for fast membership testing and uniqueness.

Exam trap

Cisco often tests the misconception that a dictionary is the best choice for fast membership tests because it also uses hashing, but the trap is that the question specifically asks for a collection of unique items, not key-value pairs, making a set the more precise and appropriate data structure.

How to eliminate wrong answers

Option A is wrong because a tuple is an immutable ordered sequence that allows duplicates and requires O(n) linear search for membership tests, making it unsuitable for fast lookups. Option C is wrong because a list is an ordered mutable sequence that also allows duplicates and requires O(n) linear search for membership tests, failing both the uniqueness and speed requirements. Option D is wrong because while a dictionary provides O(1) membership tests on its keys, it stores key-value pairs rather than just unique items, making it overkill and semantically incorrect for a simple collection of unique items.

67
MCQeasy

A Python script uses a dictionary to store device configuration parameters. Which key, if any, will raise a KeyError if it does not exist in the dictionary?

A.config.setdefault('timeout', 30)
B.config['timeout']
C.config.get('timeout')
D.config.pop('timeout', None)
AnswerB

Direct key access raises KeyError if the key does not exist.

Why this answer

Option B is correct because using square bracket notation (config['timeout']) on a dictionary will raise a KeyError if the specified key does not exist. This is a fundamental behavior of Python dictionaries: direct key access without a fallback mechanism throws an exception when the key is missing.

Exam trap

Cisco often tests the distinction between direct dictionary access (which raises KeyError) and safe access methods like .get(), .setdefault(), and .pop() with defaults, trapping candidates who assume all dictionary access methods behave identically.

How to eliminate wrong answers

Option A is wrong because dict.setdefault('timeout', 30) does not raise a KeyError; if the key 'timeout' does not exist, it inserts the key with the default value 30 and returns that value. Option C is wrong because dict.get('timeout') returns None (or a user-specified default) if the key is missing, never raising a KeyError. Option D is wrong because dict.pop('timeout', None) removes the key if it exists and returns its value; if the key does not exist, it returns the default value None without raising an error.

68
MCQeasy

Which Python data type is mutable and unordered?

A.List
B.Tuple
C.Dictionary
D.Set
AnswerC

Dicts are mutable and unordered (or insertion-ordered in 3.7+, but still considered unordered in context).

Why this answer

Option C (Dictionary) is correct because dictionaries in Python are mutable (you can add, remove, or change key-value pairs) and unordered (prior to Python 3.7, insertion order was not guaranteed; even with order preservation in CPython 3.7+, the data structure is conceptually unordered and accessed by key, not index). This matches the question's requirement for a mutable and unordered data type.

Exam trap

Cisco often tests the distinction between mutable vs. immutable and ordered vs. unordered, and the trap here is that candidates confuse the ordered nature of lists (mutable, ordered) with the unordered nature of dictionaries, or mistakenly think tuples are mutable because they can contain mutable objects.

How to eliminate wrong answers

Option A is wrong because a list is mutable but ordered (elements maintain insertion order and are accessed by index). Option B is wrong because a tuple is immutable (cannot be changed after creation) and ordered. Option D is wrong because a set is mutable and unordered, but the question asks for a data type that is both mutable and unordered, and while set fits, dictionary is the correct answer in the context of the provided options; however, note that set is also mutable and unordered, but the exam expects dictionary as the canonical answer for this pairing.

69
MCQhard

In the MVC (Model-View-Controller) pattern, which component is responsible for handling user input and updating the model?

A.Controller
B.Model
C.Router
D.View
AnswerA

Controller handles input and updates Model.

Why this answer

In the MVC pattern, the Controller is the component that receives user input (e.g., HTTP requests, button clicks) and translates it into commands that update the Model. It acts as the intermediary between the View and the Model, ensuring that user actions trigger appropriate changes in the application's data layer.

Exam trap

Cisco often tests the misconception that the Router is part of the MVC pattern, but in reality, the Router is a separate component used for URL dispatch, not for handling user input or updating the Model.

How to eliminate wrong answers

Option B is wrong because the Model is responsible for managing the application's data, business logic, and rules, not for handling user input directly. Option C is wrong because the Router is a component used in web frameworks (e.g., Express.js, Django) to map URLs to controllers, but it is not part of the core MVC pattern and does not handle user input or update the Model. Option D is wrong because the View is responsible for presenting data to the user and rendering the UI, not for processing user input or modifying the Model.

70
Multi-Selectmedium

A DevOps engineer is managing a Git repository and wants to discard local changes to a file and revert it to the last committed state. Which TWO commands can accomplish this? (Choose two.)

Select 2 answers
A.git reset --hard HEAD
B.git checkout -- <file>
C.git stash drop
D.git revert <file>
E.git restore <file>
AnswersB, E

This reverts the file to its state in the index (last staged version) or HEAD if not staged.

Why this answer

Both `git checkout -- <file>` and `git restore <file>` discard unstaged local changes to a file, reverting it to the content of the last commit (HEAD). `git checkout -- <file>` is the traditional command, while `git restore <file>` is the newer, more intuitive alternative introduced in Git 2.23. Both operate on the working tree without affecting the staging area or commit history.

Exam trap

Cisco often tests the distinction between commands that affect the entire repository (like `git reset --hard`) versus those that target a single file (like `git checkout -- <file>` or `git restore <file>`), leading candidates to incorrectly choose `git reset --hard HEAD` when only a single file needs reversion.

71
MCQmedium

A developer needs to create a Python function that accepts any number of keyword arguments and prints them. Which function definition correctly uses **kwargs?

A.def print_args(*args): print(args)
B.def print_args(kwargs): print(kwargs)
C.def print_args(**kwargs): print(kwargs)
D.def print_args(*kwargs): print(kwargs)
AnswerC

**kwargs collects keyword arguments into a dict.

Why this answer

Option C is correct because the **kwargs syntax in a Python function definition collects any number of keyword arguments into a dictionary. The function then prints that dictionary, which matches the requirement to accept and print any number of keyword arguments.

Exam trap

Cisco often tests the distinction between *args (positional arguments) and **kwargs (keyword arguments), and the trap here is that candidates confuse the single asterisk (*) for collecting keyword arguments instead of the double asterisk (**).

How to eliminate wrong answers

Option A is wrong because *args collects positional arguments into a tuple, not keyword arguments. Option B is wrong because it defines a single parameter named 'kwargs' that expects a single positional argument, not any number of keyword arguments. Option D is wrong because *kwargs uses the single-asterisk syntax, which collects positional arguments into a tuple, not keyword arguments into a dictionary.

72
MCQhard

In a microservices architecture, which of the following is a primary advantage over a monolithic architecture?

A.Easier end-to-end testing
B.Lower operational overhead
C.Simpler inter-service communication
D.Independent deployability and scaling of services
AnswerD

Each service can be deployed and scaled independently, improving agility.

Why this answer

Microservices allow independent deployment and scaling of services, which is a key advantage.

73
Multi-Selectmedium

A Python script needs to iterate over a dictionary of network interfaces and print each interface name and its IP address. The dictionary is structured as: {'GigabitEthernet1/0/1': '10.1.1.1', 'GigabitEthernet1/0/2': None}. Which THREE code snippets correctly iterate and print the key-value pairs, skipping entries with None? (Choose three.)

Select 4 answers
A.for iface, ip in interfaces.items(): if ip != None: print(f'{iface}: {ip}')
B.for iface, ip in interfaces.items(): if ip: print(f'{iface}: {ip}')
C.for iface in interfaces.keys(): print(iface + ': ' + interfaces.get(iface))
D.for iface in interfaces: ip = interfaces[iface] if ip is not None: print(iface + ': ' + ip)
E.for iface in interfaces: if interfaces[iface]: print(iface, ':', interfaces[iface])
AnswersA, B, D, E

Explicit None check.

Why this answer

Option A is correct because it uses the `.items()` method to iterate over key-value pairs, explicitly checks `if ip != None` to skip entries with `None`, and uses an f-string for clean output. This directly meets the requirement to skip `None` values while printing each interface name and IP address.

Exam trap

Cisco often tests the distinction between checking for `None` explicitly versus relying on truthiness, and the subtle formatting differences in print statements (comma vs. concatenation vs. f-strings) to catch candidates who overlook exact output requirements.

74
MCQhard

Given the Python list comprehension: result = [x*2 for x in range(10) if x > 5] What is the value of result?

A.[12, 14, 16, 18]
B.[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
C.[10, 12, 14, 16, 18]
D.[6, 7, 8, 9]
AnswerA

Correct: x=6->12, 7->14, 8->16, 9->18.

Why this answer

The list comprehension `[x*2 for x in range(10) if x > 5]` iterates over `x` from 0 to 9, filters to only include `x` values greater than 5 (i.e., 6, 7, 8, 9), and multiplies each by 2, producing `[12, 14, 16, 18]`. This is a standard Python comprehension with a conditional filter.

Exam trap

The trap here is that candidates often forget the filter condition and include all values, or they mistakenly apply the multiplication to the filtered indices rather than the values, leading to options like C or D.

How to eliminate wrong answers

Option B is wrong because it includes all numbers from 0 to 9 multiplied by 2, which would result from omitting the `if x > 5` filter. Option C is wrong because it incorrectly includes 10 (from x=5), but the condition `x > 5` excludes 5, so 5*2=10 should not be present. Option D is wrong because it lists the unfiltered x values (6,7,8,9) instead of the doubled results, confusing the iteration variable with the output expression.

Ready to test yourself?

Try a timed practice session using only Devnet Software Dev questions.