Python while Loop Statements

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.


Syntax of while

The syntax of a while loop in Python programming language is-

while expression:
   statement(s)

Example : example of while


# example of the while loop
x=True
count=0
while(x):
	print(count)
	count=count+1
	if count==5:
		x=False
		break
0
1
2
3
4

Example : Finding the sum of digits of a number


# finding the sum of digits of a number
number=int(input("Enter the number "))
sum=0
while(number>0):
	sum=sum+(number%10)
	number=number//10

print("sum of the digits : "+ str(sum))
Enter the number 23242
sum of the digits : 13

str() - function is used to convert other type value to string value

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.


# Infinite Loop
while(True):
	print("Hello..python")
Hello..python
Hello..python
Hello..python
Hello..python
Hello..python
Hello..python
Traceback (most recent call last):
  File "dm.py", line 3, in 
    print("Hello..python")
KeyboardInterrupt

While Loop with else block

If the else statement is used with a while loop, the else statement is executed when the condition becomes false.


# While loop with else
i=0
while(i<=5):
	print("Hello..python")
	i+=1
else:
	print("Else block....")
Hello..python
Hello..python
Hello..python
Hello..python
Hello..python
Hello..python
Else block....