Selection is the process of taking an action based on a condition.
This decision must resolve to a boolean value, which is
either true
or false
.
In other words, it must use an boolean expression to make the decision.
A single alternative decision structure yields control to a process only if some boolean expression is true.
Charge Customer for Item - v1
BEGIN
Begin point of sales transaction
Scan all items
IF customer is a rewards member:
Apply discount
END IF
Complete point of sales transaction
END
Do in class. Keep for later.
Anything inside the code block (indented at the if’s level) will be evaluated only if the “if” expression evaluates to true.
The expression for the if statement can be arbitrarily complex - the only constraint is that it must evaluate to True or False.
if x:
# do something
Check if a number is even. (We will do even or odd in a single program shortly.)
Write a program given the following logic:
A dual alternative decision structure yields control to one of two processes based on the truthfulness of a given boolean condition.
Dual alternative example: Open communication channel with landing aircraft.
Charge Customer for Item - v2
BEGIN
Begin point of sales transaction
Scan all items
IF customer is a rewards member:
Apply discount
Get payment method
IF payment method is credit card:
Swipe card
ELSE
Take cash
END IF
End point of sales transaction
END
Do in class.
if x:
# do something
else:
# do something else
Check if a number is even/odd.
We can put decision structures into the flow of execution from another decision. These are called nested decisions.
BEGIN
IF it is cold outside:
IF it is snowing:
Wear boots
ELSE:
Wear shoes
ELSE:
Wear sandals
END
Charge Customer for Item - v3
BEGIN
Begin point of sales transaction
Scan all items
IF customer is a rewards member:
Apply discount
Get payment method
IF payment method is credit card:
Swipe card
IF payment is declined:
Deny payment
Shelve items for restocking
ELSE
Take cash
IF change is due:
Give change
END IF
End point of sales transaction
END
Do in class.
We can chain together arbitrary amounts of decisions to represent “fallback logic” - if, else if, else if, … else.
What happens if we use regular if
statements instead of
else if
?
What would the pseudocode look like if we did not have
else if
, and instead just used a series of
if
statements?
Charge Customer for Item - v3
BEGIN
Begin point of sales transaction
Scan all items
IF customer is a rewards member:
Apply discount
Get payment method
IF payment method is credit card:
Swipe card
ELSE IF payment method is cash:
Take cash
ELSE
Deny payment
Shelve items for restocking
END IF
End point of sales transaction
END
Do in class.
if x:
# do something
elif y:
# do something else
else:
# do something else