Chapter 3 PPT Notes: Decision Structures and Boolean Logic (Python)
The if Statement (1 of 4)
Definition: A control structure is a design that controls the order in which a set of statements executes.
Sequence structure: statements execute in the order they appear.
Decision structure (selection structure): actions are performed only if a condition exists.
Also known as: decision structure or selection structure.
The if Statement (2 of 4)
In flowcharts, a diamond shape represents a true/false condition tested by the program.
Actions can be conditionally executed — performed only when the condition is true.
Single alternative decision structure: provides only one alternative path of execution.
If the condition is not true, the structure exits (no alternative path).
The if Statement (3 of 4)
Figure 3-1: A simple decision structure (reference to visual example).
The if Statement (4 of 4)
Python syntax:
if condition: Statement Statement
First line:
The if clause: keyword
iffollowed by a condition.The condition can be true or false.
When the
ifstatement executes, the condition is tested; if it is true, the block statements are executed; otherwise, block statements are skipped.
Boolean Expressions and Relational Operators (1 of 5)
Boolean expression: an expression tested by an
ifstatement to determine if it is true or false.Example: a > b
True if
ais greater thanb; false otherwise.
Relational operator: determines whether a specific relationship exists between two values.
Example: greater than operator >.
Boolean Expressions and Relational Operators (2 of 5)
Relational operators that test ranges:
a \, \ge \, b and a \, \le \, b test more than one relationship; it is enough for one to be true for the expression to be true.
Equality/Inequality:
a == b tests whether the two operands are equal.
Do not confuse with the assignment operator
=.a != b tests whether the two operands are not equal.
Boolean Expressions and Relational Operators (3 of 5)
Table (conceptual):
Expression: x > y
Meaning: Is x greater than y?
Expression: x < y
Meaning: Is x less than y?
Expression: x \ge y
Meaning: Is x greater than or equal to y?
Expression: x \le y
Meaning: Is x less than or equal to y?
Expression: x == y
Meaning: Is x equal to y?
Expression: x != y
Meaning: Is x not equal to y?
Boolean Expressions and Relational Operators (4 of 5)
Using a Boolean expression with the
>relational operator (illustrative):Figure 3-3 shows an example decision structure using a relational operator.
Boolean Expressions and Relational Operators (5 of 5)
Any relational operator can be used in a decision block.
Examples: ext{if balance } == 0, or ext{if payment } != ext{ balance}.
Nested blocks:
It is possible to have a block inside another block (e.g., a statement inside a function).
Inner block statements must be indented with respect to the outer block.
Single-Line if Statements
An
ifstatement can be written on a single line if it executes only one statement.Syntax:
if condition: statementExample:
if score > 59: print('You passed!')
The if-else Statement (1 of 3)
Dual alternative decision structure: two possible paths of execution.
One path if the condition is true, another path if the condition is false.
Syntax:
if condition: statements else: other statements
The
ifclause andelseclause must be aligned; statements must be consistently indented.
The if-else Statement (2 of 3)
Visual reference: Figure 3-5 shows a dual alternative decision structure.
The if-else Statement (3 of 3)
Visual reference: Figure 3-6 shows conditional execution in an if-else statement.
Comparing Strings (1 of 2)
Strings can be compared using
==and!=.String comparisons are case sensitive.
Strings can also be compared using
>,<,>=,<=.Comparison is character-by-character based on ASCII values.
If a shorter word is a substring of a longer word, the longer word is greater than the shorter word.
Comparing Strings (2 of 2)
Figure 3-9: Comparing each character in a string (visual example).
Nested Decision Structures and the if-elif-else Statement (1 of 2)
A decision structure can be nested inside another decision structure.
Common in programs (e.g., loan qualification).
Example: To qualify for a loan, a person must meet two conditions:
Must earn at least 30{,}000/\text{year}; and
Must have been employed for at least two years.
Check first condition, and if it is true, check the second condition.
Nested Decision Structures and the if- elif-else Statement (2 of 2)
Indentation is crucial in a nested decision structure:
The
elseclause should align with the matchingifclause.Statements in each block must be consistently indented.
The if-elif-else Statement (1 of 2)
The
if-elif-elsestatement is a special version of a decision structure that can simplify the logic of nested decision structures.It can include multiple
elifstatements.Syntax range note: the exact syntax mirrors standard Python structure (alignment and indentation are key).
The if-elif-else Statement (2 of 2)
Alignment:
if,elif, andelseclauses are all aligned.Conditionally executed blocks are consistently indented.
It's never required to use
elifchain; sometimes nestedif-elsecan achieve the same logic, but can be harder to read and maintain.
Figure 3-15: Nested Decision Structure to Determine a Grade
Logical Operators
Logical operators allow the creation of complex Boolean expressions:
andandorare binary operators that connect two Boolean expressions into a compound expression.notis a unary operator that reverses the truth value of its operand.
The and Operator
Takes two Boolean expressions as operands.
Produces a compound expression that is true only when both sub-expressions are true.
Can simplify nested decision structures.
Truth-like behavior (conceptual):
The compound expression is true only if both operands are true; otherwise false.
The or Operator
Takes two Boolean expressions as operands.
Produces a compound expression that is true when either sub-expression is true.
Can simplify nested decision structures.
Truth-like behavior (conceptual):
The compound expression is true if at least one operand is true; false only if both are false.
Short-Circuit Evaluation
Short-circuit evaluation occurs when the value of a compound Boolean expression can be determined after evaluating only one sub-expression.
For
or: if the left operand is true, the whole expression is true and the right operand is not evaluated.For
and: if the left operand is false, the whole expression is false and the right operand is not evaluated.
The not Operator
Unary operator: takes one Boolean expression and reverses its value.
Parentheses may be used to clarify the scope of the
notoperator.Truth table (conceptual):
If the expression is true,
notmakes it false; if false,notmakes it true.
Checking Numeric Ranges With Logical Operators
To determine whether a numeric value is within a range, use
and:Example: x \ge 10 \land x \le 20
To determine whether a numeric value is outside a range, use
or:Example: x < 10 \lor x > 20
Boolean Variables
Boolean variable: a variable that references one of two values, True or False.
Data type:
bool.Commonly used as flags to signal when a condition exists in a program.
Flag set to False => condition does not exist.
Flag set to True => condition exists.
Conditional Expressions (1 of 3)
Syntax: value1\ if\ condition\ else\ value2
conditionis a Boolean expression.If the condition is true, the expression yields
value_1; otherwise, it yieldsvalue_2.
Conditional Expressions (2 of 3)
Example:
grade = 'Pass' if score > 59 else 'Fail'.If
score > 59,gradeis assigned'Pass'; elsegradeis'Fail'.
Equivalence to a full
ifstatement:If
score > 59:grade = 'Pass'else:grade = 'Fail'.
Conditional Expressions (3 of 3)
Example:
max = num1 if num1 > num2 else num2.If
num1 > num2,maxis assignednum1; otherwise,maxis assignednum2.
Equivalence to: if
num1 > num2:max = num1else:max = num2.
Assignment Expressions and the Walrus Operator (1 of 5)
The walrus operator
:=is an enhanced assignment operator.Assignment expressions do two things:
It assigns a value to a variable.
It returns the value that was assigned to the variable.
Assignment Expressions and the Walrus Operator (2 of 5)
Example:
print(num := 99)This statement assigns
99tonumand prints the value99.
Assignment Expressions and the Walrus Operator (3 of 5)
Example:
if (area := width * height) > 100: print('The area is too large')The
areavariable is assigned the value ofwidth * height.If the assigned value is greater than 100, the message is displayed.
Assignment Expressions and the Walrus Operator (4 of 5)
Precedence: the walrus operator has the lowest precedence of all operators in Python.
When used in a larger expression with other operators, the walrus operator works last.
Recommendation: parentheses around the assignment expression help ensure the correct value is assigned.
Assignment Expressions and the Walrus Operator (5 of 5)
An assignment expression is not a complete statement.
Example error:
num := 99on its own.It must be part of a larger statement, e.g.,
print(num := 99).
Turtle Graphics: Determining the State of the Turtle (1 of 9)
turtle.xcor()andturtle.ycor()return the turtle's X and Y coordinates.Examples in an
ifstatement:if turtle.ycor() < 0:turtle.goto(0, 0)
Another example:
if turtle.xcor() > 100 and turtle.xcor() < 200:turtle.goto(0, 0)
Turtle Graphics: Determining the State of the Turtle (2 of 9)
turtle.heading()returns the turtle's heading in degrees (default).Example:
if turtle.heading() >= 90 and turtle.heading() <= 270:turtle.setheading(180)
Turtle Graphics: Determining the State of the Turtle (3 of 9)
turtle.isdown()returnsTrueif the pen is down, otherwiseFalse.Example:
if turtle.isdown():followed byturtle.penup()if not(turtle.isdown()):followed byturtle.pendown()
Turtle Graphics: Determining the State of the Turtle (4 of 9)
turtle.isvisible()returnsTrueif the turtle is visible, otherwiseFalse.Example:
if turtle.isvisible():followed byturtle.hideturtle()
Turtle Graphics: Determining the State of the Turtle (5 of 9)
When you call
turtle.pencolor()without an argument, it returns the pen's current color as a string.Example:
if turtle.pencolor() == 'red':turtle.pencolor('blue')
When you call
turtle.fillcolor()without an argument, it returns the current fill color as a string.Example:
if turtle.fillcolor() == 'blue':turtle.fillcolor('white')
Turtle Graphic: Determining the State of the Turtle (6 of 9)
turtle.bgcolor()without an argument returns the current background color as a string.Example:
if turtle.bgcolor() == 'white':turtle.bgcolor('gray')
Turtle Graphics: Determining the State of the Turtle (7 of 9)
turtle.pensize()without an argument returns the pen's current size.Example:
if turtle.pensize() < 3:turtle.pensize(3)
Turtle Graphics: Determining the State of the Turtle (8 of 9)
turtle.speed()without an argument returns the current animation speed.Example:
if turtle.speed() > 0:turtle.speed(0)
Turtle Graphics: Determining the State of the Turtle (9 of 9)
See In the Spotlight: The Hit the Target Game in your textbook for numerous examples of determining the state of the turtle.
Summary
This chapter covered:
Decision structures, including:
Single alternative decision structures
Dual alternative decision structures
Nested decision structures
Relational operators and logical operators as used in creating Boolean expressions
String comparison as used in creating Boolean expressions
Boolean variables
Determining the state of the turtle in Turtle Graphics