While Loop In Python
A while
loop in Python is a control flow statement that allows you to repeat a block of code as long as a certain condition is true. while loop body define by indentation(whitespaces'TAB').
Before using the while loop you must mention the termination condition otherwise it will goes infinite loop and your system may be crashed.
The basic syntax for the while
loop is as follows:
while condition:
# code to be executed as long as the condition is true
Example:
a = 1
while a <= 10: # condition
print("hello World",a)
a+=1 # update the variable
In the above example, the condition a <= 10
is checked at the beginning of each iteration. If the condition is true, the code block is executed, and then the condition is checked again. This process continues until the condition becomes false, at which point the loop terminates.
While Else
In python, We can use else
statement with while
loop . when successfully while loop end else
block code execute, if while loop terminated by break
keyword else block does not execute .
a = 1
while a < 10:
print("hello World",a)
a+=1
else:
print("fine") # it will execute after completing the loop
#another example
a = 1
while a < 10:
print("hello World",a)
a+=1
if a == 5:
break # terminate the loop
else:
print("fine") # it will not execute
It's important to note that the condition in the while
loop should eventually become false, otherwise the loop will run indefinitely and cause an infinite loop. To avoid this, you should make sure to change the value of one or more variables inside the loop so that the condition eventually becomes false.