In programming, the term flow control refers to the order in which statements run in your program. Normally, statements will run from top to bottom, in the order they appear in your source code. This order can be changed from the natural sequence using flow control statements. In this lesson, we will focus on conditional (also called selection) flow control statements.

The "if" Statement
The "if" conditional statement performs different actions based on whether a logical expression evaluates to True or False. The format for an "if" statement in code looks something like this:

if <logical expression>:
# this code executes if the logical expression is true
Copy
The "if" keyword is followed by a logical expression and then a colon (:). The logical expression can be very simple or very complicated, but it must evaluate to either True or False. If the logical expression is True, the code indented below the "if" statement is executed. If the expression is False, the code indented below the "if" statement is skipped, and the program continues on the next line that is not indented.

Let's give this a try with a simple example. The code below will get an input value from the user and immediately convert it to an integer data type. The resulting answer variable is compared to 5 inside an "if" statement. If the value is greater than 5, a message will be printed on the screen. When the "if" statement ends, a final print() statement will run, regardless of the results of the "if" statement.

Try It Now


Try running the code above two times. First, enter a value less than 5. Then, run it again and enter a value greater than 5. Did you see the expected printed output in each case?

The Importance of Indentation in Python
Many programming languages like C# and Java will use curly braces { } or other symbols to mark the start and end of statements that belong together. Python, however, does things a bit differently. To mark a block of code in Python, you simply indent each line in the block with the same amount of spaces.

This indentation is very important for "if" statements! If the logical expression is true, Python will run every indented line of code that follows the "if" statement. If the statement is false, Python will jump down to the first un-indented line after the "if" statement, skipping all the indented lines.

Let's extend our example by indenting multiple statements underneath the "if" line. Now, when the logical expression is True, all those statements should run. If the expression is False, they will all be skipped. Try it and see!

Try It Now


When indenting several statements to form a block of code, be sure to use exactly the same number of spaces each time. Many programmers use a standard of three or four spaces to indent code blocks, but the number is really up to you. Just make sure to be consistent in your programs.
Multiple "if" Statements
You can use as many "if" statements in your program as you like. As long as each is indented at the same level (or aligned to the left side), they will all work independently of one another. In the example below, we use three different "if" statements to test the value of a score variable, printing different statements each time. Every one of these "if" statements will run, test the logical expression, and execute or skip the indented block of code that follows each statement.

Try It Now


What happens when you run with score = 60? Only the first "if" statement has a True logical expression, so you will just see "Try harder!" in the output. Try changing score to 80 and run the code again. Do you get the expected results? What happens if you set score = 95? Remember that all "if" statements are running independently. So, a score of 95 will produce a True expression in both the second and third "if" statements, and you should see both printed output statements for that value.

The "if", "elif", "else" Statements
The examples above demonstrate multiple "if" statements that are independent. Each has a logical expression that will be tested, regardless of what happens in other "if" statements. However, it is possible to write a series of tests that will only run if the previous logical expression was False.

After an "if" statement, you can add one or more "elif" statements that will run if the previous "if" or "elif" test returned False. "elif" is short for "else if". In addition, you can add a final "else" statement that will always run if all the previous tests returned False.

So, in plain language, you can write code that says "if (something is true), else if (something else is true), else if (something else is true), else (do something when all prior tests return false)". An outline of the Python code is shown below.

if <1st logical expression>:
# this code executes if the 1st logical expression is true
elif <2nd logical expression>:
# this code executes if the 1st logical expression is false
# AND if the 2nd logical expression is true
else:
# this code executes if all the above expressions are false
# the next un-indented line will always run, independent of the if / elif / else chain above
Copy
This example shows a series of decision-making statements. If the first logical expression is True, the indented code block will run. Once the first indented block is executed, the program skips the remaining "elif" and "else" statements completely and continues the program at the next un-indented line.

If the first logical expression is False, the program will drop down and test the second logical expression on the "elif" line. If this second expression is True, the second indented block of code will run. Once this block is finished, the program will skip any remaining "elif" and "else" statements and continue at the next un-indented line.

If both of the first two logical expressions are False, the program will enter the last else statement. This statement is a catch-all that will run a block of code if no other expression in the if/elif chain has evaluated to true. Once this set of statements has executed, the program will continue at the next un-indented line in the program.

Let's re-write our score example to use an if / elif / else chain of logic.

Try It Now


Try running this example 3 times, changing the score from 60 to 80 to 85. Do you now get just a single output statement in each case? A score of 95 will produce False in the first two logical expressions, so the "else" section will run to print "You rock!".

Once you start an "if" statement, you may follow it with any number (0 or more) "elif" expressions. The final "else" is optional as well.
Nested "if" Statements
You are allowed to write any kind of code inside the body of an if, elif, or else block - including other if chains of logic! When one block of code is placed inside another, the inner block is said to be nested.

Take a look at the sample program below. The second if statement is nested inside the body of the first if statement. It will only be considered if the program flow has already checked the first if expression, found it to be true, and began executing the body of the first if.

With a starting moviePrice of 13.50, which printed output statements would you see? What would be printed if your starting moviePrice was 9.50 or 15.00?

Try It Now


Keeping "==" and "=" Straight
When writing logical expressions, it's easy to confuse the assignment operator (=) with the equal to operator (==). The single equals sign is used in assignment statements to store a new value in a variable. The double equals sign is used in logical expressions to test two values for equality.

What happens if you accidentally use a single equals sign in a logical expression? Let's explore the following example.

Try It Now


At a quick glance, you might expect to see "Mystery remains" in the output, because the mystery variable is equal to 2, not 1. What happens when you run this code? Python will display an error message because you have not written a valid logical expression. "mystery = 1" is an assignment statement, not a logical expression! You can fix the code by changing the single equals sign (=) to a double equals sign (==) and re-running the example.

Be sure to double-check the logical expressions in your if/elif statements. One incorrect character can make all the difference in the world, resulting in strange error messages or unexpected behavior when the program runs.

1. What is flow control? Why might this concept be important in a program?
2. What statement is used to run a block of code when a logical expression is true? How do you format this statement?
3. What is the purpose of indenting statements following an "if" statement?
4. What is an elif statement and when does it execute?
5. What is an else statement and when does it execute?
6. What is the difference between = and ==, and when should each be used?

1. Flow control refers to the order in which statements run in a program. This concept is important in a program because it allows for different actions to be taken based on specific conditions, enabling the program to make decisions and respond accordingly.

2. The "if" statement is used to run a block of code when a logical expression is true. It is formatted with the keyword "if", followed by the logical expression, followed by a colon (:), and then an indented block of code.

3. Indenting statements following an "if" statement is important because it visually groups the indented statements together as a block of code that will only be executed if the logical expression in the "if" statement evaluates to true. The indentation is used to indicate the scope or extent of the code block.

4. An "elif" statement is used in an if/elif/else chain and it executes when the previous "if" or "elif" statements in the chain have returned false and its own logical expression evaluates to true. It is short for "else if" and allows for additional conditions to be tested.

5. An "else" statement is also used in an if/elif/else chain and it executes when all the previous "if" and "elif" statements in the chain have returned false. It provides a default or catch-all option for when none of the conditions in the chain are met.

6. The "=" operator is used for assignment, where it assigns a value to a variable. For example, x = 5 assigns the value 5 to the variable x. On the other hand, the "==" operator is used to compare two values for equality. For example, x == 5 is a logical expression that checks if the value of x is equal to 5. It is important to use the correct operator in logical expressions to ensure they function as intended.