The while not statement in Python is used to execute a block of code repeatedly as long as a certain condition is false(condition is not met).
The while loop is used for repeated execution as long as a condition is true.
Adding not to the condition inverts the logic.
Example 1: Basic Usage
x = 5
while not (x == 0) :
print(x)
x = x - 1
Output
5
4
3
2
1
This loop prints numbers from 5 to 1. It will stop when x becomes 0 because the condition not (x == 0) (which is equivalent to x != 0) becomes false.
Example 2: Using with list
listA = [1, 2, 3]
while 7 not in listA:
listA.append(len(listA) + 1)
print(listA)
Output
1, 2, 3, 4, 5, 6, 7]
Example 3: Using with break
The break statement is used to exit a loop prematurely when a certain condition is met.
x = 5
while not (x == 0):
print(x)
x = x - 1
if x <= 2:
break
Output
5
4
3
Example 4: Using with continue
The continue statement skips the current iteration of a loop and proceeds to the next iteration.
x = 5
while not (x == 0):
x = x - 1
if x == 3:
continue
print(x)
Output
4
2
1
0