Question 5.23: Breaking Out of a Loop You are in a loop and need to exit th......

Breaking Out of a Loop

You are in a loop and need to exit the loop if some condition occurs.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.21

Verified Answer:

Use the Python for command and iterate over a rang...
Question: 5.20

Verified Answer:

Use one of the logical operators: and, or, and not...
Question: 5.19

Verified Answer:

Use one of the comparison operators: <, >, &...
Question: 5.17

Verified Answer:

Use the upper or lower function as appropriate. Fo...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...
Question: 5.14

Verified Answer:

Use the find Python function. For example, to find...