Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance. A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
Expression for while loop
while expression:
statements
Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.
In programming, there are two types of iteration, indefinite and definite:
With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.
n = 0
while n > 0:
n += 1
print(n)
The Python break and continue Statements In each example you have seen so far, the entire body of the while loop is executed on each iteration.
Python provides two keywords that terminate a loop iteration prematurely:
The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.
The Python continue statement immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.
Break Statement program
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
Continue Statement program
n = 5
while n > 0:
n -= 1
#print("n",n)
#continue
if n == 2:
continue
print(n)
print('continue Loop ended.')
print('break Loop ended.')
0 Comments