这段代码中返回的重点是什么?

时间:2013-08-14 05:27:45

标签: python

所以,我有以下功能:

def remove_all(lst):
    i = 0
    while i < 10:
        try:
            print('Removing... ')
            print(int(lst.pop()) + 10)
            print("Removed successfully.")

        # As soon as an IndexError is raised, jump to the following block of code...        
        except IndexError as err: 
            # if you encounter an indexerror, do the following:
            print("Uh oh! Problems.")
            return

        #As soon as a Value error is raised, jump here.
        except ValueError as err:
            print("Not a number")

        i = i + 1

回报是做什么的?返回后没有值,所以它是否意味着无或真? 如果值为none,那么返回那里有什么意义?

谢谢!

4 个答案:

答案 0 :(得分:7)

返回值为None

在此上下文中,函数永远不会返回值。 return的目的是停止执行

答案 1 :(得分:0)

return语句可以用作一种控制流程。通过在函数中间放置一个(或多个)返回语句,可以退出/停止该函数。

答案 2 :(得分:0)

这会导致函数在遇到IndexError时退出,而不返回任何值。

答案 3 :(得分:0)

在您的示例中,没有返回值。

鉴于你会调用这样的函数:

a = remove_all(lst)

a将为None,因为该函数不会返回任何内容。

要检查函数是否成功,您可以像这样实现它:

def ....
    try:
        ...
    exception 1:
        your error handling...
        return False
    exception 2:
        your error handling...
        return False

    continue function...
    return True

当您检查函数的返回值时,您将看到它是否已执行到最后(True)或者是否在(False)之前引发错误。

但是,在发生一个定义的错误后,这将不会继续执行此特定功能。