Python Interactive Guide - Step 2 Control Flow (4) - Loops (2): while Loops
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 2 Control Flow.”
2.2. Loops
Last time, we learned about loops using the for statement.
This time, we’ll learn about another loop structure, the while statement.
2.2.2. while Loops
Basics of while Loops
The while statement is a loop structure that executes repeated processing as long as the specified condition is True.
- In a
whilestatement, the loop process is executed repeatedly as long as the condition isTrue - 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;
Create a program that counts up from 1 to 10 using a while statement.
Sample Solution
Write a program that divides a specified integer by 2 repeatedly until it becomes an odd number, then outputs the result.
Sample Solution
Add integers starting from 1 in sequence, and display the last integer added and the total sum when the sum exceeds 1000.
Sample Solution
Loop Control Statements
Just like with for loops, you can use break and continue in while loops.
break: Breaking Out of a Loop
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.
Infinite Loops
A loop whose condition is always True is called an infinite loop. Infinite loops are sometimes used in combination with break statements.
while Truealways evaluates toTrue, so it will continue executing forever unless explicitly exited using abreakstatement- Be careful of unintended infinite loops, such as forgetting to update a counter
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.
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
continue: Skipping Loop Iterations
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.
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
break and continue in Nested Loops
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.
while-else Statement
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.
Choosing Between for and while
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 of while Loops
- A
whilestatement executes repetitive processing as long as a condition isTrue forloops are suitable for loops with a fixed number of iterations, whilewhileloops are suitable for loops with a fixed condition- The
breakstatement interrupts a loop, and thecontinuestatement skips the current iteration - The
elseclause can be used to execute processing when a loop terminates normally (not interrupted bybreak) - 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
Create a number guessing game where the player tries to guess a random number between 1 and 100.
- The program selects a random number between 1 and 100
(We’ll use therandommodule, but since we haven’t covered it yet, it’s already implemented) - The program repeatedly takes the user’s guess
- 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) - When the user guesses correctly, display “Correct!” and end the game
- If the user enters “exit”, end the game