0

I simply want to continue asking for input until it becomes valid.

def IsValidInput(UserInput): # We hate string return False if it is string.
    if type(UserInput) == str: return False; return True 

temp = 0 # By default, the value is 0.
while(True): 
    temp = float(input("Enter a valid input between 1 and 100: ")) # Float and Integer are accepted.
    if IsValidInput(temp) and 1 <= temp <= 100: 
         break # break the loop on correct input.
    else: 
         print("Not a valid input, please try again.") # Continue with the loop.

....

But I keep having an error of ValueError: could not convert string to float: everytime I pressed enter on my keyboard(no input) or inputting a string.

Even with this I always get the same error.

def IsValidInput(UserInput):
    try:
        float(UserInput)
    except ValueError:
        return False
    else:
        return True

How can I check for a valid input then? I'm confused.

I'm using Python3

Distro
  • 13
  • 4
  • 1
    You need to convert input to float after the validity of the input is checked. That is if`IsValidInput(temp)` returns true, then you need to convert it to float and check if it belongs in the range 1-100. Currently you are trying to convert to float even if the input is not a number and that is why the mentioned error – kuro Mar 08 '23 at 06:01
  • you are doing `float(input(".."))` which means you are trying to cast it to float before you check the input type. `IsValidInput()` doesn't get reached. – Shorn Mar 08 '23 at 06:05
  • @Shorn Well, this is embarrassing. Thank you! – Distro Mar 08 '23 at 06:10

1 Answers1

0

Put the try around the line where you convert the input to a float. Having a separate function isn't even necessary:

while True: 
    try:
        temp = float(input("Enter a valid input between 1 and 100: "))
        if 1 <= temp <= 100: 
            break  # break the loop on correct input.
        # Otherwise, just fall through to the end of the loop.
    except ValueError:
        pass  # we get here if the float() conversion fails.  Fall through.
    print("Not a valid input, please try again.")  # Continue with the loop.
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • You are correct, it's not necessary if you only have a single while-loop with conditions. In my case, I want to repeat the same process in five more inputs so I have to define a function for it. Anyway, the problem already mentioned by [@Shorn](https://stackoverflow.com/users/21169587/shorn), Thanks anyway! – Distro Mar 08 '23 at 06:29