如何修复'除ValueError'之外的无效语法错误?

时间:2013-11-18 20:56:27

标签: python python-3.x

我正在尝试编写一个简单的异常处理。但是,我似乎做错了。

def average():
    TOTAL_VALUE = 0
    FILE = open("Numbers.txt", 'r')

    for line in FILE:
        AMOUNT = float(line)
        TOTAL_VALUE += AMOUNT
        NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
    print("the average of the numbers in 'Numbers.txt' is :",
        format(NUMBERS_AVERAGE, '.2f')) 

    FILE.close()

    except ValueError,IOError as err:
        print(err)

average()

> line 14
>         except ValueError as err:
>              ^
>     SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:11)

这里有两件事不对。首先,您需要括号来包含错误:

except (ValueError,IOError) as err:

其次,您需要try来使用except行:

def average():
    try:
        TOTAL_VALUE = 0
        FILE = open("Numbers.txt", 'r')

        for line in FILE:
            AMOUNT = float(line)
            TOTAL_VALUE += AMOUNT
            NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
        print("the average of the numbers in 'Numbers.txt' is :",
            format(NUMBERS_AVERAGE, '.2f')) 

        FILE.close()

    except (ValueError,IOError) as err:
        print(err)
如果没有except,则无法使用

try