Python While-loop

The while loop executes a block of code until a given condition is True. First, it checks the condition before executing the block of code. If the condition is True, it executes the block of code. It then again goes back to check the condition, and the process goes on until the condition becomes False.

Syntax

while Boolean-expression: statement

The while loop starts with the while keyword and ends with a colon. First, the Boolean expression is evaluated. If the condition is fulfilled, statements in the while loop block are executed. If the conditional expression evaluates to False, statements in the while loop block are not executed. If the conditional expression evaluates to TRUE, then after each iteration, the expression is checked, and the same process repeats until the conditional expression evaluates to FALSE.

For example

			

num=2
while num<10:
	print(num)
	num+=1

				

Output:

2 3 4 5 6 7 8 9

Like the for loop, we can define an else block with the while loop as well. This else block is executed before the termination of the while loop. If a break statement is executed to terminate the loop, the else block is not executed.

			

num=2
while num<10:
	print(num)
	num+=1
	if num==6:
		break
	else:
		print("Else block executed")

				

Output:

2 3 4 5