Unit 11: Making Decisions Flashcards
Boolean
a type that contains only two possible values: true and false
Comparison operators
used as a symbol in a comparison statement when you describe a relationship between two things
> = comparison operator to indicate that one value is larger than another vs. == two values are equal
Conditional Statement
like a traffic controller that causes different code to run in different situations
if/ switch statements
Remainder Operator [%]
returns the amount left over after dividing one number by another
27 % 10 = 7
Making Decisions
All the code you’ve written so far has run in playgrounds — and has run from the first line to the last, in order. No matter what you give your code to work on, it does the same things with it.
Consider the string interpolations you learned about. You had to perform a calculation and show the result in a string, something like this:
let videoLength = 3 let videoLengthTooShortReaction = "If I blinked, I'd miss it!" let videoReasonableLengthReaction = "That was lovely." let videoMessage = "Your video is \(videoLength) seconds long. \(videoLengthTooShortReaction)"
/*: If the answer was 3, then this works fine:
Your video is 3 seconds long. If I blinked, I'd miss it!
But try changing the video length to something enormous, like 2857013857. In that case, the videoMessage
doesn’t look right:
Your video is 2857013857 seconds long. If I blinked, I'd miss it!
You want your code to do different things depending on the value of the answer. You need your code to make decisions.
Find out about the type used in Swift for making decisions.
True and False
All the code you’ve written so far has run in playgrounds — and has run from the first line to the last, in order. No matter what you give your code to work on, it does the same things with it.
Consider the string interpolations you learned about. You had to perform a calculation and show the result in a string, something like this:
let videoLength = 3 let videoLengthTooShortReaction = "If I blinked, I'd miss it!" let videoReasonableLengthReaction = "That was lovely." let videoMessage = "Your video is \(videoLength) seconds long. \(videoLengthTooShortReaction)"
/*: If the answer was 3, then this works fine:
Your video is 3 seconds long. If I blinked, I'd miss it!
But try changing the video length to something enormous, like 2857013857. In that case, the videoMessage
doesn’t look right:
Your video is 2857013857 seconds long. If I blinked, I'd miss it!
You want your code to do different things depending on the value of the answer. You need your code to make decisions.
Find out about the type used in Swift for making decisions.
Equality
You’ve learned that true and false are special values. Without typing in Bools directly (which isn’t really making a decision), how do you ask questions in code? One way is by making comparison statements.
Comparison statements say something, and Swift will say if that something is true or false. A comparison statement has three parts:
This…
has a relationship to…
that
Parts 1 and 3 are values, like the numbers and strings you’ve already been working with. Part 2 is something new: a comparison operator. Here’s an example:
1 == 2 /*: The double equal sign `==` checks if the left hand and right hand sides of the statement are equal. In this case they’re not, so the statement is false.
- note: You can’t use a single equal sign
=
for a comparison because it’s already used for assigning a value, as you learned in previous playgrounds.
The following slightly more complicated example statement is `true`: */ 10 == 9 + 1 //: Named values can also be used: let hundred = 100 let tenTimesTen = 10 * 10 let nineTimesTen = 9 * 10
hundred == tenTimesTen
hundred == nineTimesTen
//: - Experiment: Try some comparisons of your own. Can you check if two string values are equal?
//: Find out more ways to compare values on the next page.
More Comparisons
The comparison operator == is very useful, but it would get tedious quickly if you had to check equality against every number. Luckily, there are more comparisons you can make between numbers:
// Less than
1 < 2
2 < 2
3 < 2
// More than 1 > 2 2 > 2 3 > 2 /*: Some comparisons use two symbols, right next to each other, that combine to form one meaning: */ // Not equal 1 != 2 2 != 2 2 != 1
// Less than or equal to
2 <= 2
1 <= 2
3 <= 2
// More than or equal to
1 >= 2
2 >= 2
3 >= 2
/*: Check the results sidebar to see the outcomes of these comparisons 👉.
- note: A helpful way to remember what
>
and `🍰 - callout(Exercise): Practice writing out some comparison statements of your own. What happens if you try to compare non-integer types, like doubles or strings?
- /
//: Learn how to add decision points to your code on the next page. //:
Conditionals
You’ve learned about true and false. You’ve seen how to write comparison statements that can have a result of true or false. The final part of the puzzle is how to make your code do different things depending on these results.
At the start of the playground, you read about reactions to the length of a video. Now it’s time to implement that in code. What you want to happen is this:
If the duration is shorter than 5, say it was too short.
If the duration is greater than or equal to 5, say it was very nice.
The code is similar to how you’d write it in prose:
let videoLength = 3
if videoLength < 5 {
“If I blinked, I’d miss it!”
}
if videoLength >= 5 { "That's lovely." } /*:
This is called an if statement. It works like this:
-
if
… - some code that could be
true
orfalse
istrue
… - run the code inside the braces:
{ ... }
- otherwise, skip it
In the code above, you can see in the results sidebar that the first if statement is run. The code inside the second if statement isn’t executed because the conditions for it aren’t true.
- experiment: Change the value of
videoLength
and see how the new value affects the code that is run. - experiment: What happens if you change the comparison in the first example, so it complains about videos shorter than 10 seconds? What happens if you then set the
videoLength
to 8?
Your second experiment may have had strange results. Head to the next page to straighten them out.
Else
You’ve learned about true and false. You’ve seen how to write comparison statements that can have a result of true or false. The final part of the puzzle is how to make your code do different things depending on these results.
At the start of the playground, you read about reactions to the length of a video. Now it’s time to implement that in code. What you want to happen is this:
If the duration is shorter than 5, say it was too short.
If the duration is greater than or equal to 5, say it was very nice.
The code is similar to how you’d write it in prose:
let videoLength = 3
if videoLength < 5 {
“If I blinked, I’d miss it!”
}
if videoLength >= 5 { "That's lovely." } /*:
This is called an if statement. It works like this:
-
if
… - some code that could be
true
orfalse
istrue
… - run the code inside the braces:
{ ... }
- otherwise, skip it
In the code above, you can see in the results sidebar that the first if statement is run. The code inside the second if statement isn’t executed because the conditions for it aren’t true.
- experiment: Change the value of
videoLength
and see how the new value affects the code that is run. - experiment: What happens if you change the comparison in the first example, so it complains about videos shorter than 10 seconds? What happens if you then set the
videoLength
to 8?
Your second experiment may have had strange results. Head to the next page to straighten them out.
Else If
What if you wanted to show a different message if a video was too long?
There is one last thing you can do with if and else. Here’s how it looks:
let videoLength = 120
if videoLength < 5 { "If I blinked, I'd miss it." } else if videoLength > 500 { "Don't worry, I know a good editor." } else { "That was lovely." } /*: Using `else if` lets you add another conditional statement, which is only checked if the first conditional is `false`. If the `else if` conditional is also `false`, then the code after the final `else` is executed. - experiment: Change the value of `videoLength` and trace the flow of the code through the conditionals.
You can add more than one `else if` statement, but the first one that is `true` will be the one that “wins”: */ let anotherVideoLength = 75000 if anotherVideoLength < 5 { "If I blinked, I'd miss it." } else if anotherVideoLength > 50000 { "This is too long for anyone." } else if anotherVideoLength > 500 { "Don't worry, I know a good editor." } else { "That was lovely." } //: Notice that the final `else if` statement, even though it is `true`, does not get executed. Once a conditional is `true`, the later ones are not checked. The order of your code is very important! //: //: On the next page, learn how to use functions to make complicated decisions look simple. //:
Functions and Decisions
You can use conditionals to write more useful functions. If you have some decision-making code that doesn’t read very nicely or makes things look too complicated, you can wrap it in a function and make it look like you’re asking a question.
For example, imagine your five-person band is playing a gig, and you’ve got 600 pounds of equipment. You and your bandmates each can carry 50 pounds of gear per trip, but if anyone has to make more than two trips, they’ll quit on the spot. So you do some arithmetic:
let bandMemberCount = 5 let gearWeight = 600 let weightPerPerson = 50 let maximumTripCount = 2
if gearWeight < bandMemberCount * weightPerPerson * maximumTripCount { "Rock on." } else { "Everyone quits! Looks like you've got a solo show." } //: Even though this code gives you an accurate answer, it’s not clear what’s happening. Another person may have to read the code multiple times to understand why everyone quit. If the code logic lives inside a function, though, the function's name can help describe the logic of the arithmetic: func bandCanCarryGear(bandMemberCount: Int, gearWeight: Int) -> Bool { let maximumTripCount = 2 let weightPerPerson = 50 let carryingCapacity = bandMemberCount * weightPerPerson * maximumTripCount
return gearWeight < carryingCapacity } //: This approach hides the complexity of what’s happening in the function. Functions that return a `Bool` can be used directly in an if statement, like this: if bandCanCarryGear(bandMemberCount: 5, gearWeight: 600) { "Rock on." } else { "Everyone quits! Looks like you've got a solo show" } //: Now anyone reading the code should be able to understand what it’s doing. (It looks like you need to hire another drummer, or leave some speakers behind.) //: //: Continue your rock and roll adventure on the next page. //:
Remainder Operator
Your band hired that extra member and has gone on tour. But there’s more trouble.
They insist on a bowl of candy in the dressing room every night. If it doesn’t divide exactly between all of them, they’ll quit.
You can use the remainder operator to find out if one number divides evenly into another. The remainder operator % gives the remainder of a division.
4 divided by 2 is 2, with no remainder, so this line equals zero
4 % 2 //: 5 divided by 2 is 2, with a remainder of one, so this line equals one: 5 % 2 //: To find out if the candy can be split evenly among your band members, you have to check if the remainder is zero: let bandMemberCount = 6 let candyCount = 79 if candyCount % bandMemberCount == 0 { "Rock on." } else { "Everyone quits! This is unacceptable!" } //: When reading the code, it’s not completely clear what’s happening. The `%` and `== 0` distract from the question that the code is asking. To make it clearer, you could put the code inside a function: func isCandyAmountAcceptable(bandMemberCount: Int, candyCount: Int) -> Bool { return candyCount % bandMemberCount == 0 } //: As in the previous example, this approach hides the complexity of what’s happening in the function. You can then write the following code: if isCandyAmountAcceptable(bandMemberCount: bandMemberCount, candyCount: candyCount) { "Rock on." } else { "Everyone quits! This is unacceptable!" } //: > In some other programming languages `%` is called the modulo operator and has different behavior for negative numbers. //: //: Now summarize what you’ve learned. //:
Wrap Up
Making decisions and choosing which code to run based on those decisions adds power to your code.
Decisions can be made by comparison statements, which can have a value of either true or false
Comparison statements can be used to run parts of code with the use of if and else
let youWantToPractice = true if youWantToPractice { Go to the exercises! }
Exercise: If Statement Practice
Come to grips with the if statement by rewriting the following comments in code form.
let a = 20 let b = 30 let c = 20
// If a is equal to c, print “a and c are the same”
// If a is less than b, print “b is ahead of a”
// If b is greater than a, print “a is not winning against b”
// If a is less than or equal to c, print “a is either losing to or tied with c”
//: - callout(Exercise): Add code after each comment above to follow the instructions. (For the greater than and less than operators, remember the rule about the hungry mouth.) //: