There are several problems in your code:
You can end up trying to access
stDigs[len(stDigs)]
becausenum < len(stDigs)
might be true, but you then add 1 before using it as an index.sum(digits)
won't work becausedigits
is a string.
Just loop over the string directly instead of using a while
loop, add up the digits in the loop:
def avgUntilLetter(stDigs):
total = i = 0
for i, each_char in enumerate(stDigs):
if not each_char.isdigit():
break
total += float(each_char)
if i:
return total / i
return 0.0
This handles edge-cases as well:
>>> avgUntilLetter('0123a456')
1.5
>>> avgUntilLetter('')
0.0
>>> avgUntilLetter('abc')
0.0