0% found this document useful (0 votes)
111 views49 pages

Gaddis Python 6e Chapter 03 - Accessible

Gaddis Python 6e Chapter 03_accessible

Uploaded by

Jose Vega
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views49 pages

Gaddis Python 6e Chapter 03 - Accessible

Gaddis Python 6e Chapter 03_accessible

Uploaded by

Jose Vega
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Starting Out with Python

Sixth Edition

Chapter 3
Decision Structures and
Boolean Logic

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Topics
• The if Statement
• The if-else Statement
• Comparing Strings
• Nested Decision Structures and the if-elif-else Statement
• Logical Operators
• Boolean Variables
• Conditional Expressions
• Assignment Expressions and the Walrus Operator
• Turtle Graphics: Determining the State of the Turtle

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if Statement (1 of 4)
• 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if Statement (2 of 4)
• In flowchart, diamond represents true/false condition
that must be tested
• Actions can be conditionally executed
– Performed only when a condition is true
• Single alternative decision structure: provides only
one alternative path of execution
– If condition is not true, exit the structure

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if Statement (3 of 4)
Figure 3-1 A simple decision structure

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if Statement (4 of 4)
• Python syntax:
if condition:
Statement
Statement
• 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Boolean Expressions and Relational
Operators (1 of 5)
• 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
• Relational operator: determines whether a specific
relationship exists between two values
– Example: greater than (>)

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Boolean Expressions and Relational
Operators (2 of 5)
• >= and <= operators test more than one relationship
– It is enough for one of the relationships to exist for the
expression to be true
• == operator determines whether the two operands
are equal to one another
– Do not confuse with assignment operator (=)
• != operator determines whether the two operands
are not equal

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Boolean Expressions and Relational
Operators (3 of 5)
Table 3-2 Boolean expressions using relational operators
Expression Meaning

x>y Is x greater than y?

x<y Is x less than y?

x >= y Is x greater than or equal to y?

x <= y Is x less than or equal to y?

x == y Is x equal to y?

x != y Is x not equal to y?

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Boolean Expressions and Relational
Operators (4 of 5)
• Using a Boolean expression with the > relational operator
Figure 3-3 Example decision structure

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Boolean Expressions and Relational
Operators (5 of 5)
• Any relational operator can be used in a decision
block
– Example: if balance == 0
– Example: if payment != balance
• It is possible to have a block inside another block
– Example: if statement inside a function
– Statements in inner block must be indented with
respect to the outer block

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Single-Line if Statements
An if statement can be written on a single line if it
executes only one statement.
• Python syntax:
if condition: statement
• Example:
if score > 59: print('You passed!')

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if-else Statement (1 of 3)
• Dual alternative decision structure: 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if-else Statement (2 of 3)
Figure 3-5 A dual alternative decision structure

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if-else Statement (3 of 3)
Figure 3-6 Conditional execution in an if-else statement

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Comparing Strings (1 of 2)
• Strings can be compared using the == and !=
operators
• String comparisons are case sensitive
• Strings can be compared using >, <, >=, and <=
– Compared character by character based on the ASCII
values for each character
– If shorter word is substring of longer word, longer
word is greater than shorter word

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Comparing Strings (2 of 2)
Figure 3-9 Comparing each character in a string

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Nested Decision Structures and the if-
elif-else Statement (1 of 2)
• 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Figure 3-12 A Nested Decision Structure

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Nested Decision Structures and the if-
elif-else Statement (2 of 2)
• 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if-elif-else Statement (1 of 2)
• 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:

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
The if-elif-else Statement (2 of 2)
• 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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Figure 3-15 Nested Decision Structure to
Determine a Grade

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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
Expression Value of the Expression
false and false false
false and true false
true and false false
true and true true

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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
Expression Value of the Expression
false and false false
false and true true
true and false true
true and true true

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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

Expression Value of the Expression


true false
false true

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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
• To determine whether a numeric value is outside of a
specific range of values, use or
– Example: x < 10 or x > 20

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Conditional Expressions (1 of 3)
• Syntax:

value_1 if condition else value_2


• condition is a Boolean expression that is tested
• If condition is true, the expression gives us
value_1
• If condition is false, the expression gives us
value_2

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Conditional Expressions (2 of 3)
• Example:

grade = 'Pass' if score > 59 else 'Fail'

• If score is greater than 59, grade is assigned


'Pass'. Otherwise, grade is assigned 'Fail'.
• Equivalent to:

if score > 59:


grade = 'Pass'
else:
grade = 'Fail'

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Conditional Expressions (3 of 3)
• Example:

max = num1 if num1 > num2 else num2

• If num1 is greater than num2, max is assigned num1.


Otherwise, max is assigned num2.
• Equivalent to:

if num1 > num2:


max = num1
else:
max = num2

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and the Walrus
Operator (1 of 5)
• The walrus operator := is an enhanced assignment
operator
• You use the walrus operator to create assignment
expressions
• An assignment expression does two things:
– It assigns a value to a variable
– It returns the value that was assigned to the variable

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and the Walrus
Operator (2 of 5)
• Example:
print(num := 99)

• This statement does two things:


– It assigns 99 to the num variable
– It prints the value that was assigned to the num
variable, 99

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and the Walrus
Operator (3 of 5)
• Example:
if (pay := hours * pay_rate) > 40:
print('You worked overtime’)

• This if statement does the following:


– The pay variable is assigned the value of hours *
pay_rate
– If the value that was assigned to pay is greater than
40, the message You worked overtime is displayed.

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and the Walrus
Operator (4 of 5)
• Precedence of the walrus operator
– The walrus operator has the lowest precedence of all
the operators in Python
– When using the walrus operator in a larger expression
that also uses other operators, the walrus operator
will work last
– In most cases, you need to put parentheses around
the assignment expression to make sure the walrus
operator assigns the correct value to its variable

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and the Walrus
Operator (5 of 5)
• An assignment expression is not a complete
statement
– For example, this alone causes an error:
num := 99
• It must be written as part of a larger statement
print(num := 99)

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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 © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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() <= 270:


turtle.setheading(180)

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (3 of 9)
• The turtle.isdown() function returns True if the pen is
down, or False otherwise.
• Example of calling the function in an if statement:

if turtle.isdown():
turtle.penup()

if not(turtle.isdown()):
turtle.pendown()

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (4 of 9)
• The turtle.isvisible() function returns True if the turtle is
visible, or False otherwise.
• Example of calling the function in an if statement:

if turtle.isvisible():
turtle.hideturtle()

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (5 of 9)
• When you call turtle.pencolor() without passing an
argument, the function returns the pen's current color as a
string. Example of calling the function in an if statement:

if turtle.pencolor() == 'red':
turtle.pencolor('blue')

• When you call turtle.fillcolor() without passing an


argument, the function returns the current fill color as a string.
Example of calling the function in an if statement:

if turtle.fillcolor() == 'blue':
turtle.fillcolor('white')

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (6 of 9)
• When you call turtle.bgcolor() without passing
an argument, the function returns the current
background color as a string. Example of calling the
function in an if statement:

if turtle.bgcolor() == 'white':
turtle.bgcolor('gray')

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (7 of 9)
• When you call turtle.pensize() without passing
an argument, the function returns the pen's current
size as a string. Example of calling the function in an
if statement:
if turtle.pensize() < 3:
turtle.pensize(3)

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Turtle Graphics: Determining the State of
the Turtle (8 of 9)
• When you call turtle.speed() without passing an
argument, the function returns the current animation
speed. Example of calling the function in an if
statement:
if turtle.speed() > 0:
turtle.speed(0)

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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.

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
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

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved
Copyright

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2023, 2021, 2018 Pearson Education, Inc. All Rights Reserved

You might also like