CSBP119_FA2024_LCN_03(1) (1) (1).pptx
Document Details
Uploaded by EasiestMandelbrot
Tags
Full Transcript
CSBP119 Algorithms & Problem Solving CIT, UAEU CHAPTER 3 Decision Structures and Boolean Logic Copyright © 2018 Pearson Education, Ltd. ...
CSBP119 Algorithms & Problem Solving CIT, UAEU CHAPTER 3 Decision Structures and Boolean Logic Copyright © 2018 Pearson Education, Ltd. Topics The if Statement The if-else Statement Comparing Strings Nested Decision Structures and the if-elif-else Statement Logical Operators Boolean Variables Turtle Graphics: Determining the State of the Turtle Copyright © 2018 Pearson Education, Ltd. Decision Structure Control structure: logical design that controls order in which set of statements execute Sequence structure: set of statements that execute in the order they appear Decision structure: specific action(s) performed only if a condition exists Also known as selection structure Copyright © 2018 Pearson Education, Ltd. Single Decision Structure In flowchart, diamond represents true/false condition that must be tested Actions can be conditionally executed Single alternative decision structure (one-way selection): provides only one alternative path of execution Performed only when a condition is true If condition is not true, exit the structure Copyright © 2018 Pearson Education, Ltd. Example Figure 3-1 A single alternative decision structure Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3-5 The if Statement Python syntax: if condition: Statement1 Statement2 First line known as the if clause Includes the keyword if followed by condition The condition can be true or false When the if statement executes, the condition is tested, and if it is true the block statements are executed. otherwise, block statements are skipped Copyright © 2018 Pearson Education, Ltd. Relational Operators and Boolean Expressions and Relational operator: determines whether a specific relationship exists between two values Example: greater than (>) Boolean expression: expression tested by if statement to determine if it is true or false Example: a > b true if a is greater than b; false otherwise Copyright © 2018 Pearson Education, Ltd. Relational Operators and Boolean Expressions (cont’d.) >= and y ?Is x greater than y x < y ?Is x less than y x >= y ?Is x greater than or equal to y x >> x = 1 Enter >>> y = 0 Enter >>> y < x Enter True >>> x < y Enter False >>> Copyright © 2018 Pearson Education, Ltd. Boolean Expressions in Flowchart Using a Boolean expression with the > relational operator Copyright © 2018 Pearson Education, Ltd. Relational Operators and Decision Block Any relational operator can be used in a decision block Example: if balance == 0 Example: if payment != balance Copyright © 2018 Pearson Education, Ltd. Example Write a program to find if the test score is equal or higher than 95. HIGH_SCORE = 95 test = int(input('Enter the score for test: ' )) if test >= HIGH_SCORE: print('Congratulations!’) print('That is a great score!') Copyright © 2018 Pearson Education, Ltd. Exercise Write an if statement that assigns 20 to the variable y and assigns 40 to the variable z if the variable x is greater than 100. Write an if statement that assigns 10 to the variable b, and 50 to the variable c if the variable a is equal to 100. Copyright © 2018 Pearson Education, Ltd. The if-else Statement Dual alternative decision structure (two-way selection): two possible paths of execution – One is taken if the condition is true, and the other if the condition is false Syntax: if condition: statements else: other statements if clause and else clause must be aligned Statements must be consistently indented Copyright © 2018 Pearson Education, Ltd. The if-else Statement Copyright © 2018 Pearson Education, Ltd. The if-else Statement (2 of 3) Figure 3-5 A dual alternative decision structure Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 16 The if-else Statement (3 of 3) Figure 3-6 Conditional execution in an if-else statement Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 17 Exercise Write an if-else statement that assigns 0 to the variable b if the variable a is less than 10. Otherwise, it should assign 99 to the variable b. Copyright © 2018 Pearson Education, Ltd. Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and name2: print('Mary is greater than Mark') else: print('Mary is not greater than Mark') Program Output: Mary is greater than Mark Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 20 Nested Decision Structures A decision structure can be nested inside another decision structure Commonly needed in programs Example: Determine if someone qualifies for a loan, they must meet two conditions: Must earn at least $30,000/year Must have been employed for at least two years Check first condition, and if it is true, check second condition Copyright © 2018 Pearson Education, Ltd. Nested Decision Structures Flowchart Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 22 Nested Decision Structures rules Important to use proper indentation in a nested decision structure Important for Python interpreter Makes code more readable for programmer Rules for writing nested if statements: else clause should align with matching if clause Statements in each block must be consistently indented Copyright © 2018 Pearson Education, Ltd. Nested Decision Structures Example MIN_SALARY = 30000.0 # The minimum annual salary MIN_YEARS = 2 # The minimum years on the job salary = float(input('Enter your annual salary: ‘)) years_on_job = int(input('Enter the number of years employed: ')) if salary >= MIN_SALARY: if years_on_job >= MIN_YEARS: print('You qualify for the loan.’) else: print('You must have been employed for at least’, MIN_YEARS,'years to qualify.') else: print('You must earn at least $’, format(MIN_SALARY, ',.2f’), ' per year to qualify.', sep='') Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement if-elif-else statement: special version of a decision structure Makes logic of nested decision structures simpler to write Can include multiple elif statements Syntax: if condition_1: statement(s) elif condition_2: statement(s) Insert as many elif clauses elif condition_3: as necessary. statement(s) else statement(s) Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement (cont’d.) Alignment used with if-elif-else statement: if, elif, and else clauses are all aligned Conditionally executed blocks are consistently indented if-elif-else statement is never required, but logic easier to follow Can be accomplished by nested if-else Code can become complex, and indentation can cause problematic long lines Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement Flowchart Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 27 The if-elif-else Statement Example if score >= 90: print('Your grade is A.') elif score >= 80: print('Your grade is B.') elif score >= 70: print('Your grade is C.') elif score >= 60: print('Your grade is D.') else: print('Your grade is F.') Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 28 Logical Operators Logical operators: operators that can be used to create complex Boolean expressions and operator and or operator: binary operators, connect two Boolean expressions into a compound Boolean expression not operator: unary operator, reverses the truth of its Boolean operand Copyright © 2018 Pearson Education, Ltd. The and Operator Takes two Boolean expressions as operands Creates compound Boolean expression that is true only when both sub expressions are true Can be used to simplify nested decision structures Truth table for the and operator Value of the Expression Expression false false and false false false and true false true and false true true and true Copyright © 2018 Pearson Education, Ltd. The or Operator Takes two Boolean expressions as operands Creates compound Boolean expression that is true when either of the sub expressions is true Can be used to simplify nested decision structures Truth table for the or operator Value of the Expression Expression false false or false true false or true true true or false true true or true Copyright © 2018 Pearson Education, Ltd. Short-Circuit Evaluation Short circuit evaluation: deciding the value of a compound Boolean expression after evaluating only one sub expression Performed by the or and and operators For or operator: If left operand is true, compound expression is true. Otherwise, evaluate right operand For and operator: If left operand is false, compound expression is false. Otherwise, evaluate right operand Copyright © 2018 Pearson Education, Ltd. The not Operator Takes one Boolean expressions as operand and reverses its logical value Sometimes it may be necessary to place parentheses around an expression to clarify to what you are applying the not operator Truth table for the not operator Value of the Expression Expression false true true false Copyright © 2018 Pearson Education, Ltd. Checking Numeric Ranges with Logical Operators To determine whether a numeric value is within a specific range of values, use and Example: x >= 10 and x 20 Copyright © 2018 Pearson Education, Ltd. Boolean Variables Boolean variable: references one of two values, True or False Represented by bool data type Commonly used as flags Flag: variable that signals when some condition exists in a program Flag set to False condition does not exist Flag set to True condition exists Copyright © 2018 Pearson Education, Ltd. Optional Slides TURTLE GRAPHICS Copyright © 2018 Pearson Education, Ltd. Turtle Graphics: Determining the State of the Turtle (1 of 9) The turtle.xcor() and turtle.ycor() functions return the turtle's X and Y coordinates Examples of calling these functions in an if statement: if turtle.ycor() == 0: turtle.goto(0, 0) if turtle.xcor() > 100 and turtle.xcor() < 200: turtle.goto(0, 0) Copyright © 2018 Pearson Education, Ltd. Turtle Graphics: Determining the State of the Turtle (2 of 9) The turtle.heading() function returns the turtle's heading. (By default, the heading is returned in degrees.) Example of calling the function in an if statement: if turtle.heading() >= 90 and turtle.heading()