在 Python 中,一旦执行到 “return ”语句,函数就会返回。

Section 42.1: 函数循环内的返回语句

在本例中,只要 var 值为 1,函数就会返回

def func(params):
  for value in params:
    print ('Got value {}'.format(value))

    if value == 1:
      # Returns from function as soon as value is 1
      print (">>>> Got 1")
      return

    print ("Still looping")

    return "Couldn't find 1"

func([5, 3, 1, 2, 8, 9])

输出

Got value 5
Still looping
Got value 3
Still looping
Got value 1

>>> Got 1

函数循环内的返回语句