Python While Loop

Python Loop

Python has two primitive loop commands:

  • while Loop
  • for Loop

while loop

If using while Loops, we can execute a group of statements as long as the condition is true.

Example

Print i as long as i is less than 7:

i = 1
while i < 7:
  print(i)
  i += 1

Run Instance

Note:Remember to increment i, otherwise the loop will continue forever.

while Loops need to prepare the relevant variables. In this example, we need to define an index variable i, we set it to 1.

break statement

If using break Statement, we can stop the loop even if the while condition is true:

Example

Exit the loop when i equals 3:

i = 1
while i < 7:
  print(i)
  if i == 3:
    break
  i += 1

Run Instance

continue statement

If using continue Statement, we can stop the current iteration and continue to the next:

Example

If i equals 3, continue to the next iteration:

i = 0
while i < 7:
  i += 1 
  if i == 3:
    continue
  print(i)

Run Instance

else statement

By using the else statement, we can run a code block once when the condition no longer holds:

Example

Print a message when the condition is false:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

Run Instance