很多刚学习编程的小伙伴不知道return和break的不同,今天就这个问题给大家讲解。
break用于提前结束循环,而return是用于将返回值传递回函数调用方的关键字。如果它不带参数使用,它只会结束函数并返回到之前执行代码的位置。
在某些情况下,它们可以实现相同的目标,但这里有两个例子来向您展示它们的用途。
[En]
In some cases, they can achieve the same goal, but here are two examples to show you what they are for.
使用中断
[En]
Use break
迭代值列表并在看到数字3时中断。
[En]
Iterate over the list of values and break when we see the 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()
产出:
[En]
Output:
Found 3!
使用return
下面是一个示例,说明如何使用return在函数基于传入参数计算值之后返回值:
def sum(a, b):
return a+b
s = sum(2, 3)
print s
产出:
[En]
Output:
将两者进行比较
[En]
Compare the two
现在,在第一个例子中,如果循环之后没有发生任何事情,我们也可以使用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()
产出:
[En]
Output:
3
–
[En]
–
版权声明:本文为CSDN博主「weixin_39600328」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39600328/article/details/111862091
Original: https://www.cnblogs.com/weifeng1463/p/15797539.html
Author: Oops!
Title: python return break 区别_Python基础:return和break的不同
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6384/
转载文章受原作者版权保护。转载请注明原作者出处!