The While Loop in Python

Life is 10% what happens to us and 90% how we react to it. If you don't build your dream, someone else will hire you to help them build theirs.

The While Loop in Python

Let’s talk about the while loop in Python. The while loop is used to be executing a suite, or a block, of code if its condition is true. For example, here we see the ‘counter=3’, the while statement has its condition that follows it, and a colon. If that evaluates to a true condition, then it’s going to execute the indented block, or suite, of code. So since 3 is greater than zero, it is going to execute this print statement, counting down that value 3 and then we see a decrement statement, here, where counter will equal counter -1 or counter will be 2.

#The while loop executes a suite of code if its condition is True 
 counter= 3 
 while counter > 0:    
	print("Counting down:", counter)    
	counter -=1 
 
 while counter > 0:    
	print('Never executes suite')    
	print('when condition is False') 
	
 while 1:    
	print('Executes at least once')    
	if not counter:        
		break 
	
	names = ['Tom', 'Ellen'] 
	while names:
	print(names.pop(), 'is going')
	results = [1, 0, 1] 
	processed = 0
	passed = 0 
	while results:    
		processed += 1    
		result = results.pop()
		if not result:        
			continue    
			passed += 1 
		else:
			print('Processed:', processed, 'Passed:', passed) 

	
	The output :
	Counting down: 3 Counting down: 2 Counting down: 1
	Executes at least once 
	Ellen is going Tom is going 
	Processed: 3 Passed: 2

Now it’s possible that a while loop might never execute. Remember the counter variable is now zero, and zero is not greater than zero, so the print statement never executes suite. And the other one, when condition is false, never gets printed, as we see over here. So if you have a false condition, the loop will never execute. If you have a true condition, something that’s always true, which is a common Python idiom to use, while 1, we also could have put while true. It’s just more verbiage. So we’ll always execute, at least once, this print statement and then it checks a condition here, if not counter, so if the counter variable is zero, that’s false, not false is true, and if true statement will execute its suite of code. In this case, break will cause the while loop to exit. The break statement can be used to exit a while loop before the while condition becomes false. Obviously, with a static value of 1, that while loop would never become false. So it would be critical to be able to break out of that loop.

While loops can be used to process things that might contain a sequence until that sequence is empty.

names =['Tom', 'Ellen'] 
 while names:    
	print(names.pop(), 'is going') 
	
  The output: 
	Ellen is going 
	Tom is going

So there you see how to use the while statement in Python, to control the flow of your code execution, to execute a suite or block of code while a condition is true.