Search code examples
pythonpython-3.xwhile-loopvalueerrortry-except

How can I set a value error exception in python


I have the following code:

while True:
            try:
                HOST = input(float(('Enter host IP'))
            except ValueError:
                print('Error. That is not a valid IP address.')
                continue

I require the user to input an IP address. I wanted to set an error so that if he uses a letter he gets an error. How can I do that and why isn't my code working?


Solution

  • Try something like this

    while True:
        try:
            HOST = input('Enter host IP: ')
            if len(HOST.split(".")) != 4:
                raise ValueError
            for char in HOST:
                if char not in "0123456789.":
                    raise ValueError
        except ValueError:
            print('Error. That is not a valid IP address.')
            continue
        else:
            break