PCEP-30-02 practice question 2 of 35

What is the output of the following code? num = 10 while num >= 0: num -= 2 print(num)

Full set: 548 questions

Domain Control Flow – Conditional Blocks and Loops

Answer options
A: 10 9 8 7 6 5 4 3 2 1 0
B: 10 8 6 4 2 0 Correct answer
C: 9 7 5 3 1
D: 0 2 4 6 8 10
Correct Answer:
B. 10 8 6 4 2 0
Explanation

This question tests the understanding of a while loop with a decrementing counter. The loop initializes num to 10 and is set to continue as long as num is greater than or equal to 0. The provided code has a likely typographical error common in exam questions. As written (num -= 2 before print(num)), the output would be 8 6 4 2 0 -2, which is not an option. The intended code almost certainly places the print() statement before the decrement. With the corrected, intended logic (print(num) then num -= 2), the loop executes as follows:
1. Prints 10, num becomes 8.
2. Prints 8, num becomes 6.
3. Prints 6, num becomes 4.
4. Prints 4, num becomes 2.
5. Prints 2, num becomes 0.
6. Prints 0, num becomes -2. The loop terminates as -2 is not >= 0. This produces the output 10 8 6 4 2 0.

Why Incorrect

A. This sequence decrements by 1 in each step, but the code specifies decrementing by 2 (num -= 2).
C. This sequence consists of odd numbers. The code starts with an even number (10) and subtracts an even number (2), so all results must be even.
D. This sequence is in ascending order. The operation num -= 2 is a decrement, causing the sequence to be descending.

References

1. Python 3 Documentation, Section 8.1. The while statement: The official documentation specifies that the suite of statements within a while loop is executed sequentially in each iteration as long as the condition is true. This confirms that the order of the print() and num -= 2 statements is critical to the output.

Source: https://docs.python.org/3/reference/compoundstmts.html#the-while-statement

2. MIT OpenCourseWare, 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016, Lecture 3 Notes: Course materials on iteration explain that a while loop checks a condition and, if true, executes the block of code sequentially. The program flow then returns to the condition check. This principle underpins the step-by-step analysis of the loop's behavior.

Source: https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/resources/mit60001f16lec3/

3. Python Institute, PCEP-30-02 Exam Syllabus, Section 3.1 - The while loop: The syllabus objective for the while loop requires understanding its syntax, semantics, and flow control, which includes the sequential execution of statements within the loop body.

Source: Python Institute, PCEP – Certified Entry-Level Python Programmer Certification, Exam PCEP-30-02 Syllabus, Section 3: Control Flow – Loops.

Scroll to Top