python中的return是干嘛的-python中的return和break有什么区别?

1586010002-jmsa.png

what is the difference between return and break in python?

Please explain what they exactly do in loops and functions?

thank you

解决方案

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.

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

Iterating over a list of values and breaking when we've seen 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()

will produce the following output

0

1

2

3

Found 3!

Using 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:

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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值