0

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

1 Answer 1

2
        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.

Sign up to request clarification or add additional context in comments.

1 Comment

Because I am an idiot? :) If you could make any suggestions about making the code less verbose it would also be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.