-1

I am using python to request user input for a float between two values. If they are not between the specified values, I use "raise ValueError". Unfortunately, this configuration does not seem to loop even though the components seem like they should. Below is the code.

while True:                    
    percent_var = float(input("Type in a number between 0 and 100"))
    if percent_var > 100 or percent_var < 0:
        raise ValueError(f"{percent_var} is not between 0 and 100")
        percent_var = float(input("Type in a number between 0 and 100"))
    else: 
        break

How can I make this so that the infinite loop continues to request input and give error messages when the input does not meet requirements?

  • 1
    replace the `raise` and `input` with a `continue`. After raising exception the input would not happen anyway. And you are not handling the exception in any way so your program will exit. You should just show the message in the exception to the user with a `print` and then `continue` with the loop – rdas Jun 27 '21 at 19:17

2 Answers2

0

When you raise it immediately stops the flow of execution unless it's caught. The simple approach would be to just let the loop go until you get the answer you want:

while True:                    
    percent_var = float(input("Type in a number between 0 and 100"))
    if percent_var > 100 or percent_var < 0:
        print(f"{percent_var} is not between 0 and 100")
    else: 
        break

You could use a ValueError as long as you wrap it in a try/except to make sure that when the error is raised it does the thing you want instead of terminating the entire function.

The benefit of using exceptions this way is that it would allow you to catch cases where the user enters something that's not a valid float, and handle both error cases with the same block of code that does the exact same thing in both cases (i.e. print the error and then continue the loop):

while True:  
    try:                  
        percent_var = float(input("Type in a number between 0 and 100"))
        if percent_var > 100 or percent_var < 0:
            raise ValueError(f"{percent_var} is not between 0 and 100")
        break     # the loop only breaks if no exceptions were raised!
    except ValueError as e:
        print(e)  # the loop will automatically continue and try again

Or very slightly more simply:

while True:  
    try:                  
        percent_var = float(input("Type in a number between 0 and 100"))
        if 0 <= percent_var <= 100:
            break
        raise ValueError(f"{percent_var} is not between 0 and 100")
    except ValueError as e:
        print(e)
Samwise
  • 51,883
  • 3
  • 26
  • 36
0

Replace the raise keyword with a print statement, otherwise it’ll break before it intended to.

Cody Tapp
  • 9
  • 4