81.7k views
3 votes
In python,

Write a while loop that validates user input. The user should be prompted to enter a positive integer in the range 0 to 100. The while loop should print an error if an invalid value is entered and re-prompt the user for another value. The loop should terminate when the user enters a valid value. The first user input should be captured outside the while loop (priming read).
Expected Output:
Enter a value between 0 and 100: 250
Invalid value!
Enter a value between 0 and 100: 199
Invalid value!
Enter a value between 0 and 100: -20
Invalid value!
Enter a value between 0 and 100: -3
Invalid value!
Enter a value between 0 and 100: 73
done!

User Pusparaj
by
8.3k points

1 Answer

3 votes

Final answer:

In Python, a while loop is used to validate user input of a positive integer between 0 and 100, re-prompting for input if the value is outside the range, and terminating when a valid input is received.

Step-by-step explanation:

To write a while loop in Python that validates user input for a positive integer between 0 and 100, follow the example below:

value = int(input("Enter a value between 0 and 100: "))
while value < 0 or value > 100:
print("Invalid value!")
value = int(input("Enter a value between 0 and 100: "))
print("done!")

This code starts by capturing the first user input before entering the loop (priming read). Inside the loop, it checks if the value is outside the acceptable range. If so, it prints an error message and prompts the user to enter a new value. The loop continues until the user provides a value within the specified range, at which point it prints 'done!' and terminates.

User Aelphaeis
by
8.3k points