Python Book 3 Decision Structures and Boolean Logic PDF
Document Details
Tags
Related
Summary
This document is a Python programming textbook, focusing on decision structures and Boolean logic. It explains the use of if statements and various relational and logical operators in Python code examples, useful for beginner to intermediate programmers.
Full Transcript
Python Book 3 - DECISION STRUCTURES AND BOOLEAN LOGIC Computer 521 Python Programming Book 3 1|Page The if Statement Prior to this book, we have been using the sequence structure to create programs. Using the...
Python Book 3 - DECISION STRUCTURES AND BOOLEAN LOGIC Computer 521 Python Programming Book 3 1|Page The if Statement Prior to this book, we have been using the sequence structure to create programs. Using the sequence structure, program statements execute in the order in which they appear in a program. In a sequence structure, the program code executes from top to bottom. Not all programs can logically be written using a sequence structure. You simply can’t solve some programming problems by using a set of sequential steps. Some programs require that a set of statements be executed only under certain conditions. To do this, programmers use decision structures (aka selection structures). In a decision structure, a certain set of statements is performed only if a certain condition exists. If that condition does not exist, the statements are not executed. The following flowchart shows a single alternative decision structure. It is called a single alternative decision structure because there is one alternative path of execution. If a certain condition is true, a statement is executed. If the condition is false, the statement is not executed. age >= True 19 Display False message The diamond symbol represents a true/false condition. If the condition is true (age >= 19), the program will print a message (by taking the alternative path). If the condition is false, the message is not displayed. The display message is conditionally executed because it is performed only when a certain condition is true. Programmers use the if statement to write a single alternative decision structure. Here is an example of the code that could be written for the above flowchart: if age >= 19: print(“You can legally vote in a PEI election.”) In the above example, the first line of code is referred to as the if clause. An if clause begins with the word if, followed by a condition. The condition must evaluate to either true or false. A colon must be written after the condition. The next line contains one statement. In the real world, several program statements can be written here. These statements are referred to as a block. A block of statements is a set of statements that belong together as a group. A block of statements must be indented after an if Python Programming Book 3 2|Page clause. This is a requirement in Python because the interpreter uses it to tell where the block begins and ends. When Python executes an if statement, the condition is tested. If the condition is true, the statements in the block are executed. If the condition is false, the statements in the block are skipped. Here is another example with a block of statements: if age >= 19: print(“You can legally vote on PEI.”) print(“You can legally vote in a Federal election.”) print(“Don’t forget to exercise your right to vote!”) Here is the flowchart for this decision structure: True age > = 19 You can legally False vote on PEI You can legally vote in a Federal election Don’t forget to exercise your right to vote Boolean Expressions and Relational Operators The expressions tested by an if statement are called Boolean expressions. A relational operator is used to determine the relationship between two values. A greater than operator (>) determines if one value Python Programming Book 3 3|Page is greater than another. A less than operator ( Greater than < Less than >= Greater than or equal to = 19). The expression determines if the value in the age variable is greater than or equal to 19. We could have used any of the above operators in our expression, depending on the purpose required. For instance, if we wanted to check to see if the age was equal to 19, we could have used the expression age == 19. The >= and = and the = operator checks to see if the operand on its left is greater than or equal to the operand on its right. If we have two variables, number_1 and number_2, we can compare their values using the >= operator. If the value of number_1 is greater than or equal to the value of variable number_2, then we can execute a block of statements. Here is an example: if number_1 >= number_2: print(“Number 1 is greater than or equal to number 2”) So, if number_1 is greater than or equal to number_2, the condition becomes True and the print statement is executed. The = 19: print(“You are an adult.”) else: print(“You are not an adult yet.”) Take note of the indentation in the above if-else statement. Follow these simple guidelines for indentation: - The if and the else clause should be aligned - Indent the blocks (statements) consistently. They should be aligned as in the example above. Python Programming Book 3 7|Page Let’s take a look at another example program. This program uses a dual or double alternative decision structure to determine a car salesperson’s commission rate. It then determines the salesperson’s gross pay. Type it in and save it as: car_comission.py Here is some sample output: Python Programming Book 3 8|Page Comparing Strings Strings can be compared in a decision structure. Here is an example: if class == “Calculus”: print(“This is a tough course.”) else: print(“You should take Calculus.”) In this example the == (comparison) operator compares the value in the string variable class to the string ‘Calculus’ to determine if they are equal. If the value stored in the class variable is equal to Calculus, the program will print the message ‘This is a tough course.’ If the value stored in the string variable class is not Calculus, the program will print the message ‘You should take Calculus.’ String comparisons are case sensitive. In the previous example, if the class variable contains the word calculus (with a lower case c), the if condition is false and the else part of the double alternative decision structure will execute. This happens because calculus is not equal to Calculus. Other String Comparisons Python can determine if one string is greater or less than another string. This is useful if a programmer wants to sort strings. Computers store numeric codes that represent characters like A, B, C etc. ASCII is a commonly used character coding system in computer science. Google it for more information (it should show you a set of ASCII codes). Some interesting facts about ASCII codes are: - The uppercase characters A to Z are represented by the numbers 65 to 90 - The lowercase characters a to z are represented by the numbers 97 to 122 - When the digits 0 to 9 are stored in memory as characters (as strings), they are represented by the numbers 48 to 57. - A blank space is represented by the number 32 ASCII also establishes an order for characters. The character “A” comes before the character “B” and so on. When Python compares characters, it actually compares the ASCII codes for the characters. So, if you compare two characters like c and d, (if ‘c’ < ‘d’) the expression is true because the ASCII code for the character c is less than the ASCII code for the character d. Let’s take a look at how multi character strings are compared in Python. We will demonstrate with some sample code and then we will dissect it. first_name = “Bubs” second_name = “Buba” if first_name > second_name: print(‘Bubs is larger than Buba’) Python Programming Book 3 9|Page else: print(‘Bubs is smaller than Buba’) This program will print ‘Bubs is larger than Buba’ – here is an explanation why: The > (greater than sign) is a relational operator. When we use the > operator to compare two strings, the strings are compared character-by-character from left to right. B u b s 92 117 98 115 B u b a 92 117 98 97 Here is how the two names will be compared: 1. The ‘B’ in Bubs is compared to the ‘B’ in Buba. The ASCII character codes are the same (92), so the next character will be compared. 2. The ‘u’ in Bubs is compared to the ‘u’ in Buba. The ASCII character codes are the same (117), so the next character will be compared. 3. The ‘b’ in Bubs is compared to the ‘b’ in Buba. The ASCII character codes are the same (98), so the next character will be compared. 4. The ‘s’ in Bubs is compared to the ‘a’ in Buba. The ASCII character code for ‘s’ (115) is larger than the ASCII character code for ‘a’ (97). Therefore, the strings are not equal. Python will determine that the string ‘Bubs’ is greater than the string ‘Buba’. Let’s take a look at this code: if John < Johnny: print(‘John is less than Johnny’) else: print(‘John is greater than Johnny’) Since ‘John’ is shorter than ‘Johnny’, only the corresponding characters will be compared. If the corresponding characters are identical, then the shorter string is considered to be less than the longer string. In the above example, the program would print ‘John is less than Johnny’. Nested Decision Structures and the if-elif-else Statement Decision structures can be nested inside other decision structures. This is often done when a program needs to test more than one condition. Let’s take a look at an example program that uses nested decision structures. This program determines if the user is an Islander. If the user is an Islander and the user is at least 19 years old, they qualify to vote on PEI. If the user is an Islander but they are not at least 19 years old, they do not qualify to vote Python Programming Book 3 10 | P a g e on PEI. If the user is not an Islander, they do not qualify to vote on PEI. So, to qualify to vote on PEI you have to meet two conditions: (1) the user must be an Islander, and (2) the user must be at least 19 years old. Here is a flowchart for the program: Get islander status True islander == ‘Y’ False Get age from user Print ‘Can’t vote True on PEI’ age >= 19 False Print ‘Can vote’ Print ‘Too young’ The program asks the user if they are an Islander. It then checks to see if the condition islander == ‘Y’ is true. If it is false, (they are not an Islander) the program immediately prints a message telling the user that they are not eligible to vote on PEI. It does not ask the user for their age if they are not an Islander because it does not matter how old they are if they are not an Islander. They simply cannot vote. If the user is an Islander, the condition islander == ‘Y’ is true and the program asks the user for their age. The program then checks the condition age >= 19 and if this condition is true, the program prints a message Python Programming Book 3 11 | P a g e telling the user that they are eligible to vote on PEI. If the condition age >= 19 is false, the program prints a message telling the user that they are too young to vote on PEI. Here is the code for the program. Type it in and save it as: PEI_voter.py Here is some sample output: Python Programming Book 3 12 | P a g e Testing a Series of Conditions Sometimes a program needs to test a series of conditions. The program will then execute a specific statement depending on what condition evaluates to true. Let’s take a look at a program that does this by nesting several decision structures in sequence. See the appendix for the flowchart for this program. Python Programming Book 3 13 | P a g e Here is some sample output: Python Programming Book 3 14 | P a g e The if-elif-else Statement The coding and logic in the above program can get complicated and messy. Luckily, Python has version of the decision structure known as the if-elif-else statement, which makes writing multiple nested conditionals easier to write. Below is an example of the car_manufacturer.py program that has an if-elif-else statement instead of the multiple nested decision structures code. When the above code executes, the first condition is tested (make == ‘Dodge’). If this condition is true, the print statement is executed and the rest of the structure is ignored. The same is true for any of the rest of the conditions. As soon as a particular condition tests as true, the print statement for that condition is executed and the rest of the structure is ignored. When coding an if-elif-else statement, the if, elif, and else clauses are all aligned and the conditionally executed statements are indented. Coding an if-elif-else statement is preferred to if-else statements (see car_manufacturer.py) by most programmers. There are some major disadvantages to coding with an if-else statement. - The code is difficult to debug and understand. - Indentation rules make a long series of nested if-else statements scroll horizontally to the right. This makes the code difficult to read, edit and debug. - When printing the code, the long horizontal lines wrap, making the code extremely difficult to read on paper. The advantages of coding with an if-elif-else statement are: - The logic of an if-elif-else statement is easier to follow than a long series of nested if-else statements. - The code lines in the if-elif-else statement are much shorter than in the if-else statement. They don’t wrap when printed and the programmer usually does not have to scroll horizontally to see all the code in each line. Python Programming Book 3 15 | P a g e Logical Operators The logical operators in Python are the and, or and not operators. They are used to create complex Boolean expressions. Operator Meaning Example and True if both operands are true x and y or True if either of the operands x or y are true not True if operand is False not x (complements the operand) The and Operator The logical operator and returns True only if both operands are true. In any other case, False will be returned. Let’s take a look at an example: Logical and operator if (7 < 9) and (7 > 5): operand Our example evaluates to True because 7 is less than 9 and 7 is greater than 5. Here is the logical and operator’s truth table: First operand Second operand Result T T T T F F F T F F F F Let’s look at some examples: (7 < 9) and (7 > 5) True (5 > 5) and (65 > 25) False (15/3 > = 123) and (6 == 6) False (2 == 2) and (5 5) True (15 = 35) or (7 != 7) True Here is the logical or operator’s flowchart (assume that x is the first operand and y is the second operand(: x or y Y N x= True Output = True Y N y= True Output = True Output = False The not Operator The logical not operator negates the truth value of a single operand. In other words, True becomes False and vise versa. Let’s take a look at an example: Logical not operator if not (7 < 3): operand Our example evaluates to True because 7 < 3 evaluates to False. Here is the logical not operator’s truth table: Operand Result T F F T Python Programming Book 3 18 | P a g e Let’s look at some examples: not True False not False True not 7 > 5 False not (7 > 5 and 7 > 4) False not (7 > 5 and 7 < 384) False not (7 < 5 and 7 < 49) True not (7 > 5 or 7 < 4) False When trying to figure out the truth value of the not operator, always check the operand first (or what is inside parenthesis) and then switch the truth value. Here is the logical not operator’s flowchart (assume that x is the operand): not x Y N x= True Output = False Output = True Python Programming Book 3 19 | P a g e The PEI_voter.py Program Revisited We are going to take another look at our PEI voter program that we previously coded. We are going to use the logical and operator to simplify the nested decision structure in this program. Before looking at the new code in the program below, go back and review the code for the PEI_voter.py program. Type in the following code and save the program as: PEI_voter_2.py Here is some sample output: Python Programming Book 3 20 | P a g e Let’s take a look at the code. Our new if-else statement tests the compound expression islander == ‘Y’ and age >= 19. If both operands are true, the compound expression is true and the message “You are eligible to vote on PEI” is printed. If one of the compound operands is false, the compound expression is false and the message “You are NOT eligible to vote on PEI” is printed. Type in the following program and save it as: logical_or.py Here is some sample output: Let’s take a look at the code. Our if-else statement tests the compound expression day == 'Saturday' or day == 'Sunday'. If one of the operands is true, the compound expression is true and the message “Welcome to the weekend.” is printed. If both of the compound operands is false, the compound expression is false and the message “Keep working - it is not the weekend yet.” is printed. Python Programming Book 3 21 | P a g e Type in the following program and save it as: logical_not.py Here is some sample output: Let’s take a look at the code. Our if-else statement tests the value of not (day == 'Saturday' or day == 'Sunday'). The not operator negates the truth value of a single operand. In our case, if the user types in Sunday, the not operator negates the truth value (True becomes False) and the message “Welcome to the weekend.” is printed. If the user types in Thursday, the not operator negates the truth value (False becomes True) and the message “Keep working - it is not the weekend yet.” is printed. Remember, to check the truth value inside the parenthesis first, then reverse it. Checking Numeric Ranges with Logical Operators Python programs can be designed to see if a value falls inside a range. In this situation, it is best to use the and operator. Here is an example: if grade >= 0 and grade 100: print(“Invalid grade entered”) The compound Boolean expression being tested by this statement will be true only when the value in the grade variable is less than zero or greater than 100. Boolean Variables The Boolean data type (bool data type in Python) is either True or False. In Python, Boolean variables are defined by the True and False keywords. The keywords True and False must have an Upper Case first letter. Using a lowercase true returns an error. Here are two examples of assigning values to a bool variable in Python: habs_good = True leafs_good = False Programmers usually use Boolean variables as flags. Flag variables are the same for all languages, whether it's RUBY, Python, Javascript or C++. A flag variable is usually given one value, 0 or 1, True or False. It's used as a Boolean variable where the result toggles between 0 (False) and 1 (True) or as used by the programmer. Some prefer flag = 0 and change it to flag = 1 in the program to perform an action. Here is an example: if mark < 50: pass_flag = False else: pass_flag = True The if statement in this code checks to see if the value in a variable called mark is less the 50. If it is, the value of the bool variable called pass_flag will be set to False. If the statement is false, the pass_flag variable will be assigned the value True. Later in the program, we can test the pass_flag variable in the following way: if pass_flag: print(“You have achieved a passing grade in Computer 521”) The if statement checks the value of the bool variable pass_flag. If the value in the pass_flag variable is True, the program will print a message for the user. The above if statement could also have been written like this: Python Programming Book 3 23 | P a g e If pass_flag == True: print(“You have achieved a passing grade in Computer 521”)