While Statement (Python)
To create a conditional loop in Python, use the while statement.
while [ condition ]:
block of code
This statement executes the indented block of code as long as the while condition is true.
The loop stops when the condition becomes false.
What is indentation? Python doesn't use braces to group a block of code. Instead, it relies on indentation. The code block is indented to the right of the while structure. This technique is called significant indentation.
It's important not to forget the colon : after the while condition. I often do.
A Practical Example
This script prints the numbers from 1 to 4:
- x=1
- while x<5:
- print(x)
- x+=1
- print("end")
It's important to note that the code block within the while loop consists only of lines 3 and 4. These lines are indented to the right of the while statement.
Line 5, however, is outside the while loop because it's at the same indentation level as the while statement. Therefore, it is not indented.
The program's output is:
1
2
3
4
end
The Difference Between while and for
Both while and for loops allow you to create loops in Python.
However, there are two important differences:
- The while loop uses a counter variable to count iterations, while the for loop iterates over an object.
- The while loop creates an indeterminate loop, as the number of iterations is not known in advance, whereas the for loop is a determinate loop.
Loop Interruptions
In a while loop, you can use the break and continue statements to control the flow:
- break stops and exits the loop, passing control to the first instruction after the loop.
- continue skips the current iteration and proceeds to the next iteration.
Example 1 (break)
On the second iteration (x=3), the break statement exits the loop.
- x=0
- while x<6:
- x+=1
- if (x==3): break
- print(x)
- print("end")
The output is:
1
2
end
The while loop terminates early at the third iteration.
Example 2 (continue)
On the second iteration (x=3), the continue statement skips the rest of the code and proceeds to the next iteration (x=4).
- x=0
- while x<6:
- x+=1
- if (x==3): continue
- print(x)
- print("end")
The output is:
1
2
4
5
6
end
In this case, only the third iteration is skipped.
And so on.