sec03 - Mastering Python while Loops: A Complete Guide to Conditional Looping
スポンサーリンク

1. Basics of the while Statement

In the previous section, we focused on for loops that iterate over elements sequentially. In contrast, the while statement repeatedly executes a block of code as long as a given condition is met. It is commonly used when the number of iterations is not predetermined.

2. Syntax of the while Statement

The while statement has the following syntax:

while condition:
    # code to execute

The loop continues executing as long as the condition evaluates to True. Once it becomes False, the loop exits. The following example uses a counter variable to repeat the loop exactly five times.

count = 0
while count < 5:
    print(count)
    count += 1

Output:

0
1
2
3
4
スポンサーリンク

3. Execution Flow

The execution flow of a while loop is as follows:

  • Initialization (e.g., count = 0)
  • Condition evaluation (e.g., count < 5)
  • Loop body execution (e.g., print(count))
  • Update state (e.g., count += 1)
  • Repeat until the condition becomes False

4. Infinite Loops and Cautions

If the condition remains True indefinitely, the loop will never stop. This is known as an "infinite loop." A common cause is forgetting to update the counter variable, which can unintentionally trigger an infinite loop.

count = 0
while count < 5:
    print(count)
    # Forgot to write count += 1!

In this code, count remains 0, so count < 5 is always True, causing the program to run indefinitely. Always ensure that variables inside the loop are updated as intended.

5. while + break / continue / else

As with for loops, while loops can be controlled using keywords like break, continue, and else.

SyntaxPurpose
breakImmediately exit the loop when a condition is met
continueSkip the current iteration and proceed to the next loop cycle
elseExecuted when the loop ends because the condition becomes False, not via break
(Skipped if break was used)

For example:

count = 0
while count < 5:
    print(count)
    if count == 10:
        break
    count += 1
else:
    print('Loop completed successfully.')

Output:

0
1
2
3
4
Loop completed successfully.

Here, count reaches 5, making count < 5 False, which triggers the else block.

If break is executed in the middle, the else block is skipped. (Try changing count < 5 to count < 20 to see the else block skipped.)

6. Practical Example: while Loop with User Input

The while loop is frequently used to repeat operations based on user input. In such cases, specifying True as the condition creates an "infinite loop." You can then safely exit the loop using break.

while True:
    password = input('Enter password (type "exit" to quit): ')
    if password == 'exit':
        print('Exiting the program.')
        break
    elif password == 'python123':
        print('Login successful!')
        break
    else:
        print('Incorrect password. Please try again.')

This use of while True is ideal when the number of repetitions is unknown beforehand. The loop continues until the user either meets the condition or decides to exit, allowing flexible interactive behavior.

スポンサーリンク