Writing a small piece of code to sum up digits in a string, through using a try-except block

1.7k views Asked by At

Background: One of the "Finger Exercises" in my introductory textbook has me try to write such a program to teach me how to use a try-except block. The textbook is designed to accompany the '6.00x' class on edX, an MIT MOOC. This isn't part of the online class itself, but merely some practice to get me to understand try-excpet blocks.

Here is my code so far:

def sumDigits(s):
'''Assumes s is a string
   Returns the sum of the decimal digits in s
       For example, if is is 'a2b3c' it returns 5'''
    try:
        digitsum = 0
        for i in s:
            digitsum += int(i)


    except TypeError:
        return 'You have hit a TypeError'

    except ValueError:
        return 'You have hit a ValueError'

    return digitsum

So, what I'm having trouble with is knowing what to put into the except clause. The text I put into the two except clauses are there because I just wanted my program to run. I'm assuming the interpreter goes through a string like '456ab', hits 'a', then prints out the text I told it to return when it inevitably hits a ValueError. How do I get it to 'ignore' the alphabetical characters in the string, and just make use of the numbers in the string, all in the context of a try-except block?

1

There are 1 answers

13
Martijn Pieters On BEST ANSWER

Move your try within the loop, and ignore the exception by using pass as the exception handler:

digitsum = 0
for i in s:
    try:
        digitsum += int(i)
    except ValueError:
        pass  # ignore non-digit characters

You won't hit a TypeError here unless any i is a type of object that int() cannot handle; e.g. anything not a number or a string:

>>> int({})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'dict'