I do not get a raise with ValueError

1

I have the following code:

def sum_digits(s):

    r = ''.join(x for x in s if x.isdigit())
    newList = list(r)
    try:
        result = sum(int(i) for i in newList)
    except:
        raise ValueError
    return result


print(sum_digits("a;d"))

They should find the numbers in a string , and if they are not found, I should return a ValueError , but it's not coming back, in fact > it returns me 0.
I hope someone can help me. Thank you very much

    
asked by Luis Miguel 28.07.2017 в 17:26
source

2 answers

1

That happens to you because there's never going to be an error in try with those conditions. newlist will be a list of numeric characters (so the casting to int will always work) or an empty list if there is none (in this case sum will return 0).

If you want me to launch a ValueError when there is no numeric character, use a conditional to see if the list is empty or not:

def sum_digits(s):

    aux = [int(i) for i in s if i.isdigit()]
    if not aux:
        raise ValueError
    return sum(aux)

This function adds the characters that are digits, do not count them:

>>> print(sum_digits("1a;4d7"))
12
>>> print(sum_digits("a;d"))
Traceback (most recent call last):
  File "C:\...", line 29, in <module>
    print(sum_digits("a;d"))
  File "D:\...", line 26, in sum_digits
    raise ValueError
ValueError
    
answered by 28.07.2017 / 17:47
source
0

You could try with the following function to eliminate the handling of exceptions, keep in mind that in newstring there will never be anything other than a number, in this way with a map you convert to the list of numbers and the sums You also control that if you use it in iterative processes do not break the process and even control what it returns in these cases.

def sum_digits(string):
    newstring = ''.join(ch for ch in string if ch.isdigit())
    if len(newstring)==0:
        return None
    else:    
        return sum(map(int, newstring))

# véase
sum_digits("aszdas")
sum_digits("1aszdas,2")
Out[1]: 
3
    
answered by 02.08.2017 в 11:12