python中的返回和中断有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28854988/
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-19 03:50:11  来源:igfitidea点击:

what is the difference between return and break in python?

pythonfunctionloops

提问by

what is the difference between return and break in python? Please explain what they exactly do in loops and functions? thank you

python中的返回和中断有什么区别?请解释它们在循环和函数中究竟做了什么?谢谢你

采纳答案by Parham

breakis used to end a loop prematurely while returnis the keyword used to pass back a return value to the caller of the function. If it used without an argument it simply ends the function and returns to where the code was executing previously.

break用于提前结束循环,而return是用于将返回值传回给函数调用者的关键字。如果它在没有参数的情况下使用,它只会结束函数并返回到之前执行代码的位置。

There are situations where they can fulfil the same purpose but here are two examples to give you an idea of what they are used for

在某些情况下,它们可以实现相同的目的,但这里有两个示例可以让您了解它们的用途

Using break

使用 break

Iterating over a list of values and breaking when we've seen the number 3.

遍历值列表并在我们看到 number 时中断3

def loop3():
    for a in range(0,10):
        print a
        if a == 3:
            # We found a three, let's stop looping
            break
    print "Found 3!"

loop3()

will produce the following output

将产生以下输出

0
1
2
3
Found 3!

Using return

使用 return

Here is an example of how returnis used to return a value after the function has computed a value based on the incoming parameters:

下面是一个示例,说明如何return在函数根据传入参数计算出一个值后返回一个值:

def sum(a, b):
    return a+b

s = sum(2, 3)
print s

Output:

输出:

5

Comparing the two

比较两者

Now, in the first example, if there was nothing happening after the loop, we could just as well have used returnand "jumped out" of the function immediately. Compare the output with the first example when we use returninstead of break:

现在,在第一个示例中,如果在循环之后没有发生任何事情,我们也可以return立即使用并“跳出”该函数。当我们使用return代替时,将输出与第一个示例进行比较break

def loop3():
    for a in range(0, 6):
        print a
        if a == 3:
            # We found a three, let's end the function and "go back"
            return

    print "Found 3!"

loop3()

Output

输出

0
1
2
3

回答by Paul Lo

returnwould finish the whole function while breakjust make you finish the loop

return会完成整个功能,而break只是让你完成循环

Example:

例子:

def test_return()
    for i in xrange(3):
        if i==1:
            print i
            return i
    print 'not able to reach here'


def test_break()
    for i in xrange(3):
        if i==1:
            print i
            break
    print 'able to reach here'

test_return()  # print:  0 1
test_break()  # print:  0 1 'able to reach here'   

回答by Reut Sharabani

breakis used to end loops while returnis used to end a function (and return a value).

break用于结束循环而return用于结束函数(并返回值)。

There is also continueas a means to proceed to next iteration without completing the current one.

还有continue一种方法是在不完成当前迭代的情况下进行下一次迭代。

returncan sometimes be used somewhat as a break when looping, an example would be a simple search function to search whatin lst:

return有时可以循环时稍微用作休息,一个例子是一个简单的搜索功能来搜索whatlst

def search(lst, what):
    for item in lst:
        if item == what:
            break

    if item == what:
        return item

And nicer, equivalent function, with return:

更好的等效功能,具有return

def search(lst, what):
    for item in lst:
        if item == what:
            return item # breaks loop

Read more about simple statements here.

在此处阅读有关简单语句的更多信息。

At the instruction level you can see the statements do different things:

在指令级别,您可以看到语句做不同的事情:

returnjust returns a value (RETURN_VALUE) to the caller:

return只返回一个值 ( RETURN_VALUE) 给调用者:

    >>> import dis
    >>> def x():
    ...     return
    ... 
    >>> dis.dis(x)
      2           0 LOAD_CONST               0 (None)
                  3 RETURN_VALUE        

breakstops a the current loop (BREAK_LOOP) and moves on:

break停止当前循环 ( BREAK_LOOP) 并继续:

>>> def y():
...     for i in range(10):
...         break
... 
>>> dis.dis(y)
  2           0 SETUP_LOOP              21 (to 24)
              3 LOAD_GLOBAL              0 (range)
              6 LOAD_CONST               1 (10)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 7 (to 23)
             16 STORE_FAST               0 (i)

  3          19 BREAK_LOOP          
             20 JUMP_ABSOLUTE           13
        >>   23 POP_BLOCK           
        >>   24 LOAD_CONST               0 (None)
             27 RETURN_VALUE  

回答by Benjamin James Drury

Return will exit the definition at the exact point that it is called, passing the variable after it directly out of the definition. Break will only cause the end of a loop that it is situated in.

Return 将在它被调用的确切点退出定义,在它之后直接从定义中传递变量。Break 只会导致它所在的循环结束。

For example

例如

def Foo():
    return 6
    print("This never gets printed")

bar = Foo()

That will make bar equal to six. The code after the return statement will never be run.

这将使 bar 等于 6。return 语句之后的代码将永远不会运行。

The break example:

中断示例:

def Loop():
    while True:
        print("Hi")
        break

Loop()

That will print only once, as the break statement will cause the end of the infinite while loop.

这只会打印一次,因为 break 语句将导致无限 while 循环结束。

回答by motoku

Let's take a look at an example:

我们来看一个例子:

def f(x, y):
    n = 0
    for n in range(x, y):
         if not n % 2: continue
         elif not n % 3: break
    return n
print((f(1, 10)))

This prints 3. Why? Let's step through the program:

这打印3. 为什么?让我们逐步完成该程序:

def f(x, y):

define a function

定义一个函数

    n = None

set variable 'n' to None

将变量“n”设置为 None

    for n in range(x, y):

begin iterating from 'x' to 'y'. in our case, one through nine

开始从“x”到“y”迭代。在我们的例子中,一到九

         if not n % 2: continue

discontinue this iteration if 'n' is evenly divisible by two

如果 'n' 可被 2 整除,则停止此迭代

         elif not n % 3: break

leave this iteration if n is evenly divisible by three

如果 n 可被 3 整除,则离开此迭代

    return n

our function 'f' "returns" the value of 'n'

我们的函数 'f' “返回”了 'n' 的值

print((f(1, 10)))

'f(1, 10)' prints three because it evaluates to 'n' once execution leaves the scope of the function

'f(1, 10)' 打印 3,因为一旦执行离开函数的范围,它的计算结果为 'n'

回答by d.raev

I will try to illustrate it with an example:

我将尝试用一个例子来说明它:

def age_to_find_true_love(my_age):
    for age in range(my_age, 100):
        if find_true_love_at(age):
            return age

        if age > 50:
            break

    return "...actually do you like cats?"