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?
Move your
try
within the loop, and ignore the exception by usingpass
as the exception handler:You won't hit a
TypeError
here unless anyi
is a type of object thatint()
cannot handle; e.g. anything not a number or a string: