Contents

Python Quick Guide - Step 2 Control Flow (4) - Loops (2): while Loops

Info
  • This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
  • The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
  • You can run and see the results of each code example.
    Feel free to experiment with the code - reloading the page will reset the content.

This is a continuation of “Step 2 Control Flow.”

Last time, we learned about loops using the for statement.
This time, we’ll learn about another loop structure, the while statement.

The while statement is a loop structure that executes repeated processing as long as the specified condition is True.

while Statement
while condition: loop process
  • In a while statement, the loop process is executed repeatedly as long as the condition is True
  • When the condition is evaluated as False, the loop ends and execution proceeds to the next process
flowchart TD
    START[Start] --> INIT["counter = 5"]
    INIT --> WHILE{"while counter > 0"}
    WHILE -->|False| END["Loop ended"]
    WHILE -->|True| LOOP_BODY["Loop process\n(... counter -= 1)"]
    LOOP_BODY --> WHILE

linkStyle 2 stroke:red,stroke-width:2px;
linkStyle 3 stroke:green,stroke-width:2px;
📚Exercise 1

Create a program that counts up from 1 to 10 using a while statement.

Sample Solution
📚Exercise 2

Write a program that divides a specified integer by 2 repeatedly until it becomes an odd number, then outputs the result.

Sample Solution
📚Exercise 3

Add integers starting from 1 in sequence, and display the last integer added and the total sum when the sum exceeds 1000.

Sample Solution

Just like with for loops, you can use break and continue in while loops.

The break statement allows you to exit a loop immediately, regardless of the condition.

In the example above, when number becomes 5, the break statement executes and exits the loop. As a result, numbers 6 and above aren’t processed.

A loop whose condition is always True is called an infinite loop. Infinite loops are sometimes used in combination with break statements.

  • while True always evaluates to True, so it will continue executing forever unless explicitly exited using a break statement
  • Be careful of unintended infinite loops, such as forgetting to update a counter
input function

The input function allows you to receive input from the user as a string and assign it to a variable for use.

In this environment, executing the input function displays a browser dialog, but in normal Python scripts (for example, when running a .py file on your PC), it accepts input in a terminal format. We’ll explain how to run programs as scripts in more detail later.

📚Exercise

Create a program that repeatedly asks the user for their favorite vegetable using the input function, and outputs User's favorite vegetable: <favorite vegetable> until the string “exit” is entered.

Sample Solution

The continue statement allows you to skip the remaining process in the current iteration and proceed to the next condition check.

In this example, if number is even, the continue statement skips the remaining process (print(f"Processing: {number}")) and proceeds to the next iteration of the loop.

📚Exercise

Create a program using while and continue statements that outputs only numbers that are multiples of 3 or multiples of 5 from 1 to 20.

Sample Solution

When loops are nested, break and continue statements, just like in for loops, only affect the innermost loop that contains them.

In the example above, the break in the inner loop only exits the inner loop, and the outer loop continues to execute.

Like the for statement, you can also add an else clause to a while statement.
The else block is executed when the loop terminates normally (i.e., not interrupted by break).

In the example above, once an even number is found, the loop is immediately exited using the break statement, so the else block isn’t executed. The else block is only executed if the loop completes normally without finding an even number.

For choosing between for and while loops, choose the one that can be written more simply.

When a for loop is appropriate:

  • Repetitive processing with a predetermined number of iterations
  • Processing each element in an iterable (list, tuple, string, etc.)
  • Repetition over a fixed range that can be expressed using the range() function

When a while loop is appropriate:

  • When the termination condition changes dynamically
  • When an infinite loop is needed, ending only under specific conditions
  • When the number of iterations isn’t known beforehand
Summary
  • A while statement executes repetitive processing as long as a condition is True
  • for loops are suitable for loops with a fixed number of iterations, while while loops are suitable for loops with a fixed condition
  • The break statement interrupts a loop, and the continue statement skips the current iteration
  • The else clause can be used to execute processing when a loop terminates normally (not interrupted by break)
  • Be careful of infinite loops, and always ensure there’s a termination condition
  • When using counter variables, don’t forget to initialize and update them
📚Comprehensive Exercise: Number Guessing Game

Create a number guessing game where the player tries to guess a random number between 1 and 100.

  1. The program selects a random number between 1 and 100
    (We’ll use the random module, but since we haven’t covered it yet, it’s already implemented)
  2. The program repeatedly takes the user’s guess
  3. It displays messages like “The number is higher” or “The number is lower” based on the guess
    (Hint: Convert the input string to a number for processing)
  4. When the user guesses correctly, display “Correct!” and end the game
  5. If the user enters “exit”, end the game
Sample Solution

Related Content