Chapter 4, Lesson 2 Text

Chapter Four: Making Decisions

Lesson Two: The "if" Statement

 

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 flow control statements.

The "if" Statement

The "if" conditional statement performs different actions based on whether a logical expression evaluates to Trueor 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

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 to 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

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 continue 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.

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.


Work With Me: Did You Pass?

 

In this activity, you are going to create an if / elif / else chain of logic that will translate a numeric grade like 95 into a letter grade (A, B, C, D, F). We have already written parts of some statements to get started. It is your responsibility to complete the logical expressions in the first "if" and "elif" statements to detect A and B grades. Then, write additional "elif" and "else" statements to handle the C, D and F cases on your own.

When finished, your program should demonstrate the following general logic:

  • If the numeric grade is greater than or equal to 90, the letter grade is an "A"
  • Else If the numeric grade is greater than or equal to 80, the letter grade is a "B"
  • Else If the numeric grade is greater than or equal to 70, the letter grade is a "C"
  • Else If the numeric grade is greater than or equal to 60, the letter grade is a "D"
  • Else any other numeric grade is an "F"

Try It Now

  

Console

When done, test your program with different myGrade values like 55, 65, 75, 85 and 95, and ensure you get the expected letter grade in each case.

Advanced Challenge: Don't forget, you know how to write an input() statement and convert text input to a numeric value with int(). So, if you don't want to change code each time you test the program, you can enhance the initial myGrade assignment statement to prompt the user for a numeric grade input.

End of Lesson


Last modified: Wednesday, 8 May 2019, 8:16 AM