0% found this document useful (0 votes)
9 views

Decision Structures and Boolean Logic

Uploaded by

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

Decision Structures and Boolean Logic

Uploaded by

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

Starting out with Python

Fifth Edition, Global Edition

Chapter 3
Decision Structures and
Boolean Logic

3-1
Topics

 The if Statement
 The if-else Statement
 Comparing Strings
 Nested Decision Structures and the if-
elif-else Statement
 Logical Operators
 Boolean Variables

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3-2


The if Statement (1 of 5)
 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3-3


The if Statement (2 of 5)
 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3-4


The if Statement (3 of 5)

Figure 3-1 A simple decision structure

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3-5


The if Statement (4 of 5)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3-6


The if Statement (5 of 5)
 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3-7


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3-8


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3-9


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 10


Boolean Expressions and
Relational Operators (4 of 5)
 Using a Boolean expression with the > relational
operator

Figure 3-3 Example decision structure

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 11


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 12


Example
 Create the program of the following
pseudocode:

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 13


Solution
HIGH_SCORE = 95
test1 = int(input('Enter the score for test 1: ' ))
test2 = int(input('Enter the score for test 2: ' ))
test3 = int(input('Enter the score for test 3: ' ))
# Calculate the average test score.
average = (test1 + test2 + test3) / 3
# Print the average.
print(f'The average score is {average}.')
# If the average is a high score,
# congratulate the user.
if average >= HIGH_SCORE:
print('Congratulations!')
print('That is a great average!')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 14


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 15


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


Example

 If any employee works over 40 hours in a


week, he pays them 1.5 times their regular
hourly pay rate for all hours over 40.
 Write a program with the following
pseudocode:
 Get the number of hours worked.
 Get the hourly pay rate.
 If the employee worked more than 40 hours:
Calculate and display the gross pay with
overtime.
 Else:
Calculate and display the gross pay as usual.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 18


BASE_HOURS = 40 # Base hours per week
OT_MULTIPLIER = 1.5 # Overtime multiplier
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > BASE_HOURS:
overtime_hours = hours − BASE_HOURS
# Calculate the amount of overtime pay.
overtime_pay = overtime_hours * pay_rate * OT_MULTIPLIER
# Calculate the gross pay.
gross_pay = BASE_HOURS * pay_rate + overtime_pay
else:
# Calculate the gross pay without overtime.
gross_pay = hours * pay_rate
# Display the gross pay.
print(f'The gross pay is ${gross_pay:,.2f}.')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 19


Comparing Strings (1 of 3)
 Strings can be compared using the ==
and != operators
 Example:
name1 = 'Mary‘
name2 = 'Mark‘
if name1 == name2:
print('The names are the same.')
else:
print('The names are NOT the
same.')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 20


Comparing Strings (2 of 2)

Figure 3-9 Comparing each character in a string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 21


Comparing Strings (3 of 3)

 String comparisons are case sensitive


 Strings can be compared using >, <,
>=, and <=
 Compared character by character
based on the ASCII values for each
character
 Ifshorter word is substring of longer
word, longer word is greater than
shorter word

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 22


ASCII (American Standard Code for Information
Interchange)
character set

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 23


Example

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 24


Comparing Strings

 If one of the strings in a comparison is


shorter than the other, only the
corresponding characters will be
compared.
 If the corresponding characters are
identical, then the shorter string is
considered less than the longer string.
 For example, suppose the strings 'High‘ and
'Hi' were being compared. The string 'Hi'
would be considered less than 'High‘
because it is shorter.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 25


Example

 Take two names from the user and list


them alphabetically.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 26


# This program compares strings with the < operator.
#name1 = input('Enter a name (last name first): ')
#name2 = input('Enter another name (last name first): ')
# Display the names in alphabetical order.
print('Here are the names, listed alphabetically.')
if name1 < name2:
print(name1)
print(name2)
else:
print(name2)
print(name1)
Get two names from the user.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 27


Nested Decision Structures and the
if-elif-else Statement (1 of 3)

 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 28


Nested Decision Structures and the
if-elif-else Statement (2 of 3)

Figure 3-12 A nested decision structure

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 29


Nested Decision Structures and
the if-elif-else Statement (3 of 3)
 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 30


The if-elif-else
Statement (1 of 3)
 if-elif-else statement: special
version of a decision structure
 Makes logic of nested decision structures
simpler to write
 Can include multiple elif statements
if condition_1:
 Syntax:
statement(s)
elif condition_2:
statement(s) Insert as many elif clauses
elif condition_3: as necessary.
statement(s)
else
statement(s)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 31


The if-elif-else
Statement (2 of 3)
 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 32


The if-elif-else Statement (3 of 3)

Figure 3-15 Nested decision structure to determine a grade

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 33


# This program gets a numeric test score from the
# user and displays the corresponding letter grade
# Named constants to represent the grade thresholds
A_SCORE = 90
B_SCORE = 80
C_SCORE = 70
D_SCORE = 60
# Get a test score from the user.
score = int(input('Enter your test score: '))
# Determine the grade.
if score >= A_SCORE:
print('Your grade is A.')
else:
if score >= B_SCORE:
print('Your grade is B.')
else:
if score >= C_SCORE:
print('Your grade is C.')
else:
if score >= D_SCORE:
print('Your grade is D.')
else:
print('Your grade is F.')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 34


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 35


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 36


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 or false false
false or true true
true or false true
true or true true

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 37


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 38


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 39


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 40


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 41


Flag example

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 42


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
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 43

You might also like