Home > Net >  How to transfer the following Java methods to Python def()
How to transfer the following Java methods to Python def()

Time:11-15

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related