Python While Loop
In this tutorial you'll learn how to repeat a series of actions using while loop in Python.
A condition-controlled loop causes a block of code to repeat as long as a condition is true. The while statement is used to write condition-controlled loop in Python.
While Loops
2019-01-14T00:56:09+05:30
2019-01-14T00:56:09+05:30
In this tutorial you will learn how to use Python while loops to automate the repetitive tasks within a program to save the time and effort.
Amit Arora
Amit Arora
Python Programming Language Tutorial
Python Tutorial
Programming Tutorial
The while Loop
The while loop checks whether the expression that follows it evaluates to true or not. It keeps executing until the expression returns true.
Example
This while loop executes 10 times unless the condition num is less than or equal to 10 returns false.
num = 1 while num <= 10: print("5 X ", num, " = ", 5 * num) num = num + 1
Output
5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25 5 X 6 = 30 5 X 7 = 35 5 X 8 = 40 5 X 9 = 45 5 X 10 = 50
The break Statement
The break statement is used to terminate the execution of loop even if the while condition is true.
Example
Exit the loop when num is 5:
num = 1 while num <= 10: print("5 X ", num, " = ", 5 * num) if num == 5: break num = num + 1
Output
5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25
The continue Statement
The continue statement is used to skip or stop the remaining iteration of loop and to shift the control back to the beginning of the loop.
Example
Continue to the next iteration if num is 5:
num = 0 while num <= 10: num = num + 1 if num > 5: continue print("5 X ", num, " = ", 5 * num)
Output
5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25