Python Intermediate #7 - Overview of IF Statements

In previous posts, we used "if" statements to accomplish our objectives.  This post will serve as an overview on the use of "if" statements.

In the example below, we set the value of x equal to 5.  We then use "if" (and "elif") statements to determine if x is greater than 10, greater than 7, or greater than 1.  Python will go through the "if" statements sequentially.  You can see below that the first statement in the sequence is an "if" statement.  Subsequent statements use "elif", which is shorthand for else if.



The output from running the program is shown below.


If we set the value of x equal to zero, then none of the "if" or "elif" statements apply.  For the code below, the programs returns nothing.


To offset the program returning nothing, we can add an else statement that returns a message in the event that none of the "if" or "elif" statements apply.  The "else" statement has been added in the figure below.


The results of the program are shown below.  We can see that the "else" statement has been applied since none of the "if" or "elif" statements were true.



In the next example, "if" statements have been nested to test two conditions.  A color is tested along with a value for x.  Note that the color is given in quotes to denote that it is a string.  Indentation in Python is important.  The testing of the colors, blue and green, using the "if" and "elif" statements go together along with the final "else" statement.  The testing of the numbers under the color testing for blue and green are only activated if the color is true.  So, if the color is not blue, the first set of indented "if" and "else" is ignored.    


The results of the program are shown below.


Changing the color to red will cause the "if" and "elif" statements testing for blue and green, respectively, to be false.  The indented "if" and "else" statements testing the value of the number are ignored.  Python then defaults to the action given under the final "else" statement.  The result is shown below.


One final point about using "if" statements is the importance of the order that is used when testing numbers.  The program below is using the wrong order for testing the values.  Recall that Python sequentially tests the "if" statements and executes the action associated with the first true "if" or "elif" statement.  In the program below, we are first testing if x is less than 10 before testing if x is less than 5.  Since we set the value of x to 4, Python recognizes that 4 is less than 10 and never tests if x is less than 5. 


The results of the program are shown below.


To fix this, we simply switch the order in the program.


The result is shown below.







Comments