9.1 Conditional Loop
A loop for is perfect for situations where we know exactly how many times we want to execute the block of commands. But that's not always the case. About half of the time, you need to run a block of commands while some condition (rule) is true.
That's what the while loop in Python is for. Its general form is even simpler than that of a for loop:
while condition:
command1
command1
commandN
The loop will continue as long as the condition is true.
Important! To prevent the loop from running indefinitely, something inside the block of commands must affect the condition so that it can eventually become false and the loop can terminate.
Example:
| Example | Explanation |
|---|---|
|
The loop will print the numbers 0 1 2 3 4 |
In a while loop, two things happen repeatedly:
- The condition is checked.
- The block of commands is executed.
If the condition was true, the block of commands will execute. If for some reason the condition is false (even if the block of commands hasn't run once), the loop will end.
Another example of a while loop combined with user input of an unknown amount of data:
| Example | Explanation |
|---|---|
|
The loop will print everything on the screen until the user enters the word exit. After that, the loop will print it and terminate. |
9.2 break Statement
In Python, the break statement is used to immediately stop the execution of a while loop or a for loop. This statement is extremely useful in situations when it's necessary to exit a loop before its normal conditional termination.
Using break enhances the flexibility of controlling the flow of program execution, allowing for responses to dynamically changing conditions during runtime.
Basic usage:
for num in range(10):
if num == 5:
break # Stops the loop once num reaches 5
print(num)
In this example, the loop will print numbers from 0 to 4. As soon as num reaches 5, the loop is interrupted by the break statement.
Usage in infinite loops:
while True:
response = input("Enter 'exit' to quit: ")
if response == 'exit':
break
Here, break is used to exit an infinite loop when the user inputs 'exit'.
The break statement is also frequently used to stop the execution of nested loops, handle exceptional situations that require immediate termination, and to abort processes in multithreaded or networking applications.
For example, in search or sorting tasks, where after finding the needed element, further loop execution doesn't make sense:
elements = [1, 2, 3, -99, 5]
# Finding the first negative element
for element in elements:
if element < 0:
print("Found a negative element: ", element)
break
Best practices include using break wisely, to avoid complicating program logic and making it hard to understand. It's a good practice to comment on the reasons for breaking out of the loop, especially if they're not obvious from the context.
Use of break should be justified and appropriate. For example, to improve code readability and efficiency, not just to "break" the logic. Effective use of this statement can significantly enhance program performance, especially in compute-intensive algorithms.
9.3 continue Statement
The continue statement in Python is a powerful tool for controlling the flow of loop execution. It skips the remaining code in the current iteration of the loop and proceeds to the next iteration. This statement is often used in for and while loops to skip certain conditions without breaking the whole loop.
Basics of using the continue statement
This is how continue works in a simple loop:
for i in range(10):
if i % 2 == 0:
continue
print(i)
In this example, the loop prints only the odd numbers from 1 to 9. Every time i is even (divided by 2 with no remainder), the continue statement triggers, skipping the print() call and proceeds to the next iteration.
Application of continue in real scenarios
Data filtering: continue can be used for pre-filtering data before performing more complex operations in the loop.
data = ["apple", "banana", "", "cherry", "date"]
for fruit in data:
if not fruit:
continue # Skip empty strings
print(fruit.capitalize())
Skipping specific conditions: Especially useful in situations where certain elements need to be skipped based on complex conditions.
scores = [92, 85, 99, 78, 82, 100, 67, 88]
for score in scores:
if score < 80:
continue # Skip low scores
print("Congratulations, your score: ", score)
The continue statement in Python offers an elegant way to simplify code and make it more readable by skipping non-relevant elements in iterations. Overusing continue might make it harder to understand which data is being processed by the loop, especially in complex loops with many conditions. Keep a reasonable balance.
GO TO FULL VERSION