Python Breaking Loops

In computer programming, a control flow statement is a block of code that helps your program decide which of multiple paths it should follow. In Python, you can create control flow statements in the form of for loops or try statements. However, sometimes you need to exit these blocks prematurely based on some criteria. Use the "break" style in Python to exit loops.

  1. Purpose

    • You use a break statement to terminate a while or for loop and return to the main body of a program. You can use more than one break in a conditional statement to exit a loop, but you only need to use the break statement once per termination condition. You only need to use a break statement in a loop when some criteria exist that warrants terminating the loop before it completes its task.

    Syntax

    • To use the break statement to exit from a loop, use the "break" keyword. You need to nest a break statement within a conditional if statement, which basically tells the loop that if the loop comes across a certain condition, terminate the loop, otherwise repeat it. The break should appear as the last line in a block of code within, or else any lines after the statement will not be executed.

    Values

    • When you use variables in a loop that changes their values, a break statement does not nullify those values when the loop terminates. For example, you can create a loop that counts from one to 100 and saves each value in the same variable, overwriting it each time. If you have a conditional statement that tells the loop to break when the counter reaches 50, then the value of the variable, which you can use outside of the loop, is 49.

    Considerations

    • When using a break statement, make sure the conditional statement is something that the loop can realistically achieve. For example, if you create a loop that counts numbers in a range from one to 10 and a break statement that terminates the loop if the counter reaches 11, your loop will never reach the break statement. To ensure the loop can reach a break statement, test your program thoroughly, using values that you know will cause a loop to break.

Related Searches:

References

Comments

Related Ads

Featured