Python:Selective Structures

From PrattWiki
Jump to navigation Jump to search

Note: This page is very much based on MATLAB:Selective Structures

Often in solving engineering problems you will have to make choices based on a set of input parameters or calculations. For example, if you are writing a program that has any kind of menu, you will need to have some kind of programming structure that will perform one of several possible functions based on user input. You may also have equations that are only relevant over a certain range of inputs and need to have a programming structure in place that will let the user know if he or she is trying to use a function for invalid inputs.

Logical and Relational Operators

There are two kinds of operator you need to learn in order to properly use selective structures. These are the relational operators (which compare two items) and the logical operators (which link or invert relational operators). Note especially that the "is equal to" relational operator is formed using two equals signs in a row.

The output from a relational operator will either be True False. The same is true for logical operators. Note that operator precedence is very important with respect to relational and logical operators; using parentheses to clearly establish priority will save you a great deal of time in debugging code.

if Structures

The most commonly used selective structure is the if...elif...else... structure. Every structure of this type at least starts with an if statement and uses indentation to determine what code is "owned" by a branch.

Single option: if

For example, if you have code that is determining whether someone can see an R-rated film by themselves, you may want to take that person's age, compare it to the required age using a relational operator, and print a statement based on the result of that comparison. That is:

Age = float(input("How old is the person? "))
if Age < 17:
     print("You may not see an R-rated movie alone\n")

You can ask multiple independent questions by using several trees in a series. For example,

Age = float(input("How old is the person? "))
if Age < 17:
     print("You may not see an R-rated movie alone\n")

if Age < 13:
     print("You should not see a PG 13-rated movie alone\n")

If Age is 17 or greater, the first tree will not run and the second tree will not run. If Age is less than 17 but 13 or larger, the first tree will run and the second one will not. If Age is less than 13, the first tree will run as will the second. Note, however, that these trees are independent of each other - both relational operators will be evaluated regardless of the outcome of either of them.

Default case: if...else...

Another version of an if tree involves an "either-or" choice - either the logic is true and the first set of code will run or else the second block of code will run. For example, if you want to know if a person is old enough to legally vote in North Carolina - either they are 18 or over and they can or else they cannot. The decision tree for this might be:

Age = float(input("How old is the person? "))
if Age >= 18:
     print("You may vote!\n")
     print("Be sure to register!!\n")
else:
     print("Can't vote yet...\n")
     print("Alas...\n")

Python will definitely run one of the two branches of this code - the first one if the person is 18 or older, and the second one if not.


Mutually Exclusive Options: if...elif...elif...else...

Sometimes, there will be several mutually exclusive options within your program. For these times you can use one or more elif statements and possibly a closing else statement. Your program will look at the initial if statement, and if its controlling logic is False then it will start looking at the logic for successive elif statements until

  1. it finds one that is True, or
  2. it finds an else statement

Once the logic in some part of the structure is found to be True, or an else statement is found, whatever code is inside that particular statement is run and then the whole if...elif...else structure is finished - Python skips over any remaining elif statements or an else statement if there is one. Look at the following example:

if Age < 17
     fprintf('You may not see an R rated movie alone\n');
     fprintf('You may not see an NC-17 rated movie\n');
elseif Age == 17
     fprintf('You may see an R rated movie alone\n');
     fprintf('You may not see an NC-17 rated movie\n');
else
     fprintf('You may see R and NC-17 rated movies\n');
end

Nested Decision Trees

Another more complex way of using selective structures is by nesting them. You can put selective structures within one another in order to refine the selection process based on different variables. For example, first-year Duke students can go to the Math Department's page on Placement Information for First-Year Students[1] to get guidance as to what math course to take. There are several variables that enter into the placement algorithm. A possible selective structure for determining mathematics placement based purely on AP scores might be:

APtest = input("Did you take AP Calculus? (y or n): ")
if APtest == "y":
     AB = int(input("What was your AB score? (0 if not taken): "))
     BC = int(input("What was your BC score? (0 if not taken): "))
     if BC==5:
          print("You receive credit for MTH 21 and MTH 22.\n")
     elif BC==4 or AB==5:
          print("You receive credit for MTH 21.\n")
     else:
         print("No credit based on AP scores.\n")
         print("See SFI for more information.\n")
else:
     print("See the SFI for placement information.\n")

Note the use of both nested selective structures and the use of compound relational operators (that is, relational operators joined by the logical statement "or"). The indentation level is the mechanism by which Python can figure out when one branch ends and another one begins.

Asking Multiple Questions

When selective structure process logic, the logical questions may have more than one entry. In these cases, you must explicitly tell Python if the expression should be considered true if any of the items are true or if all of the items are true. For example:

import numpy as np
n = 1
a = np.array([1, 2, 3, 4, 5])*n

if all(a>1):
     print("All entries of a are more than one\n")
elif any(a>1):
     print("At least on entry in a is more than 1")
else:
     print("No entry in a is more than 1")

will end up stating At least on entry in a is more than 1. If you want to see a different result, change n to 2 such that all the entries in a are larger than 1 or change n to 0.1 so all the entries are less than 1.

Note that the if tree will not loop through each of the five entries but rather is asking all five questions simultaneously and reacting to the five questions at once. If you want to get different answers for each element, you will need to either run a loop or use a logical mask.

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References

  1. Placement Guidelines - Duke Math Department