break

cpt.tripps.2012

Warlord
Joined
May 25, 2012
Messages
176
So in the code I'm looking at I see the word "break" often at the end of an if statement. In python does the "break" command end the function? Is it different then a return? or does it do something else?
 
You don't see it after an if, but after a for ;).

e.g. (a nonsense example):
PHP:
x = 0
for i in range(10):
    x = x + i
    if x>5:
        break

A break finishes a loop.
In this case, if x is bigger than 5, then the loop will immediately finsih, and not go to it#s end.
Normally it's used when you're searching something specific in a list, and if you then have found it, you want to end the loop, just for the performance.

A return would do the same, in case the loop is in a function.
 
Hmm I think may be abit different from return.
If I am not wrong, break only ends the current loop, whether for or while.
But if there are more codes below, not within the loop. codes will carry on.
P.S.
In your example, you do see it after an if statement, and usually you do see it after an if statement:
If a condition is fulfilled, let's stop wasting our time and break the loop.

Return will stop everything.
 
Back
Top Bottom