public static double readNumber(String prompt,double min, double max){
Scanner scanner = new Scanner(System.in);
double value;
while (true){
System.out.print(prompt);
value = scanner.nextFloat();
if (value >= min && value <= max) {
break;
} else
System.out.println("Enter a value between "+min+" and "+max);
}
return value;
}
The upper one works. But the following one doesn't jump out of the loop.
def readnumber(prompt, minimum, maximum):
while True:
value = float(input(prompt))
if minimum <= value <= maximum:
return value
else:
print(f"a valid value needed between {minimum} and {maximum}")
break
It doesn't work the same way. HELP the new beginner please
3 Answers 3
You have the break in the wrong case. in the java method you break when the value is > minimum and < than maximum, but in the python code you break the loop in the other case
Comments
For me it works perfectly fine. To use the function just put it somewhere and make sure to make the prompt a string like for example in this usecase of the function:
print(readnumber("input a number: ", 2, 4))
Edit: For contiuos asking for a number remove the break statement in the else clause
3 Comments
You could add an extra line of code and create a flag and change the flag e.g.,
flag = true
and use
while(flag)
Then instead of break, you can change the flag to false so the loop stops explicitly rather than implicitly
valueis between theminimumand themaximum, it executes thereturn valuestatement, and the function returns the value. Otherwise, it executes thebreakstatement, and the function returnsNone. Are you sure that the code you copied into your question is the same as the code that you are trying to run?breakstatement