Python en:Control Flow

Introduction
In the programs we have seen till now, there has always been a series of statements and Python faithfully executes them in the same order. What if you wanted to change the flow of how it works? For example, you want the program to take some decisions and do different things depending on different situations such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?

As you might have guessed, this is achieved using control flow statements. There are three control flow statements in Python - if, for and while.

The if statement
The if statement is used to check a condition and if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional.

Example:

Output:

$ python if.py   Enter an integer : 50 No, it is a little lower than that Done $ python if.py   Enter an integer : 22 No, it is a little higher than that Done $ python if.py   Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) Done

How It Works:

In this program, we take guesses from the user and check if it is the number that we have. We set the variable number to any integer we want, say 23. Then, we take the user's guess using the input function. Functions are just reusable pieces of programs. We'll read more about them in the next chapter.

We supply a string to the built-in input function which prints it to the screen and waits for input from the user. Once we enter something and press enter</tt> key, the input</tt> function returns what we entered, as a string. We then convert this string to an integer using int</tt> and then store it in the variable guess</tt>. Actually, the int</tt> is a class but all you need to know right now is that you can use it to convert a string to an integer (assuming the string contains a valid integer in the text).

Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. This is why indentation is so important in Python. I hope you are sticking to the "consistent indentation" rule. Are you?

Notice how the if</tt> statement contains a colon at the end - we are indicating to Python that a block of statements follows.

Then, we check if the guess is less than the number, and if so, we inform the user to guess a little higher than that. What we have used here is the elif</tt> clause which actually combines two related if else-if else</tt> statements into one combined if-elif-else</tt> statement. This makes the program easier and reduces the amount of indentation required.

The elif</tt> and else</tt> statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with proper indentation, of course)

You can have another if</tt> statement inside the if-block of an if</tt> statement and so on - this is called a nested if</tt> statement.

Remember that the elif</tt> and else</tt> parts are optional. A minimal valid <tt>if</tt> statement is:

After Python has finished executing the complete <tt>if</tt> statement along with the associated <tt>elif</tt> and <tt>else</tt> clauses, it moves on to the next statement in the block containing the <tt>if</tt> statement. In this case, it is the main block where execution of the program starts and the next statement is the <tt>print('Done')</tt> statement. After this, Python sees the ends of the program and simply finishes up.

Although this is a very simple program, I have been pointing out a lot of things that you should notice even in this simple program. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds) and requires you to become aware of all these initially, but after that, you will become comfortable with it and it'll feel 'natural' to you.


 * Note for C/C++ Programmers
 * There is no <tt>switch</tt> statement in Python. You can use an <tt>if..elif..else</tt> statement to do the same thing (and in some cases, use a dictionary to do it quickly)

The while Statement
The <tt>while</tt> statement allows you to repeatedly execute a block of statements as long as a condition is true. A <tt>while</tt> statement is an example of what is called a looping statement. A <tt>while</tt> statement can have an optional <tt>else</tt> clause.

Example:

Output:

$ python while.py   Enter an integer : 50 No, it is a little lower than that. Enter an integer : 22 No, it is a little higher than that. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. Done

How It Works:

In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly run the program for each guess, as we have done in the previous section. This aptly demonstrates the use of the <tt>while</tt> statement.

We move the <tt>input</tt> and <tt>if</tt> statements to inside the <tt>while</tt> loop and set the variable <tt>running</tt> to <tt>True</tt> before the while loop. First, we check if the variable <tt>running</tt> is <tt>True</tt> and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the <tt>running</tt> variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.

The <tt>else</tt> block is executed when the <tt>while</tt> loop condition becomes <tt>False</tt> - this may even be the first time that the condition is checked. If there is an <tt>else</tt> clause for a <tt>while</tt> loop, it is always executed unless you break out of the loop with a <tt>break</tt> statement.

The <tt>True</tt> and <tt>False</tt> are called Boolean types and you can consider them to be equivalent to the value <tt>1</tt> and <tt>0</tt> respectively.


 * Note for C/C++ Programmers
 * Remember that you can have an <tt>else</tt> clause for the <tt>while</tt> loop.

The for loop
The <tt>for..in</tt> statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. We will see more about sequences in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.

Example:

Output:

$ python for.py   1 2   3    4    The for loop is over

How It Works:

In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in <tt>range</tt> function.

What we do here is supply it two numbers and <tt>range</tt> returns a sequence of numbers starting from the first number and up to the second number. For example, <tt>range(1,5)</tt> gives the sequence <tt>[1, 2, 3, 4]</tt>. By default, <tt>range</tt> takes a step count of 1. If we supply a third number to <tt>range</tt>, then that becomes the step count. For example, <tt>range(1,5,2)</tt> gives <tt>[1,3]</tt>. Remember that the range extends up to the second number i.e. it does not include the second number.

The <tt>for</tt> loop then iterates over this range - <tt>for i in range(1,5)</tt> is equivalent to <tt>for i in [1, 2, 3, 4]</tt> which is like assigning each number (or object) in the sequence to i, one at a time, and then executing the block of statements for each value of <tt>i</tt>. In this case, we just print the value in the block of statements.

Remember that the <tt>else</tt> part is optional. When included, it is always executed once after the <tt>for</tt> loop is over unless a break statement is encountered.

Remember that the <tt>for..in</tt> loop works for any sequence. Here, we have a list of numbers generated by the built-in <tt>range</tt> function, but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters.


 * Note for C/C++/Java/C# Programmers
 * The Python <tt>for</tt> loop is radically different from the C/C++ <tt>for</tt> loop. C# programmers will note that the <tt>for</tt> loop in Python is similar to the <tt>foreach</tt> loop in C#. Java programmers will note that the same is similar to <tt>for (int i : IntArray)</tt> in Java 1.5.
 * In C/C++, if you want to write <tt>for (int i = 0; i &lt; 5; i++)</tt>, then in Python you write just <tt>for i in range(0,5)</tt>. As you can see, the <tt>for</tt> loop is simpler, more expressive and less error prone in Python.

The break Statement
The <tt>break</tt> statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become <tt>False</tt> or the sequence of items has been completely iterated over.

An important note is that if you break out of a <tt>for</tt> or <tt>while</tt> loop, any corresponding loop <tt>else</tt> block is not executed.

Example:

Output:

$ python break.py   Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 21 Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something :      use Python! Length of the string is 12 Enter something : quit Done

How It Works:

In this program, we repeatedly take the user's input and print the length of each input each time. We are providing a special condition to stop the program by checking if the user input is <tt>'quit'</tt>. We stop the program by breaking out of the loop and reach the end of the program.

The length of the input string can be found out using the built-in <tt>len</tt> function.

Remember that the <tt>break</tt> statement can be used with the <tt>for</tt> loop as well.

Swaroop's Poetic Python
The input I have used here is a mini poem I have written called Swaroop's Poetic Python:

Programming is fun When the work is done if you wanna make your work also fun: use Python!

The continue Statement
The <tt>continue</tt> statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.

Example:

Output:

$ python test.py   Enter something : a    Too small Enter something : 12 Too small Enter something : abc Input is of sufficient length Enter something : quit

How It Works:

In this program, we accept input from the user, but we process them only if they are at least 3 characters long. So, we use the built-in <tt>len</tt> function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the <tt>continue</tt> statement. Otherwise, the rest of the statements in the loop are executed and we can do any kind of processing we want to do here.

Note that the <tt>continue</tt> statement works with the <tt>for</tt> loop as well.

Summary
We have seen how to use the three control flow statements - <tt>if</tt>, <tt>while</tt> and <tt>for</tt> along with their associated <tt>break</tt> and <tt>continue</tt> statements. These are some of the most often used parts of Python and hence, becoming comfortable with them is essential.

Next, we will see how to create and use functions.

Previous Next