Ben
Ben

Reputation: 903

Problems with checking user input (Python)

I am trying to check if the user input is an integer and that lower_bound is greater than or equal to zero. I am also trying to check that upper_bound is greater than lower_bound. This is my code:

while True:

    try:

        lower_bound = int(input("What is the lower bound for x >= 0 (inclusive?)"))

    except ValueError:

        print("Lower bound is not an integer.")
        continue

    else:

        if lower_bound < 0:

            print("Lower bound cannot be less than zero.")
            continue   
    try:

        upper_bound = int(input("What is the upper bound (inclusive)?"))
        break

    except ValueError:

        print("Upper bound is not an integer.")

    else:

        if (upper_bound < lower_bound):

            print("The upper bound cannot be less than the lower bound.")
            continue

As it stands the checking of user input for lower_bound works, as does the check for upper_bound being an integer. However if upper_bound is less than lower_bound no error is returned - why is this?

Also I feel that my code must be very verbose - how could I make all this error checking more concise?

Thanks,

Ben

Upvotes: 0

Views: 184

Answers (1)

user2357112
user2357112

Reputation: 281958

        upper_bound = int(input("What is the upper bound (inclusive)?"))
        break

Why are you breaking? This break will immediately end the loop, skipping the upper_bound < lower_bound check. Move the break after the final check, so it only breaks once all checks pass.

Upvotes: 2

Related Questions