Learn to execute Python statement(s) as long as a condition is True with the help of while
loop.
1. The while
Loop
A while
loop executes a given set of statements in loop, till the time a given conditional expression is True. As soon as, the conditional expression becomes False, the while
loop ends.
We use while
loop when we do not know the number of iterations beforehand. Let’s understand the while
loop with a simple Python program.
Example: Print numbers from 1 to 5 using while loop
i = 1 while i <= 5: print(i) i += 1
Program output.
1 2 3 4 5
In above Python program, the local variable i
store the current number. We initialize i
with initial value 1.
The program prints the value of i
by 1. After program prints i
value to 5, the next time we increment the i
to 6.
At this time, the condition 'i <= 5'
becomes False and the while loop exit.
Do not forget to increment the value of
i
, else while loop will never exit. It is called the infinite loop.
Also, be very careful about the code indentation because Python uses indentation for defining the scope of the code blocks.
2. The while
Loop with else
Statement
The else
statement, in while
loop, acts very similar to if...else statements. The else
statement executes when the conditional expression in while
loop becomes False.
i = 1 while i <= 5: print(i) i += 1 else: print('The while loop ends')
Program output.
1 2 3 4 5 The while loop ends
3. The while
Loop with break
Statement
The break
statement helps to exit the loop even when the conditional expression is True. When the break
statement is executed, program execution jumps to the statement immidiately after the while
loop.
i = 1 while i <= 5: print(i) if i == 3: break i += 1 print("Statement after while loop")
Program output.
1 2 3 Statement after while loop
4. The while
Loop with continue
Statement
The continue
statement helps to exit the current iteration in the loop and start a new iteration from the start of the loop.
When the continue
statement is executed, program execution jumps to the start of the while
loop.
In this Python program, we are printing the value of 'i'
only when it is odd number. In case of i
is even number, we skip the current iteration using the continue
statement.
i = 0 while i <= 5: i += 1 if i % 2 == 0: continue print(i) print("Statement after while loop")
Program output.
1 3 5 Statement after while loop
Happy Learning !!