Search code examples
pythonpython-3.xexceptionerror-handlingvalueerror

Python ValueError is it possible to get the Incorrect Value without string parsing?


I have this bit of code :

while True:
    
    try:
        start = int(input("Starting number: "))
        fin = int(input("Ending number: "))
        amount = int(input("Count by: "))
    
    except ValueError as verr:
        
        print('error : ', verr,'\n restarting ....')
        
    else:
        
        break

I would like to intercept the inputing of '' just hitting return as a signal to exit the loop inside the except block. Is there any way to get the value that raises the ValueError (I dont know how int() is able to return a ValueError and dont know about the latter either) other than parsing the ValueError __repr__ , for example :

invalid literal for int() with base 10: 'èèè' or the one I want to intercept

invalid literal for int() with base 10: '' ?


Solution

  • You could save the input value before the conversion and use that to check.

    while True:
        
        try:
            _start = _fin = _amount = None
            start = int(_start:=input("Starting number: "))
            fin = int(_fin:=input("Ending number: "))
            amount = int(_amount:=input("Count by: "))
        
        except ValueError as verr:
            if _start == "" or _fin == "" or _amount == "":
                break
            print('error : ', verr,'\n restarting ....')
        else:
            break