Python While Loop



Definition


Python while loop is used to execute a block of code until the given condition is True.


Syntax

while condition:
    # block of code
    # to be executed
    # until the condition is True

Examples


Example1

i = 5
while i>0:
    print(i)
    i = i - 1

Output

5
4
3
2
1

Example2

# printing table for any number
number = int(input("Enter number:"))
i = 1
while i!=11:
    print(number, "X", i, "=", i*number)
    i=i+1

Output

Enter number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Example3

# infinite while loop
while True:
    print("This line will print infinite times")

Output

This line will print infinite times
This line will print infinite times
This line will print infinite times
This line will print infinite times
This line will print infinite times
...
...
...

break statement


We can use break statement if we want to exit the while loop.

Generally, we use break statements in while loop when we have some specific conditions to exit the while loop.


Example1

i = 0
while True:
    print(i)
    if i==5:
        break
    i = i + 1

Output

0
1
2
3
4
5

Example2

# printing table
i = 1
number = 10
while True:
    if i==11:
        break
    print(f"{number} X {i} = {number*i}")
    i = i + 1

Output

10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

If you have any confusion in the 7th line about f, then click here. Scroll down on that page and read fast string concepts.



continue statement


Unlike the break statement, continue statement skips one step of the loop and continues with the next step.


Example1

i = 0
while i<6:
  i=i+1
  if i==2:
    continue
  print(i)

Output

1
3
4
5
6

Example2

# skipping every step
i = 0
while i<6:
  i=i+1
  continue
  print(i)

Program outputs nothing


while… else…


In python, we can use else statement with while loop.

Block of else statement will be executed every time unless the while loop is terminated with a break statement.


Example1

i = 0
while i<6:
  i=i+1
  print(i)
else:
  print(i)

Output

1
2
3
4
5
6
6

Example2

i = 0
while i<6:
  i=i+1
  print(i)
  if i==4:
    break
else:
  print(i)

Output

1
2
3
4