Python 如何修复“除了 ValueError”的无效语法错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20057719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:23:54  来源:igfitidea点击:

How to fix invalid syntax error at 'except ValueError'?

pythonpython-3.x

提问by Sabri Gül

I'm trying to write a simple exception handling. However it seems I'm doing something wrong.

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

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

采纳答案by Sabri Gül

There are two things wrong here. First, You need parenthesis to enclose the errors:

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

except (ValueError,IOError) as err:

Second, you need a tryto go with that exceptline:

其次,您需要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)

exceptcannot be used without try.

except不能没有try.