Advertisement



< Prev
Next >



Python While Loop





Like other programming languages, Python language also provides us a feature of while loop, which allows us to execute a block of statements in a loop until a condition declared in while loop is being fulfilled.



Working of while loop


The condition of while loop is tested for the boolean value - true or false.





Important points about conditional statements in Python





Advertisement




while loop example


#Python - while loop example

i=0;

while(i<5):
	print("i =", i)
	i=i+1


Output


i = 0
i = 1
i = 2
i = 3
i = 4



Program Analysis







While loop must have an iteration part in its body or it ends an endless loop


#Python - indefinite while loop example

i=0;

while(i<5):
	print("i =", i)


Output


This program on execution runs indefinitely in a loop because of the absence of incremental part to increment the value of i.




While loop with optional else statement


Unlike other programming languages like C, C++, and Java, we can optionally declare else statement with while loop. The statement associated with this optional else statement is only executed when the condition of while loop evaluates to false.

#Python - while loop with optional else statement example


i=0;

while(i>5):
	print("i =", i)
else:
	print("i is not greater than 5")


Output


i is not greater than 5

In the above program, the condition of while loop is evaluated to false, therefore the statement associated with the optional else statement is executed.



Please share this article -





< Prev
Next >
< Python nested if else statement
Python for loop >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement