'I'm writing a code that asks the user to input a number, and if the input is not a number, it will ask the user to input again. What loop is the best? [duplicate]
I'm writing a code that asks the user to input a number, and if the input is not a number, it will ask the user to input again. What loop is the best?
Solution 1:[1]
While loop works the best when you don't know exactly how many times you need to iterate. Also, the syntax of while loop is simpler as against the syntax of for loop in python. I recommend using while loop. See the code below
x = input()
while not abs(x).isdigit():
x = input()
I have used abs() because isDigit() doesn't check for negative numbers
Solution 2:[2]
Have you tried a while-loop? Or Do-while loop? - In this case you don't know how many times you would need to repeat the loop, so a while-loop would make sense. Unless you want to limit the number of attempts? Then perhaps a for-loop.
Solution 3:[3]
The "best" loop is subjective to the reader of the code. Performance shouldn't matter in the case where we're operating with user input, as users won't notice milliseconds of difference. Some options:
while loop:
String inpt = getInput();
while (!inpt.matches("^[0-9]+$")) {
inpt = getInput();
}
do-while loop:
String inpt = null;
do {
inpt = getInput();
} while (!inpt.matches("^[0-9]+$"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aman Vishnoi |
| Solution 2 | Michael Scott |
| Solution 3 | ODDminus1 |
