The “while not” is a variation of the “while” loop that continues to execute a block of code as long as a specified condition is false in Python. It works exactly the opposite of “while loop”. Adding not to the condition inverts the logic.
The while not loop sometimes makes code easier to understand because here we want to make a process repeat until our condition is met to make it false, break the loop, and stop the process.
Syntax
while not condition: # code to execute
The while not loop will repeat the execution as long as a condition is false.
Flowchart
Example 1: Waiting for user input
correct_answer = False while not correct_answer: user_input = input("What's 2 + 2? ") if user_input == "4": correct_answer = True else: print("Incorrect. Try again.") print("Correct!")
Output
In this code example, we are continuously prompting users until they will give us a correct answer. So, we used while not in an inverse way.
Example 2: Expanding a list
We can use the “while not” loop to expand a list until a certain breakpoint is reached.
listA = [1, 2, 3] while 7 not in listA: listA.append(len(listA) + 1) print(listA)
Output
[1, 2, 3, 4, 5, 6, 7]
In this code, we added four new elements because we put a condition that until 7 are there, you will add a new element with incremental value from the previous one. So, when it reaches 6, it will add 7 and when it reaches 7, it will break the loop and print the list.
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
That’s it!