Controlling the Loop: Condition and Increment
The condition and the increment within a while loop are essential components for controlling its behavior.
Condition
The condition determines whether the loop should continue executing or terminate. It is evaluated at the beginning of each iteration. If the condition is initially False, the loop body is skipped entirely.
You can use various types of expressions as conditions, such as:
- Comparison operators (<, >, <=, >=, ==, !=) to compare values
- Logical operators (and, or, not) to combine multiple conditions
- Function calls that return a boolean value
- Variables or expressions that evaluate to True or False
For example:
age = 18
while age < 21:
print("You are not old enough.")
age += 1
print("You are now old enough!")
In this code, the while loop continues as long as the age variable is less than 21. Inside the loop, we print "You are not old enough." The age variable is incremented by 1 in each iteration. Once age reaches 21, the loop terminates, and we print "You are now old enough!"
Increment
To avoid an infinite loop, it's crucial to ensure that the loop condition eventually becomes False. One common way to achieve this is by modifying the loop variable or other relevant variables within the loop body.
In the previous examples, we used the += operator to increment the loop variable. This operator is shorthand for x = x + 1. Similarly, you can use -= for subtraction, *= for multiplication, /= for division, and so on.
Remember to update the loop variable in a way that eventually satisfies the loop condition. Otherwise, the loop may run indefinitely.