Repeating Instructions Until Some Condition Changes
You need to repeat some program code until something changes.
Use the Python while statement. The while statement repeats its nested commands until its condition becomes false. The following example will stay in the loop until the user enters X for exit:
>>> answer = ” >>> while answer != ‘X’: … answer = input(‘Enter command:’) … Enter command:A Enter command:B Enter command:X >>> |
Discussion
Note that the preceding 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.
See Also
If you just want to repeat some commands a number of times, see Recipe 5.20.
If you are trying to repeat commands for each element of a list or dictionary, then see Recipes 6.7 or 6.15, respectively.