Course Outline (Part 16)

Python has two primitive loop commands:

  • while loops
  • for loops

1. while loop

With the while loop we can execute a set of statements as long as a condition is true.

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

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

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.


2. break statement

With the break statement we can stop the loop even if the while condition is true.

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

Output:

1
2
3

As soon as i hits 3, the loop is completely terminated.


3. continue statement

With the continue statement we can stop the current iteration, and continue with the next iteration.

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

Output:

1
2
4
5
6

Note that the number 3 is missing. The continue statement skips the rest of the code block for that specific iteration.


4. else with while

With the else statement we can run a block of code once when the condition no longer is true.

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

Important Note: The else block will NOT be executed if the loop is stopped by a break statement. It only executes when the loop condition naturally becomes False.


5. Infinite loop (caution)

An infinite loop occurs when the while condition never evaluates to False. This usually happens if you forget to increment/decrement your counter variable or if your logic is flawed.

# WARNING: This is an infinite loop!
# x = 5
# while x > 0:
#     print("Always true!")

If you accidentally run an infinite loop in your terminal, you can usually stop it by pressing Ctrl + C (Keyboard Interrupt).

Discussion

Loading comments...