While Loop Usage in Python

Itacen Sabacok | Feb 10, 2022
 1x = 1
 2while x < 10:
 3  print("x:{}".format(x))
 4  x += 1
 5
 6x = 1
 7y = True
 8while y:
 9  print("x:{}".format(x))
10  if x > 5:
11    y = False
12  x += 1

Else Usage

it can be valid when the condition no longer is true.

1x = 1
2while x < 10:
3  print("x:{}".format(x))
4  x += 1
5else:
6  print("x is 10 now")

Continue Usage

Continue to the next iteration. it goes directly to top where loop starts.

1x = 1
2while x < 10:
3  print("x:{}".format(x))
4  if x == 5:
5    continue
6  x += 1

Break Usage

it can stop the loop even if the while condition is true.

1x = 1
2while x < 10:
3  print("x:{}".format(x))
4  if x == 5:
5    break
6  x += 1