3

背景:我的入门教科书中的“手指练习”之一让我尝试编写这样一个程序来教我如何使用 try-except 块。该教科书旨在配合麻省理工学院 MOOC edX 上的“6.00x”课程。这不是在线课程本身的一部分,而只是一些让我理解 try-excpet 块的练习。

到目前为止,这是我的代码:

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

所以,我遇到的麻烦是知道要在 except 子句中添加什么。我放在两个 except 子句中的文本在那里,因为我只是想让我的程序运行。我假设解释器通过像'456ab'这样的字符串,点击'a',然后打印出我告诉它在不可避免地遇到ValueError时返回的文本。如何让它“忽略”字符串中的字母字符,而只使用字符串中的数字,所有这些都在 try-except 块的上下文中?

4

1 回答 1

5

try在循环内移动,并使用pass异常处理程序忽略异常:

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

TypeError除非 anyiint()无法处理的对象类型,否则您不会在这里打到;例如任何不是数字或字符串的东西:

>>> int({})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'dict'
于 2013-12-03T16:18:58.417 回答