How to Use the while Statement in a Python Application - dummies

How to Use the while Statement in a Python Application

By John Paul Mueller

You can use the while statement in many ways in Python. This example simply displays a count based on the starting and ending condition of a variable named Sum. The following steps help you create and test the example code.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    Sum = 0
    while Sum < 5:

    The example code demonstrates the three tasks you must perform when working with a while loop in a straightforward manner. It begins by setting Sum to 0, which is the first step of setting the condition environment. The condition itself appears as part of the while statement. The end of the while code block accomplishes the third step.

    Of course, the code displays the current value of Sum before it updates the value of Sum.

    A while statement provides flexibility that you don’t get with a for statement. This example shows a relatively straightforward way to update Sum. However, you can use any update method required to meet the goals of the application. Nothing says that you have to update Sum in a specific manner.

    In addition, the condition can be as complex as you want it to be. For example, you can track the current value of three or four variables if so desired. Of course, the more complex you make the condition, the more likely it is that you’ll create an endless loop, so you have a practical limit as to how complex you should make the while loop condition.

  3. Choose Run→Run Module.

    Python executes the while loop.