Basics
Python While Loops
Using While Loops in Python
Python while loops iterate with break/continue, avoiding infinite loops.
Introduction to Python While Loops
Python while
loops are a fundamental control structure used to repeat a block of code as long as a specified condition is True
. They are essential for tasks that require repeated execution, such as processing items in a list or reading input until a valid response is received. However, improper use can lead to infinite loops, where the condition never becomes False
, causing the program to run indefinitely.
Basic Syntax of a While Loop
The basic syntax of a while
loop in Python is straightforward:
Here, condition
is a boolean expression. The loop executes the indented block of code repeatedly as long as the condition remains True
. The pass
statement is a placeholder used when no action is required.
Example: Counting with While Loops
Consider the following example, where we use a while
loop to count from 1 to 5:
This loop starts with count
equal to 1 and continues to print and increment count
until it exceeds 5. Note how the counter variable count
is incremented within the loop to avoid an infinite loop.
Using Break in While Loops
The break
statement provides a way to exit a loop prematurely when a specific condition is met, even if the loop's condition is still True
. This can be useful for searching through data or handling exceptions.
In this example, the loop is set to run indefinitely with while True
, but the break
statement exits the loop once count
reaches 5.
Using Continue in While Loops
The continue
statement allows you to skip the rest of the code inside the loop for the current iteration and move to the next iteration immediately. This is useful when you want to skip certain conditions.
In this code, when count
equals 3, the continue
statement is executed, and the loop skips printing the number 3, proceeding directly to the next iteration.
Avoiding Infinite Loops
Infinite loops occur when the loop's condition never becomes False
. To avoid this, always ensure that the loop's condition will eventually evaluate to False
, often by modifying a variable involved in the condition within the loop.
A common practice is to include control variables that are updated within the loop to ensure termination. This example demonstrates a properly controlled loop that will run exactly five times.
Basics
- Introduction
- Installation
- Running Code
- Syntax
- Variables
- Data Types
- Numbers
- Strings
- Booleans
- Type Conversion
- Operators
- Ternary Operator
- If Else
- Match Case
- While Loops
- For Loops
- Lists
- Tuples
- Dictionaries
- Sets
- Comprehensions
- Functions
- Arguments
- Scope
- Errors
- Debugging
- String Formatting
- Security Basics
- Best Practices
- User Input
- Built-in Functions
- Keywords
- Previous
- Match Case
- Next
- For Loops