Ever wanted to execute a piece of code only if some condition is true? Ever desired of executing a piece of code over and over again, automatically?

What you're willing for is in short controlling the flow of execution of a program and this is all what this chapter is about. In this chapter, we'll learn how to execute code based on some condition using if and else. Moreover, we'll see how to execute a given piece of code over and over again using the for and while loop.

The if statement

To execute a piece of code upon the fulfillment of a given condition, we use the if statement.

Here's the syntax of the if statement:

if condition:
    # code to execute if condition is True

First comes the if keyword and then the condition that must evaluate to True in order for the body of if to be executed.

This is one application of Boolean values. If a given value is True, the if's body executes, however if it's False, then the if's body is ignored.

Let's consider a very simple example.

Suppose we want to print "Don't forget the umbrella" if it's a rainy day today. A variable, specifically a Boolean variable, named is_rainy_day can be defined to specify whether or not it is a rainy day today.

If it's equal to True, then it's a rainy day; otherwise it's not a rainy day.

Based on this variable, we can output the given string "Don't forget the umbrella", using the if statement, as shown below:

if is_rainy_day:
    print("Don't forget the umbrella")

This type of execution of a block of code is known as conditional execution, since a condition governs the execution of the code.

Note that this example is not completely fictitious. It can be part of a weather application that informs us when it's a rainy day in our respective city, and suggests us to go out with an umbrella.

In short, if statements are extremely useful in practical level, day-to-day, applications

Let's consider another example. In the chapter, we saw comparison operators, in particular the ==, >= and <= operators. We'll use the equality operator to compare two values in our program to govern what gets output in the end.

Suppose our program asks users to enter their gender. 'M' is for male, and 'F' is for female. To deduce what the user entered we can use an if statement, checking whether the value input is equal to 'M' or not, and then act accordingly:

gender = input("What's your gender? M for male, and F for female.")

if gender == 'M':
    print("You're a male programmer!")

Here first we save the input sent by the user in the variable gender, and then check whether it's equal to 'M'. If it is, a message is printed saying that you're a male programmer.

The use cases of if are endless — it's not something we would use very rarely — rather it's a highly common statement used in nearly every kind of program. In the chapters following, we'll be using the if statement a lot, so make sure you understand this really well.

The else statement

Sometimes, as we've seen above, we want to execute a piece of code upon the fulfillment of a given condition. Equally, sometimes we also want to do something if that condition isn't fulfilled.

This is where the else statement comes in. Below shown is the syntax of else in Python:

if condition:
    # code to execute if condition is True
    # code to execute if condition is False

The else statement is not a standalone statement. It's a continuation of a preceding if statement.

Explaining the syntax shown above, first comes the else keyword and then its block of code. Note that the if and else keywords here are at the same level of indentation because they are in the same block of code i.e the main script.

This will always be the case for contiguous if...else statements. It's only anything within their blocks that goes at the next level of indentation. Failing to do so results in syntax errors.

Whenever a statement ends with a colon in Python, the block of code following it is considered part of the statement and expected to be at the next level of indentation.

Let's extend our previous program to print another message if the user enters something other than 'M'.

If gender is equal 'M', we print "You're a male programmer.", as before. However, if gender is not equal to 'M', in that case we print "You're not a male programmer.".

Once you start coding pratical-level programs, you'll notice that when an if statement is used, an else statement is also required, in most of the cases. We'll consider many such cases in the Python Flow Control — Conditional Statements chapter.

The for loop

Looping, or iteration, is the key to computer automation. It is when a computer executes some piece of code over and over again until some termination point is reached.

In Python, we have two statements that enable iteration: for and while. In this section, we shall explore for on the outskirts, before moving over to while in the next section.

The for loop is meant to iterate over a sequence of values. Recall any sequence types from the Python Data Types chapter? Strings and lists are one of many sequence types in Python.

The for loop can be used to iterate over these types of values.

Here's the general syntax of Python's for loop:

for item in sequence:
    # code to execute repeatedly,
    # for each item in sequence

It all starts by the for keyword. Then comes the name of a variable to hold each item of sequence during each iteration. This is followed by the in keyword and lastly the sequence to iterate over.

The body of the for loop represents code that'll be executed for each item in the given sequence.

Now, it's time to understand how all this works together.

Let's suppose that we want to go over the list [1, 3, 5] and print each number. We would write the following code to accomplish this:

nums = [1, 3, 5]

for num in nums:

Here's how this code works:

  1. When the for loop begins, the first item of the list nums is put inside the variable num. This variable is just like any other variable in Python, and thereby, is accessible within the loop's body. The loop's body gets executed for the first time, and prints 1.
  2. The loop's body completes and execution shifts back to the header of the loop. Now, the second item of the list nums is put inside the variable num, passing execution back to the body of the loop.
  3. On this second iteration, print(num) gets executed and as a result 3 gets printed.
  4. The loop's body completes, once more, and so execution shifts back to the header of the loop. Now the variable num is assigned the third item of nums, before passing execution to the body of the loop.
  5. On this third iteration, print(num) gets executed, and consequently 5 is printed.
  6. Execution comes back to the loop's header, where this time it's noted that the list nums has been exhausted i.e all its elements have been iterated over. As a result, the for loop exits and execution shifts out of the loop, to the next statement after the whole loop.

This is how for works under the hood. It keeps on iterating until the end of the sequence is reached.

We know that a string is also a sequence data type. Specifically, it's a sequence of characters. Let's see how Python dissects a string when used in the for loop:

msg = 'Hello'
for char in msg:

As expected, each iteration of the loop deals with each character of the string msg.

Working with for is quite an interesting thing, and in fact, a common concern of many computer algorithms implemented in Python. We'll discover this in detail in the Python Flow Control unit.

The while loop

Another way to iterate in Python is using the while loop.

It behaves a bit differently than for, with a different syntax; nonetheless, it's still very easy to get the hang of just like for.

Below shown is the syntax of while:

while condition:
    # code to execute while condition is True

The while loop's body keeps on executing as long as the given condition remains True. It only terminates when the given condition becomes False.

The while loop resembles English language particularly well — 'while this condition is true, keep on doing this...'

Once execution enters the while loop, it can only get out of there if the value of the condition put in the loop's header becomes equal to False during the execution of the loop.

Let's take a very simple example.

We'll print the first 5 non-negative integers using while. The idea is that we'll begin at 0 and keep on iterating until the number becomes 6, at which point our loop stops execution.

num = 0

# keep iterating while num is lesser than 5
while num < 5:
    num += 1

First num is set to 0 — the number at which we wish to start our sequence of numbers.

Then comes the while loop. The condition here is num < 5 which merely means that continue execution if num is lesser than 5.

In the first iteration, num = 0 is indeed lesser than 5, and so 0 is printed. After this, num is incremented by 1 which updates it to 1.

The second iteration begins. num < 5 is evaluated and it returns True, since num = 1 is lesser than 5. This goes on until we reach 5.

At this point, the condition num < 5 is evaluated. It returns False, and likewise execution jumps out of the while loop.

What we get altogether is the following output:


Notice line 4 in the code above. It's crucial to the behavior and termination of the while loop. If we remove it, num would always remain equal to 0, and therefore num < 5 would always evaluate to True, leading to what's known as an infinite loop — a loop that never ends!

Infinite loops are commonly witnessed as beginners construct while loops in Python — even the pros out there can end up writing infinite loops — since setting them can involve a lot of details, and where there are details, there are errors.

Debugging infinite loops is a painful task especially if the loop works around many values in a complicated manner. We'll learn more about debugging later on in this course.