Follow each number by a space.

Basic while loop expression.

Write a while loop that prints userNum divided by 4 (integer division) until reaching 2 or less. Follow each number by a space. Example output for userNum = 160:

40 10 2

Note: These activities may test code with different test values. This activity will perform four tests, with userNum = 160, then with userNum = 8, then with userNum = 0, then with userNum = -1. See “How to Use zyBooks”.

Also note: If the submitted code has an infinite loop, the system will stop running the code after a few seconds, and report “Program end never reached.” The system doesn’t print the test case that caused the reported message.

The Correct Answer and Explanation is:

Here’s the correct Python code for the task:

userNum = int(input())

while userNum > 2:
    userNum = userNum // 4
    print(userNum, end=' ')

🔍 Explanation (300+ words)

This program demonstrates how to use a basic while loop in Python to repeatedly divide a number by 4 using integer division, and print each result until the value becomes 2 or less.

✅ Code Breakdown:

userNum = int(input())
  • This line takes an integer input from the user and stores it in the variable userNum.
while userNum > 2:
  • This line starts a loop that will continue as long as userNum is greater than 2.
  • The loop’s exit condition is when userNum becomes 2 or less.
    userNum = userNum // 4
  • Inside the loop, we update the value of userNum by dividing it by 4 using floor division (//), which returns the integer part of the division result (i.e., no decimals).
  • This ensures that we are always working with whole numbers.
    print(userNum, end=' ')
  • The result of each division is printed, followed by a space.
  • The end=' ' argument ensures that outputs appear on the same line, separated by spaces.

📌 Sample Execution:

  1. Input: 160
  • Loop iterations:
    160 // 4 = 40
    40 // 4 = 10
    10 // 4 = 2 (loop stops here since userNum is now ≤ 2)
  • Output: 40 10 2
  1. Input: 8
  • 8 // 4 = 2 → loop ends
  • Output: 2
  1. Input: 0 or -1
  • Since userNum is not greater than 2, the loop doesn’t run.
  • Output: (nothing printed)

🛑 Infinite Loop Protection:

This program avoids an infinite loop because:

  • The userNum is constantly reduced.
  • Eventually, it will be ≤ 2, which stops the loop.

⚠️ Common Mistakes:

  • Using / instead of // results in a float and might not meet the expected output.
  • Forgetting to update userNum inside the loop causes infinite loops.
  • Not checking the condition userNum > 2 properly leads to incorrect output or infinite loops.

This example is a foundational concept for understanding loop control, conditions, and integer operations in Python.

Scroll to Top