A control structure is a logical design that controls the order in which a set of statements executes. So far, all of our programs have used the simplest type of control structure called the sequence structure. A sequence structure is a set of statements that execute in the order that they appear; that is, from top to bottom.
The sequence structure is extremely important, but it’s not enough. Programs written using only the sequence structure are very predictable because they always execute the same statements in the same order. But to execute a set of statements only under certain circumstances we require another program control structure called the decision structure (sometimes called selection structure).
In the simplest form of decision structure, a set of statements is only executed if a certain condition is True, or skipped entirely if the condition is False.
The if Statement
In Python, the if statement is used to implement decision structures. Here’s the Python syntax:
The if statement begins with the keyword if followed by some condition which is an expression that must evaluate to either True or False. If the result of the condition is True, then the indented block of code following the colon (:) is executed, otherwise the statements in the block are skipped. This condition is referred to as a Boolean expression, named in honour of the English mathematician George Boole. In the 1800s Boole invented a system of mathematics in which the abstract concepts of true and false could be used in computations.
To create a condition, relational operators are used to compare two values and produce a True or False result. Python supports 6 relational operators:
The relational operators above are pretty self-explanatory and are actually used in other modern languages like Java and C++. I’ll just mention a few things to be mindful of.
First, be careful with the >= and <= operators, you cannot put a space between the symbols or swap them; that is, => and =< are not valid relational operators.
Also note that the equality operator (==) is made up of two equal signs, not one. A single equal sign (=) is used for assignment in Python, and the double equal sign (==) is used for comparison. If you confuse these two operators you can cause logic errors that can be very hard to spot!
Finally, you can use these operators to compare strings alphabetically but keep in mind that Python is case sensitive, so the strings “Example” and “example” are not considered to be equal. Recall that strings are stored as ASCII values (A-Z are codes 65-90, a-z are codes 97-122, 0-9 are codes 48-57, and a blank space is 32). When Python compares two strings it is actually comparing the ASCII values of the characters in each string.
Ok, let’s put all of this together with a few example if statements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
score = int(input("Enter your score: ")) if score == 0: print("Wow, you need to practice!") if score >= 1000000: print("Wow, you must be Vik-20!") name = "Mark" if name > "Mary": print(name, "comes after Mary.") if name < "Mary": print(name, "comes before Mary.") |
The if..else Statement
Often we need a decision structure that executes one block of code if a condition is True, or a different block of code if a condition is False. To do this we use an if..else statement in Python:
Here if the condition is True, the first block of code runs, then execution continues at the statement following the if..else statement. In this case, the second block of code, following the else keyword, is skipped.
If the condition is False, then the first block of code is skipped, and the second block of code runs instead. Execution then continues at the statement following the if..else statement.
Here’s an example:
1 2 3 4 5 6 7 8 |
score = int(input("Enter your score: ")) if score > 5000: print("Good work. ", end="") else: print("You need to practice more. ", end="") print("Good luck next time!") |
Nested Decision Structures
It’s possible to nest decision structures inside other decision structures:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
score = int(input('Enter your test score: ')) # Determine the grade. if score < 60: print('Your grade is F.') else: if score < 70: print('Your grade is D.') else: if score < 80: print('Your grade is C.') else: if score < 90: print('Your grade is B.') else: print('Your grade is A.') print("Good luck next time!") |
Notice how important it is to use proper indentation when nesting decision structures. Not only does this make your code more readable, but also it’s required by the Python interpreter. Make sure that each else is aligned with its matching if. Incorrect indentation can cause hard to find logic errors.
The if..elif..else Statement
Sometimes we need a decision structure with a series of conditions to check, performing a different set of statements depending on which condition is True. In Python we use an if..elif..else statement to accomplish this:
In this case, if condition_1 is True the first block of code is run, the rest of the structure is ignored, and execution continues at the statement following the if..elif..else statement. If condition_1 is False, then condition_2 is checked. If condition_2 is True the second block of code is run, the rest of the structure is ignored, and execution continues at the statement following the if..elif..else statement. This process continues until there are no more elif clauses to check. If none of the conditions is True, then the block of code following the else clause is executed.
Here’s an example that gives the same output as the previous nested if..else example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
score = int(input('Enter your test score: ')) # Determine the grade. if score < 60: print('Your grade is F.') elif score < 70: print('Your grade is D.') elif score < 80: print('Your grade is C.') elif score < 90: print('Your grade is B.') else: print('Your grade is A.') print("Good luck next time!") |
Notice the alignment and indentation here. All elif and else keywords are aligned and the conditionally executed blocks are indented. If you compare this example with the previous one, I think you’ll agree that the logic of an if..elif..else statement is easier to follow than a long series of nested if..else statements.
Finally, as with an if..else statement, the else clause is optional in an if..elif..else statement — you can leave it out if you don’t need it.
You Try!
-
- Start a new page in your Learning Journal titled “2-1 Decision Structures“. Carefully read the notes above and in your own words summarize the key ideas from each section. Think of it as writing a “cheat sheet” for this lesson. Making these notes will help solidify your understanding of the material and serve as a future reference to help you review key concepts.
- Try to figure out what this code will display, then check your hypothesis using the Python interpreter.
1234if 'z' < 'a':print('z is less than a')else:print('z is not less than a')
- Convert the following code to an if..elif..else statement:
12345678910if number == 1:print('One')else:if number == 2:print('Two')else:if number == 3:print('Three')else:print('Unknown')