Python While Loops



while a loop is used when the body will execute until the given condition is true.

Sometimes, we require to execute a statement more than one time.

Python has only two types of loops:

  • while loop
  • for loop

Syntax

while condition:
    statement

Example 1

x = 1
while x < 6:
    print(x)
    x += 1

Output

1
2
3
4
5

Example 2

x = ["Python", "HTML", "Java", "Angular"]
while x:
    print(x.pop())

Output

Angular
Java
HTML
Python

Break keyword in while Loop

Python Break keyword used to terminate the loop.


Example

x = 1
while x < 6:
    print(x)
    x += 1
    if x == 3:
        break

Output

1
2

Continue keyword in while Loop

The continue keyword skips the current repetition of a loop and continues with the next repetition.


Example

x = 1
while x < 6:
    x += 1
    if x == 3:
        continue
    print(x)

Output

2
4
5
6

Else Keyword in While Loop

The Else keyword used when the condition of while fails then the else part is executed.


Example

x = 1
while x < 6:
    print(x)
    x += 1
else:
    print("This is Else Part")

Output

1
2
3
4
5
This is Else Part

We can reliably perform an infinite loop in your program using a break statement.