Breaking Out of a Loop
You are in a loop and need to exit the loop if some condition occurs.
Use the Python break statement to exit either a while or for loop.
The following example behaves in exactly the same way as the example code in Recipe 5.22:
>>> while True: … answer = input(‘Enter command:’) … if answer == ‘X’: … break … Enter command:A Enter command:B Enter command:X >>> |
Discussion
Note that this example uses the input command as it works in Python 3. To run the example in Python 2, substitute the command raw_input for input.
This example behaves in exactly the same way as the example of Recipe 5.21. However, in this case the condition for the while loop is just True, so the loop will never end unless we use break to exit the loop when the user enters X.
See Also
You can also leave a while loop using its condition; see Recipe 5.21.