THEORY AND PRACTICE
-
Input and Output Data
- Tasks
-
Conditions
- Tasks
-
For Loop
- Tasks
-
Strings
- Tasks
-
While Loop
- Tasks
-
Lists
- Tasks
-
Two-Dimensional Arrays
- Tasks
-
Dictionaries
- Tasks
-
Sets
- Tasks
-
Functions and Recursion
- Tasks
Lesson 5. The while loop in python
Introduction to the while cycle in Python
Cycle while Python what is repetition
In programming, a loop is a construct that allows the same block of code to be executed repeatedly. The while loop (translated from English as "bye") executes the code over and over, as long as the specified
condition remains true (True). It's like telling a computer: "Keep doing this until I tell you to stop"
or "Keep doing it until the score reaches ten."
The difference from the cycle for
The main difference between the while loop and the for loop is the execution condition.
- The
forloop is used when you know in advance how many times you need to run the loop. It is ideal for iterating over elements in a sequence (for example, in a list, a string, or a range of numbersrange()). - The
whileloop is used when the number of repetitions (iterations) is unknown in advance. The cycle does not continue for a certain number of times, but as long as a certain condition is met.
The main scenarios for using the while
Cycle while is indispensable in situations where you need to wait for an event.:
- Waiting for input from the user (for example, until he enters the word "exit").
- The program works until the desired result is achieved (for example, in games or simulations).
- Reading data from a file or network connection until the data runs out.
Basic structure and syntax
The syntax of the while loop is very simple. It consists of the while keyword, followed by
a condition, a colon, and an indented code block.
while condition:
# This code will be executed,
# as long as the "condition" is True
Loop while Python easy to use
Let's look at a simple example that prints numbers from 0 to 4.
Initializing the counter variable
Before starting a loop, we need a variable that will control its execution. It is usually called a counter. Let's initialize it with the value 0.
counter = 0 # Initial value
Checking the loop continuation condition
Our condition is counter < 5. Before each execution of the loop body, Python will check: "Is the counter variable still less than 5?". If yes (True), the code inside the loop is executed. If not (False),
the loop ends.
Loop body: actions and variable changes
Inside the loop, we first perform a useful action (print the counter value), and then we must change
the counter variable. If this is not done, the counter < 5 condition will always be true, and the cycle
will become endless!
Cycle termination when condition changes
When counter becomes 5, the condition 5 returns False. At this point, Python
will skip the body of the loop and proceed to execute the code that follows it.
Here is the full code:
# 2.1. Initializing the counter variable
counter = 0
# 2.2. Checking the cycle continuation condition
while counter < 5:
# 2.3. The body of the loop: actions and variable changes
print(f"Current counter value: {counter}")
counter = counter + 1 # or for short: counter += 1
# 2.4. Ending the loop when condition is changed
print("The loop is completed because counter has become equal to 5.")
Loop control statements while
Sometimes you need to manage the cycle more flexibly: exit it ahead of schedule or skip the current step. There are
break and continue operators for this.
The break operator in Python loops
Operating principle and purpose
The break statement immediately and completely stops executing the loop it is in.
Use for early exit from the cycle
It is used when a certain critical condition is reached inside the loop, after which further execution of the loop is pointless or undesirable.
Application example in a loop while
Imagine that we are looking for the first number greater than 5, which is divisible by 3.
number = 1
while number < 20:
print(f"Checking the number: {number}")
if number > 5 and number % 3 == 0:
print(f"Found! This is a {number}. Exit the loop.")
break # Early exit from the loop
number += 1
print("Code after the loop.")
Operator continue Python loop logic
Operating principle and purpose
The continue operator interrupts only the current iteration (current step) of the loop and immediately proceeds to check the condition for the next iteration.
Skipping the remaining code of the current iteration
All the code that is in the body of the loop after continue will be skipped.
Moving to the next iteration of the loop
Execution "jumps" back to the line while the condition:.
Usage example continue
Let's print only the odd numbers from 1 to 10.
num = 0
while num < 10:
num += 1
# If the number is even...
if num % 2 == 0:
continue # ...skip the rest of the code and go to the next number.
# This code will run only for odd numbers
print(f"Odd number: {num}")
The elseblock in the while loop with the condition
What is the else block after cycle
In Python, the while loop can have an optional else block. The code in this block is executed once when the loop ends naturally (that is, when its condition becomes false).
Conditions for executing the else
Block else is executed only if the loop has completed all its iterations and has not been interrupted
by the break statement.
Behavior of the else block when using break
If the loop was interrupted using break, the else block is not executed.
This is its key feature.
An example of using the else
block is let's find a number in the list. If we find it, we will exit through break. If you have gone
through the entire list and haven't found it, the else block will report this.
# Scenario 1: number found
items = [1, 5, 9, 12, 23]
search_value = 12
index = 0
found = False
while index < len(items):
if items[index] == search_value:
print(f"The value of {search_value} was found at position {index}.")
break # We're going out because we found it
index += 1
else:
# This block will fail because the loop was interrupted by break
print(f"The value of {search_value} was not found in the list.")
print("-" * 20)
# Scenario 2: number not found
search_value = 10
index = 0
while index < len(items):
if items[index] == search_value:
print(f"The value of {search_value} was found at position {index}.")
break
index += 1
else:
# This block will be executed, as the cycle has ended naturally
print(f"The value of {search_value} was not found in the list.")
Nested loops while python examples
Nested Python loops repeat execution
A nested loop is a loop that is inside another loop. The inner loop will be executed completely for each iteration of the outer loop.
Example of a nested loop with two counters
Let's print the multiplication table. The outer loop will be responsible for the first multiplier, and the inner one for the second.
i = 1 # Outer loop counter
while i <= 5:
j = 1 # Counter of the inner loop, reset at each iteration of the outer loop
while j <= 5:
print(f"{i} * {j} = {i * j}")
j += 1
print("--- The inner loop is completed ---")
i += 1
Practical application of nested loops
Nested loops are used to work with two-dimensional data structures (matrices, tables), to iterate through combinations, or to create complex game fields.
Processing user input with a loop while
Using a loop to re-request data
This is one of the most frequent and useful scenarios for while. We can ask the user for input until they enter the correct data or exit command.
Example of a loop running until successful completion
A simple program that will "listen" to the user until he writes "exit".
user_input = ""
while user_input.lower()!= "exit":
user_input = input("Enter something (or 'exit' to complete): ")
if user_input.lower() != "exit":
print(f"You have entered: {user_input}")
print("Program completed.")
Processing incorrect input and re-requesting
It is often necessary not only to wait for the command, but to check whether the input meets certain criteria.
Example of checking the correctness of entering a number
We will ask the user to enter a number from 1 to 10. We will repeat the request until we get the correct input.
while True: # Use an "infinite" loop, exit it through a break
try:
age_str = input("Enter your age (number): ")
age = int(age_str) # Trying to convert a string to a number
if 1 <= age <= 120:
print("Thanks! The age is correct.")
break # The input is correct, we exit the loop
else:
print("Error: age should be in the range from 1 to 120.")
except ValueError:
# This error will occur if the user enters a non-number (for example, "abc")
print("Error: please enter an integer.")
Infinite loops in Python while
Definition of an infinite loop
An infinite loop is a loop whose condition never becomes false (False). This can be either a mistake in the code or an intentional trick.
Creating a loop with the condition True
The easiest way to create an intentional infinite loop is to use while True.:.
How to avoid program freezes — exit the endless loop
Such a loop must contain a condition with the break operator to exit. Otherwise, your program will "hang" and run forever.
Example of an infinite loop with exit condition at the user's command
This is an improved version of the example with user input.
while True: # Intentional infinite loop
command = input("Enter the command ('start', 'stop', 'exit'): ")
if command == 'start':
print("The system is starting...")
elif command == 'stop':
print("The system is stopped.")
elif command == 'exit':
print("Exit the program.")
break # The only way to complete this cycle
else:
print("Unknown command.")
Avoiding errors and endless loops
The value of changing variables in the body of the loop
The most common mistake of beginners is to forget to change the variable that is checked in the loop condition. Always make sure that there is a code inside the loop that sooner or later will make the condition false.
Cycle termination control
Before running the code, mentally scroll through several iterations. Make sure that your counter variable is moving in the right direction (increases to the limit if the condition or decreases if ).
Tips for avoiding endless loops
- Always make sure that the variable in the
whilecondition changes inside the loop. - If you use
while True, make sure that there is at least onebreakinside. - Carefully check the logic of the conditions (
,,==,!=).
Example of a safe loop with a condition change
# Wrong: an infinite loop, since i will never change
# i = 0
# while i < 5:
# print("This is a mistake!")
# Correct: i changes at each iteration
i = 5
while i > 0:
print(f"Countdown: {i}")
i -= 1 # Reducing i, bringing the end cycle closer
print("Start!")
Debugging and testing loops while
Using print to check values inside a loop
The easiest way to debug is to insert print() into different parts of the loop to see how the variable values change at each step.
Step-by-step tracking of variable changes
Modern development environments (IDEs), such as PyCharm or VS Code, have debuggers that allow you to run code step-by-step and monitor all variables in real time.
Practical tips for debugging loops
- Print the value of the counter variable right before checking the condition (outside the loop) and at the end of each iteration.
- If the loop does not behave as expected, temporarily simplify the condition to
Trueand control the output only viabreakwithprint's to understand at what point the logic breaks.
Example of the status output before and after changing the counter variable
count = 0
limit = 4
while count < limit:
print(f"--- Start of iteration ---")
print(f"State BEFORE: count = {count}. Condition (count) - ({count} {4}) this is the {count < limit}.")
print(f"Doing useful work for count = {count}")
count += 1 # Changing the counter
print(f"State AFTER: count = {count}.")
print(f"--- End of iteration ---\n")
print("The cycle is completed.")