python中的return和break有什么区别? [英] what is the difference between return and break in python?

查看:1343
本文介绍了python中的return和break有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中的return和break有什么区别?
请解释他们在循环和函数中究竟做了什么?
谢谢

解决方案

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



在某些情况下,他们可以实现相同的目的,但这里有两个例子让你知道他们用于什么。



使用 break



当我们看到 $ b 3 <一个范围(0,10):
打印一个
如果a == 3:
#我们找到了三个,让我们停止循环
break
printFound 3!

loop3()

将产生以下输出

  0 
1
2
3
找到3!



使用返回



下面是一个例子,说明函数根据传入参数计算出一个值后,如何使用 return 返回一个值: p>

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

s = sum(2 ,3)
print s

输出:

  5 



比较两个



现在,在第一个例子中,如果循环后没有任何事情发生,我们可以使用 return 和立即跳出该功能。比较输出和第一个例子,当我们使用 return 而不是 break

  def loop3():
在范围内(0,6):
打印
如果a == 3:
#我们找到了三个,让我们结束这个函数并返回
return

printFound 3!

loop3()

输出

  0 
1
2
3


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

这篇关于python中的return和break有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆