如何在python中处理和设置错误、返回和返回值?

2024-04-25 02:03:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,有没有人能告诉我python有什么不同以及如何处理错误?你知道吗

def compare_files(file1, file2):
    status = 0
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            if f_file1.read() == f_file2.read():
                print 'SUCCESS \n'
            else:
                print 'FAILURE \n'
                status = 1
    except IOError:
        print "[Error]File is NOT compared"
        status = -1
    return status 

在上述程序中是否可以使用return 1、return-1或return 0?而不是使用status=0、1等等。我想有效地处理程序中的错误。有人能解释一下或者告诉我怎么做吗?你知道吗


Tags: readreturndefasstatus编程openfile1
1条回答
网友
1楼 · 发布于 2024-04-25 02:03:06

当然,您可以使用return,而不是将状态赋给变量

def compare_files(file1, file2):
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            if f_file1.read() == f_file2.read():
                print 'SUCCESS \n'
                return 0
            else:
                print 'FAILURE \n'
                return 1
    except IOError:
        print "[Error]File is NOT compared"
        return -1

你可能想这样处理:

val = compare_files(file1, file2)
if val == 0:
    print "Files are the same"
elif var == 1:
    print "Files differ"
elif var == -1:
    print "Error"

但这并没有提供任何关于什么错误导致status=-1的信息

相关问题 更多 >