While not loop works the same as a simple while loop, it will repeatedly execute the loop’s body until the condition for loop termination is matched. Where a boolean expression executes the loop’s body if the condition evaluates to False.
count= 3
while not (count== 0) :
print(count)
count= count- 1
As the above code loop will execute until the count is zero.
Output:
While not a Python example with an iterable object
The above example code only used a single variable. Let’s execute the loop’s body if the variable is not present in the iterable object.
a_list = [1, 2, 3]
while 3 not in a_list:
a_list.append(len(a_list) + 1)
print(a_list)
Output: [1, 2, 3]
Do comment if you have any doubts or suggestions on this Python while loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.