Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

function - what is the difference between return and break in python?

what is the difference between return and break in python? Please explain what they exactly do in loops and functions? thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...