Published on

Controlling Flow in Python

Authors
    avatar

    John Partee

Today, we're going to dive deep into a fundamental concept in any programming language: Control Flow. This concept is the bedrock upon which we build complex programs. In Python, which often acts as the connective tissue for modern web development, understanding control flow is vital.

Conditional Statements: if, elif, else

We start our journey with conditional statements. Imagine these as the crossroads of your program, deciding which path to take based on certain conditions.

If Statement

The if statement is Python's way of performing a task when a particular condition is true. For example:

python

temperature = 30

if temperature > 20:
    print("It's a warm day!")

Here, Python will print "It's a warm day!" if the temperature is more than 20.

Elif and Else Statements

But what if we have more conditions? That's where elif (short for 'else if') and else come in.

python

temperature = 15

if temperature > 20:
    print("It's a warm day!")
elif temperature > 10:
    print("It's a mild day!")
else:
    print("It's a cold day!")

If the temperature is above 20, Python will print "It's a warm day!". If it's not, but it's above 10, it will print "It's a mild day!". For any other temperature, it will print "It's a cold day!".

Looping Structures

Moving on from conditional statements, let's talk about loops. Think of loops as the machinery that allows a task to be repeated until a certain condition is met.

While Loop

The while loop executes a set of statements as long as a condition is true.

python

count = 0

while count < 5:
    print(count)
    count = count + 1

This loop will print the numbers 0 through 4, incrementing the count each time until the count is no longer less than 5.

Break and Continue

Sometimes, you might want to alter the normal cycle of a loop. That's where break and continue come in.

  • break: Exits the loop prematurely
  • continue: Skips to the next iteration of the loop

python

count = 0

while count < 5:
    if count == 3:
        break
    print(count)
    count = count + 1

In this case, the loop will break when the count reaches 3, thus only printing 0, 1, and 2.

For Loop

The for loop in Python is used for iterating over a sequence (like a list, tuple, or string) or other iterable objects.

python

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

This code will print each fruit in the list.

Break, Continue, and Else

Break and continue work the same way in for loops as they do in while loops. But for loops have an additional clause: else.

python

for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)
else:
    print("Loop has finished executing")

Here, the else clause executes after the loop completes all iterations and only if the loop didn't encounter a break.

Nested Loops

Finally, we reach nested loops. As the name suggests, these are loops within loops.

python

for i in range(3):
    for j in range(3):
        print(i, j)

Here, for each iteration of the outer loop, the inner loop runs to completion. This prints pairs of numbers: (0,0), (0,1), (0,2), (1,0), and so on.

Mastering these control flow concepts will set you on the path to becoming a Python whizz. Remember, the power of Python is in its simplicity and readability, which makes it a favorite in modern web development. As you become more proficient, you'll start to see the true power and flexibility it offers. Keep coding, and have fun!

Want an email when we post?

Free, weekly at most. We hate spam too.