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

Time:09-30

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

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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

CodePudding user response:

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. :/

  • Related