The while loop in Python: a complete guide with examples
The while loop in Python is a fundamental design for controlling the flow of program execution, which allows you to repeatedly execute a block of code as long as the specified condition remains true. This loop is especially useful in situations where the exact number of iterations is unknown in advance.
While loop syntax
The basic syntax of the while loop is as follows:
while condition:
# a block of code that runs while the condition is true
The loop continues to run as long as the condition remains true (True). As soon as the condition becomes false (False), the loop execution stops.
A simple usage example
count = 0
while count < 5:
print(f"Iteration number: {count}")
count += 1
In this example, the loop will run 5 times, outputting numbers from 0 to 4.
Infinite while loop
Sometimes you need to create a loop that runs indefinitely:
while True:
print("This loop will run indefinitely!")
# There must be logic to exit the loop here
Important: Always provide a mechanism to exit the endless loop to avoid program freezes.
Processing user input with while
The while loop is ideal for validating user input:
while True:
response = input("Enter 'yes' or 'no': ")
if the response.lower() == 'yes':
print("You entered 'yes'. The program is ending.")
break
elif response.lower() == 'no':
print("You entered 'no'. The program is ending.")
break
else:
print("Error! Please enter 'yes' or 'no'.")
Using conditions in the while loop
number = 10
while number > 0:
print(f"Countdown: {number}")
number -= 1
print("Time's up!")
This example demonstrates a classic countdown using a while loop.
Break statement: forced completion of the loop
The break operator allows you to exit the loop immediately, regardless of the condition:
number = 10
while number > 0:
print(f"Current number: {number}")
if number == 5:
print("The number 5 has been reached. Getting out of the loop.")
break
number -= 1
continue operator: skipping the current iteration
The continue operator allows you to skip the rest of the current iteration and move on to the next one.:
number = 10
while number > 0:
number -= 1
if the number is == 5:
continue # Skip the number 5
print(f"Output a number: {number}")
As a result of executing this code, the number 5 will not be displayed.
Practical usage examples
Searching for an item in the list
numbers = [1, 3, 7, 9, 12, 15, 18]
target = 12
index = 0
while index < len(numbers):
if numbers[index] == target:
print(f"Element {target} found at position {index}")
break
index += 1
else:
print(f"{target} element not found")
Calculator with while loop
while True:
print("Simple calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Exit")
choice = input("Select operation (1-3):")
if choice == '3':
print("Goodbye!")
break
elif choice in ['1', '2']:
try:
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
if choice == '1':
print(f"Result: {a + b}")
elif choice == '2':
print(f"Result: {a - b}")
except ValueError:
print("Error: enter correct numbers")
else:
print("Incorrect selection. Try again.")
Optimization and best practices
- Always ensure that the condition is changed inside the loop to avoid endless loops
- Use meaningful variable names to improve code readability
- Avoid complex conditions in the loop header. Put them in separate variables
- Use the break and continue operators wisely so as not to complicate the logic of the program
Conclusion
The while loop in Python is a powerful tool for creating repetitive operations. Using the break and continue operators correctly allows you to create flexible and efficient algorithms. Having mastered all aspects of working with the while cycle, you will be able to solve a wide range of programming tasks, from simple data processing to creating interactive applications.