--- slideOptions: theme: white --- # Chapter 4 - Selection --- ###### tags: `Computer programming` ## Learning objectives By the end of thai chapter, you should able to: 1. Calculate the value of a logical expression 2. Perform different action according to the logical value 3. Perform multiway selection by nested-`if` statement and `elif` statement 4. Implies double entry as one of the method of data verification --- ## Introduction _Selection_ is one of the most important concepts in programming. We can choose between two or more alternatives and hence we can make decisions through selection. The decisions are made based on the Boolean values of the logical expressions. --- ## Logical expression A _logical expression_ is composed by the logical data and logical operators, which combines the logical values and gives out new logical data. --- ### Logical data There are only two values in logical data, namely either `True` or `False`. Boolean (`bool`) is the data type of the logical data. --- ### Logical operators There are three logical operators in Python, namely and, or and not. The truth table of the logical operators are shown as below. ![](https://i.imgur.com/n6Mpm1L.png) --- The logical operators can also be represented by the Venn's diagram, as shown below. ![](https://i.imgur.com/Jn5fHkW.png) --- #### Short-circuit method In Python, it uses the _short-circuit_ method to evaluate the logical expression, as shown below. - `False` and (any expression) → `False` - `True` or (any expression) → `True` The "any expression" will not be evaluated. --- ### Comparative operator The _comparative operator_ also gives out the logical data. They are listed out as shown below. --- | **Type** | **Operator** | **Meaning** | | --- | --- | --- | | Relational | `<` | Less than | | Relational | `<=` | Less than or equal | | Relational | `>` | Greater | | Relational | `>=` | Greater than or equal | | Equality | `==` | Equal | | Equality | `!=` | Not equal | --- ## Two-way selection The _two-way selection_ performs one action or another action depending on the _condition_ which has a Boolean value of either `True` or `False`. --- ### if-else In Python, the two-way selection is implemented by an `if-else` statement. The diagram below shows the logical flow chart and the code in Python to represent the two-way selection structure. --- ![](https://i.imgur.com/Ofkw26P.png) --- Python relies on indentation (normally 4 spaces or 1 tab) to define scope in the code. Other programming languages often use curly-brackets (`{}`) for this purpose. --- The syntactic rules of the if-else statement are listed below. 1. The else statement, including the keyword else, can be omitted if there is no action on that part. ![](https://i.imgur.com/nGb8AH6.png) 2. The expression can be enclosed in parentheses (`()`). 3. Colon (`:`) is added after 1. The express after the `if` statement 2. The keyword `elif` (discussed in the later part) and `else` --- Below shows an example of using two-way selection in Python. ```python!= a = int(input("Enter the number of a: ")) b = int(input("Enter the number of b: ")) if a <= b: print(a, "<=" ,b) else: print(a,">", b) ``` --- <iframe src="https://trinket.io/embed/python3/935f7d621a?start=result" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- #### Simplifying if statement In Python, the control expression can be simplified as shown as below. | **Original statement** | **Simplified statement** | | --- | --- | | `if a == True :` <br/> ` statement`| `if a:` <br/> ` statement` | | `if a == False :` <br/> ` statement` | `if not a:` <br/> ` statement` | The simplified code can usually increase the readability of the code. --- ### Ternary expression (condition expression) Another way to imply the two-way selection is by _ternary expression_, or _conditional expression_. This gives it the following format. ```python! expression1 if expression else expression2 ``` --- ![](https://i.imgur.com/aDhDVOZ.png) --- ## Multiway selection Other than two-way selection, we can have selection on multiple values. There are two ways to implement the _multiway selection_ in Python, namely the nested-`if` statement, the `elif` statement, and `match` statement. --- ### Nested-`if` statement The nested-`if` statement is simply put an `if-else` statement inside an `if-else` statement. Below shows the logic flow and the example code. --- ![](https://i.imgur.com/KkkW7WN.png) --- Note that the else statement will automatically pair up with the `if` statement with the same indentation. ![](https://i.imgur.com/LLBIrtn.png) --- There is no limited level that can be nested. However, if the nested level is more than 3 levels, it is hard to read the code. --- ### `elif` statement Another method to imply the multiway-selection is by `elif` statements. A sample of the `elif` logic design is shown below. --- ![](https://i.imgur.com/6KVikSY.png) --- And here is an example program to print out the grade according to the score. ```python!= score = int(input("Enter the test score (0 - 100): ")) if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print("The grade is:", grade) ``` --- <iframe src="https://trinket.io/embed/python3/ae3b2f3c73?runOption=run&start=result" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ### `match` statement Starting from ***Python 3.10***, there is another type of statement that implies the multiway selection, namely match statement, which can perform different actions with different values. --- ![](https://i.imgur.com/u5YhM3s.png) --- The syntax of the `match` statement is shown below. ![](https://i.imgur.com/8pgyAPY.png) --- Ease `case` statement consists of zero or more statements. The `case _` is executed if no other case values match. Once a `case` is matched, all the following statements will be executed until another case or the end of the `match` statement is reached. Below shows a program fragment of the result, and also the flow of the `match` statement. --- ![](https://i.imgur.com/ulHGS5S.png) --- ![](https://i.imgur.com/nieiN0C.png) --- We can also have optional values for a given case. Using the or operator (`|`, which is placed at the top of the enter key), we can execute a single expression for multiple possibilities of pattern for the given variable. Below shows an example. --- ```python!= printFlag = int(input("Enter a print flag: ")) match printFlag: case 1|3: print("Good Day") print("Odds have it!") case 2|4: print("Good Day") print("Even have it!") case _: print("Good Day, I'm confused!") print("Bye!") ``` --- ### Data verification _Data verification_ is a method to check whether the data input is _actually correct_. Since a computer cannot do this by itself, _it has to involve a human in some way_. _Double entry_ is one of the methods to verify data input. The typical example is to input a new password twice when we change the password. --- Here is an example that implies double entity by `if-else` statement. ```python!= password = input("Please enter the new password: ") password_again = input("Please enter the new password again: ") if password == password_again: print("Two entries are same.") else: print("Two entries are different.") ``` --- <iframe src="https://trinket.io/embed/python3/8da04abe5a?runOption=run&start=result" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- _Visual check_ is another type of data verification. This is basically _proofreading_, the data that has been entered into the computer is _visually checked by a human_, either on screen or from a printout, to be sure that it matches the data source. --- ## Chapter summary - Decision structures are control structures that allow a program to execute different sequences of instructions for different cases. - Decisions are implemented in Python with `if` statements. Simple decisions are implemented with a plain `if`. Two-way decisions generally use an `if-else`. Multiway decisions are implemented with `if-elif-else` and `match-case`. --- - Decisions are based on the evaluation of conditions, which are simple Boolean expressions. A Boolean expression is either `True` or `False`. Conditions are formed using the relational operators: `<`, `<=`, `!=`, `==`, `>`, and `>=`. - We can use the if statement for data verification. Double entry and visual check are methods of data verification. --- ## Exercise 1. A simple decision can be implemented with an if statement. A. True B. False 2. In Python conditions, $\neq$ is written as `/=`. A. True B. False --- 3. A two–way decision is implemented using an `if-elif` statement. A. True B. False 4. Multiway decisions must be handled by nesting multiple `if-else` statements. A. True B. False --- 5. The best structure for implementing a multiway decision in Python is A. `if` B. `if-else` C. `if-elif-else` D. `try` 6. Placing a decision inside of another decision is an example of A. cloning B. spooning C. nesting D. procrastination --- ## Programming exercise ### Exercise 1 This program is a simple guessing game. The computer generates a random number (integer) between 1 and 20. The user is given **at most four** tries to guess the exact number. After each guess, the program narrows down the range of the number. If the user gives the right guess, no more guesses should be made. If the user hasn't guessed the number after five tries, display the number with a message that the user should know it by now and terminate the game. --- **A possible successful dialog:** ```! I am thinking of a number between 1 and 20. Can you guess what it is? 10 The number is between 11 and 20. Try again: 15 The number is between 11 and 14. Try again: 12 Congratulations! You did it. The number was 12. ``` --- **A possible unsuccessful dialog** ```! I am thinking of a number between 1 and 20. Can you guess what it is? 10 The number is between 1 and 9. Try again: 5 The number is between 6 and 9. Try again: 7 The number is between 8 and 9. Try again: 9 Sorry. The number was 8. You should have gotten it by now. Better luck next time ``` --- _Hint: Use the following program to start with_ ```python! import random min = 1 max = 20 random_num = random.randint(min, max) ``` --- ### Exercise 2 Write a program that reads an integer and prints "negative" for a negative integer and prints "positive" if otherwise. --- ### Exercise 3 Write a program that reads three integers and prints the median. --- ### Exercise 4 Many companies pay time-and-a-half for any hours worked above 40 in a given week. Write a program to input the number of hours worked and the hourly rate and calculate the total wages for the week. --- ### Exercise 5 A year is a leap year if it is divisible by 4, unless it is a century year that is not divisible by 400. (1800 and 1900 are _not_ leap years while 1600 and 2000 _are_.) Write a program that calculates whether a year is a leap year. --- ### Exercise 6 (Optional) Write a program with the use of a `match` statement to read an integer between 0 and 6 and print the corresponding day of the week. Assume that the first day of week (0) is Sunday.