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

Question:

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: '' ?

Asked By: pippo1980

||

Answers:

I think I would just get the inputs as strings then put an if statement to catch the case of '' or whatever else before converting to int and catching ValueErrors. This might offend if you are a stickler for concise code though.

Or as you say, parse the repr with something like .split(':')[-1]

Answered By: BloodSexMagik

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
Answered By: tdelaney

Since the error is raised without passing the function argument and is formatted as string, there is no way to get the value directly from the error, what you can do is store it separately as a variable and then check the variable directly like so:

while True:
    data = {"start": 0, "fin": 0, "amount": 0}
    try:
        for i in data:
            x = input(f"Enter the value for {i}")
            x = int(x)
            data[i] = x
    except ValueError:
        if x == "":
            break
Answered By: Amartya Gaur

Others have already posted possible solutions for your problem but to answer your question directly.

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

Answer: No it is not. ValueError only stores a message string and nothing else. You can get that message by str(verr) or verr.args[0]. The int(...) call already creates the full message and doesn’t pass it’s input string seperatly to the ValueError in any way. :/

Answered By: Robin Gugel