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

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

问题描述

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

解决方案

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

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

使用break

遍历值列表并在我们看到数字 3 时中断.

def loop3():对于范围内(0,10):打印一个如果 a == 3:# 我们找到了三个,让我们停止循环休息打印找到 3 个!"循环3()

将产生以下输出

<预><代码>0123发现3个!

使用return

以下示例说明了如何在函数根据传入参数计算出值后使用 return 返回值:

def sum(a, b):返回 a+bs = sum(2, 3)印刷

输出:

5

比较两者

现在,在第一个示例中,如果循环后没有任何事情发生,我们也可以使用 return 并立即跳出"函数.当我们使用 return 而不是 break 时,将输出与第一个示例进行比较:

def loop3():对于范围(0, 6):打印一个如果 a == 3:# 我们找到了一个三,让我们结束函数并返回"返回打印找到 3 个!"循环3()

输出

<预><代码>0123

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中的返回和中断有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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