Python 5.2.2: Basic while loop with user input

?Python 5.2.2: Basic while loop with user input.

Write an expression that executes the loop body as long as the user enters a non-negative number.

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.

Sample outputs with inputs: 9 5 2 -1

Body

Body

Body

Done

The Correct Answer and Explanation is :

Correct Answer:

# Get the first user input
num = int(input())

# Loop runs as long as the number is non-negative
while num >= 0:
    print("Body")
    num = int(input())  # Get the next input

print("Done")

Explanation (300 Words)

A while loop in Python executes a block of code as long as a specified condition evaluates to True. In this case, we want the loop to continue running as long as the user enters a non-negative number (0 or positive values). The moment a negative number is entered, the loop should stop.

Step-by-Step Breakdown:

  1. Getting User Input:
    The first input is obtained using input(), and it’s converted to an integer using int(). This ensures that the program processes numerical values rather than string inputs.
  2. Loop Condition (while num >= 0):
  • The condition num >= 0 ensures that the loop continues as long as the entered number is not negative.
  • If the user enters -1 or any other negative number, the condition evaluates to False, and the loop stops.
  1. Printing “Body”:
  • Inside the loop, the statement print("Body") executes, indicating that the loop body has been processed.
  1. Getting the Next Input:
  • After printing “Body”, the program asks for another input using num = int(input()).
  • This ensures that each time the user enters a non-negative number, the loop continues.
  1. Exiting the Loop:
  • When the user enters a negative number, the loop condition fails.
  • The program exits the loop and executes print("Done"), signaling that the loop has terminated.

Sample Run:

Input: 9  
Output: Body  
Input: 5  
Output: Body  
Input: 2  
Output: Body  
Input: -1  
Output: Done

This ensures that the program does not enter an infinite loop and properly stops when a negative number is encountered.

Scroll to Top