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

Free WGU Foundations of Programming (Python) Foundations-of-Programming-Python Exam Questions

Last updated: · 11 practice questions with answers and explanations

Page: 1 / 6 Total 60 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Python syntax and structure

Skill tested: Identify indentation and statement syntax errors in a short Python function.

A small analytics team is reviewing a script before adding it to its scheduled reporting workflow. The function should print a status message only when the supplied record count is zero. The script currently fails before producing any output, and the editor reports an indentation-related syntax error. The team wants the smallest change that preserves the intended condition and message; rewriting the function or adding exception handling is out of scope. Which version is syntactically valid and implements the stated behavior?

Correct Answer: A. def report(count): if count == 0: print("No records")
Explanation:

Python uses indentation to delimit function and conditional bodies, so the `if` statement must be indented inside the function and its `print` statement further indented inside the condition. The function definition also requires a colon, and a comparison in an `if` condition uses `==`. B leaves the function body unindented, C omits the colon after the function header, and D uses assignment syntax where a comparison is required.

Question 2

New Single answer

Topic: Variables and data types

Skill tested: Trace integer-to-string conversion and predict the resulting output and runtime behavior.

A logistics script reads a package count from a text file. The read operation returns the text `"12"`, and the script then executes `count = int(raw)` followed by `message = "Packages: " + count`. The process stops at the second statement, although the conversion succeeds. The developer must keep `count` as an integer because a later calculation adds counts from several files, but the displayed message must include the number. Which change best meets both requirements without changing the input format?

Correct Answer: B. Change the message expression to `"Packages: " + str(count)`.
Explanation:

After `int(raw)`, `count` is an integer. Python does not implicitly concatenate an integer with a string, so the second statement raises a `TypeError`. Converting `count` to a string only when building the display message preserves the integer for later arithmetic. A leaves `count` as text and therefore undermines the later calculation. C still attempts to concatenate a string and an integer, while D leaves `raw` as a string and has the same concatenation problem.

Question 3

New Multiple answers

Topic: Control flow, conditionals and loops

Skill tested: Trace loop state updates and distinguish loop termination from conditional branching.

A monitoring script examines a sequence of readings and counts values that exceed a threshold. The team uses this code:

```python
readings = [3, 8, 5, 9]
count = 0
for value in readings:
if value > 5:
count += 1
print(count)
```

A report should show the number of qualifying readings, and an engineer claims the program prints `2` because only two values exceed 5. Another engineer says the loop stops after the first qualifying reading. Select TWO statements that correctly describe Python's execution of this code and the resulting output.

Correct Answer: D. The output is `2` because the values 8 and 9 each increment `count` once.; E. The loop processes each value in the list unless an explicit control-flow statement exits it.
Explanation:

A `for` loop iterates through every element of `readings`; an `if` statement selects whether its indented body runs for the current element but does not end the loop. The values 8 and 9 satisfy `value > 5`, so each executes `count += 1`, producing a final count of 2. C confuses conditional branching with loop termination. D misinterprets augmented assignment, which adds one to the existing count. E overlooks that the increment is conditional.

Question 4

New Single answer

Topic: Functions and modular code

Skill tested: Determine how local assignment affects a function result and an outer variable.

A billing module has a module-level discount rate used by several functions. A new function is intended to calculate a discounted total without changing that shared rate:

```python
discount = 0.10

def total_after_discount(amount):
discount = 0.15
return amount * (1 - discount)

subtotal = 200
result = total_after_discount(subtotal)
```

The developer expects the new function to apply a 15 percent discount to this calculation only, while later code should still see the original 10 percent module-level value. Which statement correctly describes the function's behavior after it is called?

Correct Answer: A. `result` is 170, and the module-level `discount` remains 0.10.
Explanation:

Assignment to `discount` inside the function makes it a local variable in that function. The return expression therefore uses the local value 0.15, calculating 200 × 0.85 = 170. The assignment does not modify the module-level variable, which remains 0.10. There is no `UnboundLocalError` because the local name is assigned before it is read. D gets the calculation right but incorrectly claims the local assignment changes the outer variable.

Question 5

New Multiple answers

Topic: Basic data structures

Skill tested: Choose mutable and keyed data structures to represent ordered records and retrieve them by identifier.

A repair shop imports a batch of jobs in a defined order. Staff need to append newly received jobs, update the status of an existing job, and quickly retrieve a job by its unique ticket number. A job has a ticket number and a status. The implementation should use only built-in Python data structures and avoid maintaining two separate sources of truth. Select TWO design statements that satisfy these requirements.

Correct Answer: A. Store ticket-to-job mappings in a dictionary so a ticket number can be used as a key.; C. Store the ordered jobs in a list and append each newly received job to that list.
Explanation:

A list is a suitable mutable sequence for preserving the imported order and appending new jobs. A dictionary keyed by ticket number provides direct retrieval by that identifier and supports updating the associated job record. C is unsuitable because tuples are immutable. D is invalid as described: dictionaries are unhashable and cannot be set elements, and a set is not the appropriate ordered, keyed mapping. E cannot update a tuple in place; it would require replacing the tuple, and a list alone does not provide keyed lookup.

Question 6

New Single answer

Topic: Debugging and troubleshooting

Skill tested: Use a traceback and type reasoning to locate and correct a runtime error.

A data-cleaning script fails on this line while processing a file:

```python
age = int(row["age"])
```

The traceback ends with `ValueError: invalid literal for int() with base 10: ''`. The file contains some rows where the `age` field is an empty string; other rows contain values such as `"34"`. The requirement is to retain valid numeric ages and skip rows with missing ages, without terminating the entire import. What is the most appropriate focused correction?

Correct Answer: C. Check whether `row["age"]` is nonempty before converting it, and skip or handle the row when it is empty.
Explanation:

The traceback identifies an invalid integer conversion, and the supplied value `''` explains the `ValueError`: an empty string is not a valid base-10 integer literal. Checking for a nonempty value before conversion allows the program to skip or otherwise handle missing-age rows while retaining valid numeric ages. `float('')` also fails, so A does not solve the cause. C does not correctly filter every row and changes loop behavior. D leaves the value empty and therefore still fails conversion.

Question 7

New Single answer

Topic: Development environments and tools

Skill tested: Run a saved Python script from a command line using the interpreter.

An operations analyst has saved a script named `weekly_report.py` in a project directory. The script is intended to be run as a complete program, and the analyst wants to execute that saved file from a terminal rather than enter statements interactively. The terminal is already open in the directory containing the script, and Python is installed and available through the `python` command. Which command should the analyst run?

Correct Answer: B. `python weekly_report.py`
Explanation:

Running `python weekly_report.py` starts the Python interpreter and passes the saved file as the program to execute. Because the terminal is already in the script's directory and `python` is available, no path adjustment is needed. Starting `python` alone opens the interactive interpreter; typing a filename there as though it were a command does not run the file. The other forms reverse the expected command order or use a command that is not the stated Python invocation.

Question 8

New Single answer

Topic: Python syntax and structure

Skill tested: Distinguish comments from executable code and preserve valid expression syntax.

A team documents a calculation in a script that must continue to execute without changing its result. The original line is `total = price * quantity`. A developer tries to add an inline note but writes `total = price * quantity # calculate total` without spaces around the comment marker. Another reviewer is concerned that the marker will invalidate the expression. Which statement accurately describes the line's syntax and execution?

Correct Answer: B. The line is valid; Python treats text after `#` as a comment, and the assignment computes the product.
Explanation:

In Python, `#` begins a comment that continues to the end of the physical line, including when it follows executable code. The interpreter evaluates `price * quantity` and ignores the trailing note, so the assignment's result is unchanged. B incorrectly restricts comments to standalone lines. C mistakes comment text for a string value; no string literal or concatenation appears. `//` is Python's floor-division operator, not its comment marker, so D would change the expression rather than add a comment.

Question 9

New Multiple answers

Topic: Variables and data types

Skill tested: Select safe conversions for numeric input and preserve the intended numeric type.

A command-line tool asks users to enter a whole number of items, then calculates the cost using a decimal unit price. The input function returns text, and the tool must reject nonnumeric entries rather than silently treat them as zero. For valid entries, the item count must remain suitable for whole-number arithmetic and the total must support fractional currency amounts. Select TWO implementation statements that meet these requirements.

Correct Answer: A. Convert the input text to `int` before multiplying it by the unit price.; B. Catch `ValueError` from the integer conversion and ask for a valid whole-number entry again.
Explanation:

`int` converts valid whole-number text to an integer, which is appropriate for an item count. Multiplying that integer by a decimal unit price produces a numeric result that can represent a fractional amount. Invalid integer text raises `ValueError`; catching that error and prompting again meets the requirement to reject invalid entries rather than silently substitute a value. B retains text and cannot multiply it by a floating-point price. C accepts fractional counts and does not handle invalid input as required. E is incorrect because `int` raises an error rather than converting invalid text to zero.

Question 10

New Single answer

Topic: Control flow, conditionals and loops

Skill tested: Trace a while loop that updates its condition and identify its final printed value.

A warehouse script reduces a pending-unit counter by one each time a unit is processed. A test run uses:

```python
pending = 3
while pending > 0:
pending -= 1
print(pending)
```

A reviewer worries that the loop may run forever because the variable appears in its own condition. The script must process units until none remain and then print the final counter. Assuming the code runs as shown, what does it print, and why does execution terminate?

Correct Answer: A. It prints `0` because each iteration decrements `pending` until the condition is false.
Explanation:

The loop checks `pending > 0` before each iteration. Starting at 3, the body reduces it to 2, then 1, then 0; at that point the condition is false and control moves to `print`, which outputs `0`. The loop terminates because the body updates the condition variable toward the stopping condition. A places the print in the wrong execution order. C describes behavior that `while` does not have, and changing a condition variable inside its loop is valid Python, contrary to D.

Question 11

New Single answer

Topic: Functions and modular code

Skill tested: Trace positional arguments and return values when a function call omits an argument.

A small application defines a reusable formatter:

```python
def label(item, category="general"):
return category + ": " + item

text = label("sensor", "hardware")
```

A reviewer must confirm the output before the function is used to generate inventory labels. The function has one default parameter, and the call supplies two positional arguments. No global variables or other code affect these values. What value is assigned to `text`?

Correct Answer: D. `"hardware: sensor"`
Explanation:

Positional arguments bind from left to right: `"sensor"` becomes `item`, and `"hardware"` becomes `category`. Since the call supplies the second argument explicitly, the default `"general"` is not used. The function returns `category + ": " + item`, yielding `"hardware: sensor"`. A would apply only if the second argument were omitted. B reverses the function's concatenation order, and D omits the category and separator included in the returned value.