Learn to execute Python statement(s) as long as a condition is True with the help of python while loop.
1. The while Loop
- A
whileloop executes a given set of statements in loop, as long as a given conditional expression isTrue. - As soon as, the conditional expression becomes
False, thewhileloop ends.
We should use the while loop when we do not know the number of iterations beforehand.
Example: Print numbers from 1 to 5 using while loop
In the given example, the value of n could be anything. Here it is 5.
i = 1 n = 5 while i <= n: 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', elsewhileloop will never exit. Such loops are called the infinite loops.
Also, be very careful about the code indentation because Python uses indentation for defining the scope of the code blocks.
2. Python while Loop with 'else' Statement
The else statement, in a 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. Python while Loop with 'break' Statement
The break statement helps in exiting the loop even when the conditional expression is True. When the break statement is executed, program execution jumps to the next 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. Python 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 !!
Comments