Functions, Loops, and Logic

The core of Python programming is conditional if/else/elif control statements, loops, and functions. These are powerful tools that you must master to solve problems and implement algorithms. Use these materials to practice their syntax. If/else/elif blocks allow your program to make conditional decisions based upon values available at the time the block is executed. Loops allow you to perform a set of operations a set number of times based on a set of conditions. Python has two types of loops: for loops and while loops. For loops work by counting and terminating when the loop has executed the prescribed number of times. While loops work by testing a logical condition, and the loop terminates when the logical condition evaluates to a value of false. Functions are designed to take in a specific set of input values, operate on those values, and then return a set of output results.

Break & Continue

break and continue allow you to control the flow of your loops. They're a concept that beginners to Python tend to misunderstand.

Using break

The break statement will completely break out of the current loop, meaning it won't run any more of the statements contained inside of it.

>>> names = ["Rose", "Max", "Nina", "Phillip"]
>>> for name in names:
...     print(f"Hello, {name}")
...     if name == "Nina":
...         break
...
Hello, Rose
Hello, Max
Hello, Nina

Tip: break completely breaks out of the loop.


Using continue

continue works a little differently. Instead, it goes back to the start of the loop, skipping over any other statements contained within the loop.

>>> for name in names:
...     if name != "Nina":
...         continue
...     print(f"Hello, {name}")
...
Hello, Nina

Tip: continue continues to the start of the loop


break and continue visualized

What happens when we run the code from this Python file?

# Python file names.py
names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"]

for name in names:
    if len(name) != 4:
        continue

    print(f"Hello, {name}")

    if name == "Nina":
        break

print("Done!")

break and continue visualized


Results

See if you can guess the results before expanding this section.

(env) $ python names.py

Hello, Rose
Hello, Nina
Done!

Using break and continue in nested loops.

Remember, break and continue only work for the current loop. Even though I've been programming Python for years, this is something that still trips me up!


>>> names = ["Rose", "Max", "Nina"]
>>> target_letter = 'x'
>>> for name in names:
...     print(f"{name} in outer loop")
...     for char in name:
...             if char == target_letter:
...                 print(f"Found {name} with letter: {target_letter}")
...                 print("breaking out of inner loop")
...                 break
...
Rose in outer loop
Max in outer loop
Found Max with letter: x
breaking out of inner loop
Nina in outer loop
>>>

Tip: break in the inner loop only breaks out of the inner loop! The outer loop continues to run.


Loop Control in while loops

You can also use break and continue in while loops. One common scenario is running a loop forever, until a certain condition is met.

>>> count = 0 
>>> while True:
...     count += 1
...     if count == 5:
...             print("Count reached")
...             break
...
Count reached

Note: Be careful that your condition will eventually be met, or else your program will get stuck in an infinite loop. For production use, it's better to use asynchronous programming.