Exam Information
Free practice questions with explanations
WGU Foundations-of-Programming-Python Practice Questions
Answer a question to see the correct answer and the explanation, or click Show answer. Newest questions first.
- Questions
- 18
- Answered
- 0
- Correct
- 0
- Score
- -
-
1 Question 1 Single choice Variables, Data Types, and Basic Operations
A logistics team stores shipment weights read from a CSV file as strings such as "12.5" and "7". A script must compute the total weight and print it with exactly one decimal place. The team has a strict rule that the script must not lose precision by converting weights to integers. Which approach meets all requirements?
Correct Answer: AExplanationThe float() constructor parses decimal strings such as "12.5" into floating-point numbers, so the sum keeps the fractional part, and the .1f format specifier rounds the display to one decimal place. int() raises a ValueError on "12.5" and would lose precision even on values it accepts, which violates the stated rule. Concatenating strings produces "12.57" style text that float() reads as one large number, a silent logic error. bool() returns True for any non-empty string, so it never yields a weight total.
-
2 Question 2 Single choice Control Flow and Decision Making
A warehouse script assigns a shipping tier to each order. Orders weighing more than 50 kg always go to the heavy tier, unless the order is marked express, in which case they go to the priority tier. Orders of 50 kg or less go to the standard tier. A developer writes a chain of if/elif statements and notices that express orders over 50 kg are reaching the heavy tier. Which correction resolves the defect without changing the behaviour for other orders?
Correct Answer: DExplanationPython evaluates an if/elif chain top to bottom and executes only the first branch whose condition is true, so the heavy-weight branch currently captures express orders before the express check runs. Placing the express condition first, combined with the weight rule, sends heavy express orders to the priority tier. Replacing elif with if would let multiple branches run and assign conflicting tiers. Changing the comparison to 50 or more alters the behaviour for orders of exactly 50 kg, which the requirements did not ask for. Applying not to the weight condition inverts the rule for every order and does not isolate express orders.
-
3 Question 3 Single choice Loops and Iteration
A data quality script reads a list of sensor readings in which a value of -999 marks a failed sensor. The script must process every valid reading, skip failed readings, and stop completely as soon as it encounters a reading whose value is None, because that indicates the feed has been truncated. A developer wants the loop to behave correctly on all three cases. Which loop structure meets the requirement?
Correct Answer: DExplanationA failed reading should be skipped and processing should go on, which is the job of continue, while a truncated feed must end the whole iteration, which is the job of break. Swapping the two keywords would stop at the first failed sensor and carry on past a truncated feed. Using continue for None would ignore the truncation signal and keep reading. pass does nothing and would fall through to processing the -999 value, and return would only work inside a function, which the stem does not describe.
-
4 Question 4 Single choice Functions and Modular Programming
A team maintains a reporting module in which a function apply_discount(price, rate) multiplies the price by (1 - rate) and returns the result. A later refactor adds a global variable TAX_RATE and a second function, total_with_tax(price), that references TAX_RATE. A junior developer inserts the line TAX_RATE = 0.2 inside total_with_tax before using it, and the module now raises UnboundLocalError on the first call. The team needs total_with_tax to read the module-level value and must avoid duplicating the constant. What is the correct fix?
Correct Answer: DExplanationAny name that is assigned anywhere inside a function body is treated as local for that whole function, which is why the earlier read of TAX_RATE fails with UnboundLocalError. Declaring global TAX_RATE tells Python to use the module-level name, and removing the local assignment keeps a single source of truth. The nonlocal keyword only applies to enclosing function scopes, not module scope, so it is a syntax error here. Adding a parameter with an assigned default still leaves the constant duplicated in the body. Moving the assignment into a different function does not make it visible to total_with_tax at all.
-
5 Question 5 Single choice Data Structures and Input/Output
A school district stores student records in a Python dictionary keyed by student ID, with each value being a tuple of (name, grade_level). A reporting script must print each student's name and grade level in ascending order of student ID. The IDs are strings such as "S1042" and "S998", and the district has confirmed that lexicographic ordering of the strings is the intended order. The data must not be modified in place. Which code achieves this?
Correct Answer: DExplanationsorted() applied to a dictionary returns a new list of its keys in ascending order without changing the dictionary, which satisfies the no-modification rule and the lexicographic requirement. dict has no sort() method, so the second option raises AttributeError. Iterating over values() yields tuples rather than IDs, so the loop prints tuple fragments and ignores the requested ordering. Sorting in reverse produces descending order, violating the stated requirement.
-
6 Question 6 Single choice Variables, Data Types, and Basic Operations
A finance application stores monetary amounts as float values. An auditor reports that summing 0.1 ten times yields a total that is not exactly 1.0, and the application's end-of-day check fails. The company policy forbids rounding errors in currency calculations, and every amount has at most two decimal places. The developer must change the representation with the least disruption to existing integer and string handling in the program. Which change best meets the requirement?
Correct Answer: DExplanationBinary floating-point cannot represent 0.1 exactly, which is why repeated addition drifts, and storing amounts as integer cents keeps every operation exact because Python integers are arbitrary-precision. Formatting to two decimals happens only at output, so the rest of the program's integer handling is untouched. Rounding after each addition still uses the float representation and can accumulate error between steps. String concatenation does not perform arithmetic and would produce incorrect totals. Converting to bool discards the amount entirely.
-
7 Question 7 Single choice Control Flow and Decision Making
A access-control function must grant entry only when a user is an active employee, or when the user is a contractor whose contract has not expired and who has a badge number on file. The function receives boolean flags active_employee, contractor, contract_valid, and has_badge. A reviewer notes that the draft expression active_employee or contractor and contract_valid and has_badge grants access to contractors with no badge in some cases. Which expression correctly implements the policy?
Correct Answer: DExplanationThe policy has two independent grant paths, and parentheses must group the contractor conditions together so that all three must hold before the contractor path grants access. Python evaluates and before or, so the draft expression applies the contract and badge checks only to the contractor term in a way that leaks access in the reviewer's case. Grouping the whole employee-or-contractor clause with a shared contract and badge check would block active employees who lack a badge, violating the policy. Using or between contract_valid and has_badge would grant contractors with only one of the two. Negating the combination changes the logic entirely and locks out active employees who are also contractors.
-
8 Question 8 Single choice Loops and Iteration
A text-processing utility must count how many times each vowel appears in a user-supplied string, ignoring case and ignoring non-letter characters. The string may be very long, and the team runs the utility on a shared server where memory is constrained. The team wants the simplest correct solution that iterates through the characters of the string directly. Which implementation is best?
Correct Answer: CExplanationIterating directly over the lowercased string with a for loop processes each character once, and a dictionary of vowel keys gives constant-time lookups without building large intermediate structures, which suits the memory constraint. Building a full sorted list of characters uses extra memory proportional to the input and adds unnecessary work. Repeatedly calling pop(0) on a list shifts all remaining elements each time, making the loop quadratic on long input. A recursive function would hit Python's recursion limit on long strings and the stem asked for direct iteration.
-
9 Question 9 Single choice Data Structures and Input/Output
A small clinic receives appointment requests as lines typed into a console program. Each line has the form name,date,time, for example Lee,2026-06-01,09:30. The program must reject any line that does not contain exactly three comma-separated fields, and must print a message identifying the bad line rather than crashing. The clinic also requires that blank lines be ignored silently. Which approach satisfies all of these rules?
Correct Answer: DExplanationStripping whitespace before checking for emptiness lets blank lines be skipped silently, and checking the length of the split list enforces the exact three-field rule before any unpacking occurs. Direct unpacking raises ValueError, not IndexError, when the field count is wrong, so catching only IndexError would let the program crash. Counting commas alone does not handle blank lines and assigns fields without validation. Joining all input into one string removes the line-by-line identification the clinic requires and makes error reporting per line impossible.
-
10 Question 10 Single choice Functions and Modular Programming
A developer wrote a function compute_average(values) that returns the arithmetic mean of a list of numbers. A colleague calls compute_average([]) during testing and the program raises ZeroDivisionError. The team wants the function to return None for an empty input and to keep its existing contract for non-empty input. The function is called from many modules, so the signature must not change. Which implementation achieves this?
Correct Answer: DExplanationA guard clause checks for an empty list before dividing, returning None in that case and leaving the signature and the non-empty behaviour intact. Catching the exception and returning 0 gives a misleading average of zero rather than the required None. Adding a default parameter changes the signature and does not handle an explicitly passed empty list. math.fsum does not remove the division, and round() does not prevent a zero-length divisor from failing.
-
11 Question 11 Single choice Variables, Data Types, and Basic Operations
A script reads a configuration value from a text file. The value is the string "0" when a feature is disabled and "1" when enabled, but a developer has written if flag: intending to test for enabled. The team now sees the feature active when the file contains "0". The file format cannot change because other systems depend on it. Which correction is the most precise fix?
Correct Answer: DExplanationEvery non-empty string is truthy in Python, so "0" evaluates as true in an if test, which explains the defect. Converting to int first yields 0 or 1, and comparing against 1 correctly identifies the enabled state. bool("0") returns True because it is a non-empty string, so the third option repeats the defect. Checking for None does not detect the disabled value, and checking length only distinguishes certain string shapes without interpreting the value.
-
12 Question 12 Single choice Loops and Iteration
A batch job processes a list of customer IDs and calls an external service for each one. The service returns HTTP 429 when the rate limit is exceeded, and the team's policy is to wait and retry the same ID up to three times before logging a failure and moving to the next ID. The retry logic must not affect IDs that succeed on the first attempt. Which loop design implements this policy correctly?
Correct Answer: DExplanationNesting a bounded for loop over range(3) inside the ID loop gives exactly three attempts per ID, and break exits the retry loop as soon as the call succeeds, so first-attempt successes are unaffected. The failure logging placed after the inner loop runs only when all attempts are exhausted, as the policy requires. An unbounded retry violates the three-attempt limit. Using continue on failure retries the ID on a later pass of the outer loop rather than immediately, and it also breaks the per-ID limit. The never-terminating outer loop prevents the job from completing.
-
13 Question 13 Multiple choice Data Structures and Input/Output
A data engineer is preparing a Python program that reads a text file of product records, one per line, in the form sku,quantity,price. The file may contain a header line, blank lines, and lines with malformed numbers. The program must total quantity times price for valid records and write rejected lines to a separate file for review. The original file must never be modified. Which TWO implementation choices together meet these requirements? (Choose two.)
Correct Answer: A, EExplanationOpening the source in read mode guarantees it is never modified, and a with statement for each file closes handles reliably, while the rejects file is opened in write mode as a separate output. Catching ValueError around the numeric conversions isolates malformed numbers and lets the offending line be written to the review file, which satisfies the rejection requirement. Opening the input in write mode truncates it, destroying the source data. Splitting the whole file on commas merges records across lines and breaks the per-record logic. A bare except hides errors and prevents the rejects file from being populated.
-
14 Question 14 Multiple choice Control Flow and Decision Making
A subscription service decides whether a customer receives a loyalty discount. The customer qualifies if they have been a member for at least 12 months and have made no more than two late payments, or if they hold a corporate account regardless of tenure or payment history. The program has variables months_member, late_payments, and corporate. Which TWO conditional expressions are correct implementations of this rule? (Choose two.)
Correct Answer: C, EExplanationBoth expressions group the tenure-and-payments condition together and combine it with corporate by or, which matches the two independent qualifying paths in the policy. Swapping the order of the operands does not change the result, so both are equivalent. The third expression lets a member with many late payments qualify through the late_payments clause alone, which the policy does not permit. The fourth is the negation of the disqualifying case rather than the qualifying condition, so it is inverted. The fifth requires tenure of 12 months even for corporate accounts, which the policy exempts.
-
15 Question 15 Multiple choice Functions and Modular Programming
A payroll module contains the function calculate_overtime(hours, rate), which returns the overtime pay for hours above 40 at 1.5 times the rate. Another developer must call it from a separate script and also reuse it in a unit test without running the full payroll report. Which TWO practices make the function reusable and testable as described? (Choose two.)
Correct Answer: A, EExplanationReturning the computed value lets the function be used inside expressions and checked with assertions in a unit test, while printing and returning None prevents that reuse. The __name__ guard ensures that importing the module from a test or another script does not trigger the full payroll report, which is the stated requirement for running the function alone. Reading a global rate hides a dependency and makes calls depend on hidden state. Defining the function inside the report loop ties it to that context and prevents clean import.
-
16 Question 16 Multiple choice Variables, Data Types, and Basic Operations
A mobile app stores a user's age as the string "34" read from a form. The app must check whether the age is at least 18 before showing a restricted feature, and it must also display the age plus one year on a confirmation screen. A developer also needs to make sure a blank field does not crash the program. Which TWO code approaches correctly accomplish these requirements? (Choose two.)
Correct Answer: A, DExplanationConverting with int() inside a try block handles both the conversion and the blank-field case by catching ValueError, and then the integer supports the comparison and the addition. Checking isdigit() after stripping whitespace is a validation approach that also avoids the conversion error, and only then does int() run. Python does not convert strings to numbers in comparisons or addition, so comparing text to 18 raises TypeError and text + 1 raises TypeError as well. float conversion of an empty string still raises ValueError, so there is no safe path without handling it. Comparing strings with ">=" uses lexicographic order, so "9" would be treated as greater than "18".
-
17 Question 17 Single choice Loops and Iteration
A teacher wants a program to print the numbers from 1 to 100 that are divisible by 7, but it must stop printing as soon as a number divisible by 49 appears, because the remaining numbers are reserved for a later exercise. A student has written a loop that prints the correct values up to 49 but then keeps printing 56, 63, and so on. Which change makes the loop stop at the first multiple of 49?
Correct Answer: DExplanationReplacing continue with break inside the check for multiples of 49 exits the loop entirely, so no further numbers are printed once 49 is reached. Changing the range to 50 would also stop at 49 but ignores the stated rule that the stop depends on finding a multiple of 49, and the rule should drive termination rather than a hard-coded bound. Adding pass does nothing. Moving the check and using continue only skips the current iteration and keeps the loop running.
-
18 Question 18 Single choice Functions and Modular Programming
A developer defines a function with a mutable default argument: def add_item(item, cart=[]): cart.append(item); return cart. In a web application, separate customers report that their carts contain items from other customers' sessions. The team must fix the defect while preserving the call signature add_item(item) for existing callers. Which change is correct?
Correct Answer: DExplanationThe default list is created once when the function is defined and then shared across every call, which is why items leak between customers. Using None as the sentinel and creating a fresh list inside the body gives each call its own list while keeping add_item(item) valid. Converting an empty tuple still returns a new list, but the call pattern here passes the cart each time and the stem asks about preserving callers, and the tuple default does not clearly express intent. Clearing the shared list would wipe it for other callers and break the session logic. Removing the default breaks every existing caller that relies on the one-argument form.
These are 18 of the 60 questions in the full Foundations-of-Programming-Python pack.
Get All 60 QuestionsGet all 60 questions & answers
Full access options for WGU Foundations-of-Programming-Python
Self-study
PDF Version
- 60 actual exam questions
- Compatible with all devices
- Printable PDF format
- No download limits
- 90 days free updates
- 24/7 customer support
Best value
Bundle Pack
- Discounted PDF + online access
- 60 actual exam questions
- Both PDF and online practice test
- Free 90 days updates
- No download or practice limits
- 24/7 customer support
Exam simulation
Online Practice Test
- 60 actual exam questions
- Actual exam environment
- 90 days free updates
- Browser-based software
- 24/7 customer support
100% Money Back Guarantee
Your success comes first
At DumpsProvider, we give you a 100% money back guarantee on all of our exam dumps. For us, your success is the #1 priority and we are more than confident that our exam material will help you pass the Foundations-of-Programming-Python Exam (Foundations of Programming (Python)) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.