Control Flow in Python: Conditional Statements and Loops

Control Flow in Python: Conditional Statements and Loops

·

8 min read

In programming, control flow stands as the fundamental mechanism that governs the sequence in which instructions are executed within a program. It dictates the path a program takes, allowing it to make decisions, repeat tasks, and respond to user input.

Think of programing as instruction given to the computer and control flow as the roadmap that guides the execution of those instructions.

Python provides a rich set of features for controlling the flow of your program. From conditional statements and loops to control flow keywords and exception handling, the control flow mechanisms offer flexibility and readability.

In this blog post, we will delve into these features, exploring how they work and when to use them in your code.

Conditional Statements

Conditional statements are a way to make decision in your code based on whether the given condition is true or false.

Handling simple conditions

The most basic conditional statement is the if statement.

if condition:
    # peform this task

If the condition is true, then the given task, within the indented code block, is performed.

An else statement is added so that when the if condition is false then indented block under it is skipped and a different task can be performed. Let us see how that syntax would be written:

if condition:
    # perform this task
else:
    # perform this task instead

Let us visually see how to use the if else statement with a simple example:

# Check if number is divisible by 5
num = 25
if num % 5 == 0:
    print("Number is divisible by 5")
else:
    print("Number is not divisible by 5")

The example above simple checks if a number is divisible by 5. We first initialize a variable num and assign it the value 25.

Our if condition checks if num is divisible by 5 using the modulus (%) operator. If the statement is true, then Number is divisible by 5 should be printed. In this case since 25 is divisible by 5 then our output will indeed be Number is divisible by 5.

If the value of our variable num was 13 then we would get Number is not divisible by 5

Handling multiple conditions

There are two ways that I will talk about when handling multiple conditions within your code. The first is by using multiple if statements while the second is using elif (short for else if).

Using multiple if statement:

t = int(input("Give t a number "))
k = int(input("Give k a number "))

if t > k:
    print("t is greater than k")
if t < k:
    print("t is less than k")
if t == k:
    print("t is equal to k")

In the above example we prompt the user to provide a number for t and k .

we convert the users input to an integer using int() because input() always gives a string.

After this, the computer will look at the first if statement and check if it is true or false. It then checks the second if statement, the third and so on, depending on how many conditions you have, even though the previous condition maybes true.

This will give you the same results, but it is not really effective because of the unnecessary evaluation which may impact performance.

Before looking at some examples here is the syntax for using elif:

if condition A:
    # perform this task
elif condition B:
    # perform this task instead
else:
    # do this instead

In the above syntax, both condition A and B are Boolean expressions (true or false). If condition A is false, then the interpreter skips that task and checks the elif block. If condition B is true then the task in the elif indented block is performed.

If condition B is false, then it means all the conditions are false and the else block is executed.

Example:

t = int(input("Give t a number "))
k = int(input("Give k a number "))

if t > k:
    print("t is greater than k")
elif t < k:
    print("t is less than k")
elif t == k:
    print("t is equal to k")

With the elif, the computer first checks if the if condition (t > k) is true or false. If it is true, then the following elif statements will not be evaluated. If the condition is false then the first elif condition is evaluated, if it is true then the task under it is performed and the second elif condition is not evaluated and so on. This makes it more effective.

Loops

Loops in Python allow you to repeatedly execute a block of code, making it easier to perform repetitive tasks and iterate over data structures.

There are two loops that python uses: the for and while loop.

For Loop

We use the for loop to iterate over a sequence, could be a list, tuple or string. This executes the same block of code for each item in the sequence.

Syntax:

for variable in sequence:
    # perform this task
  • Variable -> This is a temporally variable that holds each element of the sequence.

  • Sequence -> This is whatever we are iterating over. Could be a list, tuple etc

Let us look at an example:

animals = ["Lion", "Elephant", "Whale", "Cat"]

for animal in animals:
    print(animal, "is an animal")
output:
Lion is an animal
Elephant is an animal
Whale is an animal
Cat is an animal

In the above example, we have a list of animal names. The loop goes through the animals list as it prints the animal together with the statement is an animal.

While loop

In contrast to the predetermined iterations of a for loop, the while loop focuses on continuous execution of a code block as long as a specific condition remains true. This makes it ideal for situations where the number of iterations is unknown beforehand or depends on external factors.

Syntax:

while condition:
  # Execute this task

Once the condition becomes false then the loop is terminated or rather we exit the loop.

Let's look at an example:

count = 0

while count < 3:
    print("I love Python")

    count = count + 1

In this example, we initialize a variable count and give it a value of 0. The interpreter looks at the while condition to check if count, whose value is 0, is less than 3. In this case 0 is indeed less than 3 so I love Python is printed and our count is incremented by 1.

The interpreter will go through the loop again with the value of our count now being 1 instead of 0. It checks the loops condition and 1 is indeed less than 3 so it will print I love Python and increment our count value by 1 making it 2. It goes through the loop again checking if 2 is less than 3. The condition is true so I love Python will be printed and count now becomes 3.

The interpreter checks the condition again, is 3 less than 3? No! So, the condition becomes false, and we break out of the loop. This becomes our output:

Output
I love Python
I love Python
I love Python

The match statement

The match statement is used to utilize patterns to match an expression with a value.

match expresion:
    case pattern A:
        # If pattern A matches execute this code
    case pattern B:
        # If pattern A matches execute this code
    case ...:
        # ...
    case _:
        # If no patterns matches, execute this code

It takes the expression (what we are evaluating) and compares its value to the patterns provided withing the case. If the value matches the pattern, then the code withing the case indented block is executed.

Check this example:

instrument = input("What instrument do you like to play? ")
match instrument:
    case "piano":
        print("I love playing piano")
    case "violin":
        print("I love playing violin")
    case "drums":
        print("I love playing drums")
    case "cello":
        print("I love playing cello")
    case -:
        print("What's that?")

In the above example, we prompt the user to type what instrument they like to play. If the users input matches any of the case, then whatever is under the indented matched case is printed.

Output:
What instrument do you like to play? piano
I love playing piano

Please note that the match statement may not work with some versions since it was introduced in python 3.q0

Using break and continue statements

If you want to exit a loop prematurely then the break statement comes in handy. When a break statement is encountered within the loop, it immediately terminates the loop, and the program goes to the next statement after the loop.

for t in range(7):
    if t == 4:
        break
    print(t)

This code will print 0 to 3. When t is equal to 4, the break statement terminates the program.

The continue statement skips specific iterations when certain conditions are met.

for t in range(7:
    if t == 4:
        continue
    print(t)

This code prints 0 to 6 but skips 4 when t is equal to 4 because of the continue statement.

Conclusion

In conclusion, control flow is a fundamental aspect of programming that dictates the order in which instructions are executed

Whether it's handling multiple conditions or iterating over sequences, mastering control flow empowers programmers to create efficient, and logically structured code. As you continue your programming journey, exploring these control flow concepts and incorporating them into your coding will undoubtedly contribute to your growth as a Python developer.

Happy coding!