Python While Loop Statements

The python looping statements are,

  • while loop
  • range()
  • for loop

While loop:

This is one of the most used control statements. The while loop is used to execute the body as long as the condition evaluates true. This loop works like the same as for loop. 

Syntax:

while ( condition ):
     # statement or body
     # increment or decrement

Sample code:

x = 3        # Initilize the value
while i < 9:
  print(x)   # Print the value
  x += 1     # Incremant x variable

# Output
# 3
# 4
# 5
# 6
# 7
# 8

Break Statement:

In Python, the break keyword is used to terminate the currently executing loop. In the case of a nested loop, the break keyword can terminate the innermost loop. This break keyword can also stop the currently executing loop when a loop condition is in a true state.  

Sample code:

x = 3        # Initilize the value
while i < 9:
  print(x)   # Print x variable value
  if x == 6:  
    break    # The loop will stop when x==3 and exist the loop.
  x += 1     # Increment x 

# Output
# 3
# 4
# 5
# 6

Continue Statement:

The continue keyword is used to skip the currently executing iteration of the loop and start the execution from the next iteration. 

Sample Code:

x = 5        
while x > 0:
      if  x == 3:
          continue
      print ( x ) # output will be 5 4 2 1. (It exclues 3)
      x—