What are the two ways to end a loop Python

This article will explain how we can end a while loop in Python. A while loop is a control flow statement used to repeat a specific code again and again until the specified condition is not reached. It can be considered as a repeating if statement.

We can end a while loop with a True condition within a function body and outside a function body in the following two ways in Python.

End a while Loop in Python Using the break Statement

We can end a while loop outside a function body by simply using a break statement. Suppose we have a list of numbers, and we want to end the while loop if we lose the number is greater than a certain value.

The example below demonstrates how to end a while loop using the break statement in Python.

mylist = [1, 4, 2, 7, 16, 3, 2, 8] while True: if mylist[-1] < 5: print("less than 5") if mylist[-1] > 10: print("greater than 10") break if mylist[-1] > 5: print("greater than 5") mylist.pop()

Output:

greater than 5 less than 5 less than 5 greater than 10

We can also end a while loop within a function body using the break statement in Python, as demonstrated in the below example code.

mylist = [1, 4, 2, 7, 16, 3, 2, 8] def myfunc(): while True: if mylist[-1] < 5: print("less than 5") if mylist[-1] > 10: print("greater than 10") break if mylist[-1] > 5: print("greater than 5") mylist.pop() return if __name__ == "__main__": myfunc()

Output:

greater than 5 less than 5 less than 5 greater than 10

End a while Loop in Python Within a Function Using the return Statement

We can end a while loop in Python within a function using the return statement. In a function, we can also use the return statement instead of the break statement to end a while loop, which will stop the while loop and end the function’s execution.

The example below demonstrates how to use a return statement within a function body to end the while loop in Python.

mylist = [1, 4, 2, 7, 16, 3, 2, 8] def myfunc(): while True: if mylist[-1] < 5: print("less than 5") if mylist[-1] > 10: print("greater than 10") return if mylist[-1] > 5: print("greater than 5") mylist.pop() if __name__ == "__main__": myfunc()

Output:

greater than 5 less than 5 less than 5 greater than 10

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Loop

  • Access the Index in 'Foreach' Loops in Python
  • Text Menu With Infinite Loop in Python
  • Loop Backward Iteration in Python
  • Nested for Loop in One Line in Python
  • Break and continue are two ways to modify the behavior of for loops and while loops.

    Break

    In Python, the keyword break causes the program to exit a loop early. break causes the program to jump out of for loops even if the for loop hasn't run the specified number of times.break causes the program to jump out of while loops even if the logical condition that defines the loop is still True.

    An example using break in a for loop is below.

    for i in range(100): print(i) if i == 3: break print('Loop exited')

    Summary: in this tutorial, you’ll learn about the Python break statement and how to use it to exit a loop prematurely.

    Introduction to the Python break statement

    Sometimes, you wan to terminate a for loop or a while loop prematurely regardless of the results of the conditional tests. In these cases, you can use the break statement:

    Code language: Python (python)

    Typically, you use the break statement with the if statement to terminate a loop when a condition is True.

    Using Python break with for loop

    The following shows how to use the break statement inside a for loop:

    for index in range(n): if condition: break

    Code language: Python (python)

    In this syntax, if the condition evaluates to True, the break statement terminates the loop immediately. It won’t execute the remaining iterations.

    This example shows how to use the break statement inside a for loop:

    for index in range(0, 10): print(index) if index == 3: break

    Code language: Python (python)

    Output:

    Code language: Python (python)

    How it works.

    • The for loop iterates over 10 numbers from 0 to 9 and displays each of them on the screen.
    • However, when the loop counter is 3, the break statement terminates the loop immediately. Therefore, the program shows only 4 numbers, from 0 to 3 to the screen.

    When you use the break statement in a nested loop, it’ll terminate the innermost loop. For example:

    for x in range(5): for y in range(5): if y > 1: break print(f"({x},{y})")

    Code language: Python (python)

    Output:

    (0,0) (0,1) (1,0) (1,1) (2,0) (2,1) (3,0) (3,1) (4,0) (4,1)

    Code language: Python (python)

    This example uses two for loops to show the coordinates from (0,0) to (5,5) on the screen.

    The break statement in the nested loop terminates the innermost loop when the y is greater than one.

    Therefore, you only see the coordiates whose y values are zero and one.

    Using Python break statement with a while loop

    The following shows how to use the break statement inside the while loop:

    while condition: if condition: break

    Code language: Python (python)

    The following example uses the break statement inside a while loop.

    It’ll prompt you for entering your favorite color. The program will stop once you enter quit:

    print('-- Help: type quit to exit --') while True: color = input('Enter your favorite color:') if color.lower() == 'quit': break

    Code language: Python (python)

    Output:

    -- Help: type quit to exit -- Enter your favorite color:red Enter your favorite color:green Enter your favorite color:blue Enter your favorite color:quit

    Code language: Python (python)

    How it works.

    • The while True creates an indefinite loop.
    • Once you enter quit, the condition color.lower() == 'quit' evaluates True that executes the break statement to terminate the loop.
    • The color.lower() returns the color in lowercase so that you can enter Quit, QUIT or quit to exit the program.

    Summary

    • Use the Python break statement to terminate a for loop or a while loop prematurely.

    Did you find this tutorial helpful ?