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
what is the difference between return and break in python?
提问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
break
is used to end a loop prematurely while return
is 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 return
is 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 return
and "jumped out" of the function immediately. Compare the output with the first example when we use return
instead 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
return
would finish the whole function while break
just 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
break
is used to end loops while return
is used to end a function (and return a value).
break
用于结束循环而return
用于结束函数(并返回值)。
There is also continue
as a means to proceed to next iteration without completing the current one.
还有continue
一种方法是在不完成当前迭代的情况下进行下一次迭代。
return
can sometimes be used somewhat as a break when looping, an example would be a simple search function to search what
in lst
:
return
有时可以循环时稍微用作休息,一个例子是一个简单的搜索功能来搜索what
在lst
:
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:
在指令级别,您可以看到语句做不同的事情:
return
just 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
break
stops 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?"