-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05-conditionals.Rmd
More file actions
346 lines (246 loc) · 10.7 KB
/
Copy path05-conditionals.Rmd
File metadata and controls
346 lines (246 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# Conditionals and Making Choices
## `if` Statements
Many times in programming, we want to take a certain action only if a certain condition is satisfied.\
To do this, we can use conditional statements. The most commonly used format of a conditional statement in programming is an `if` statement, which is often combined with an `else` statement.\
This structure tells the computer to check a condition and the next step depends on whether the condition is true or false.
It takes the basic form of:
```
IF (condition A is TRUE)
do something
```
In terms of our cheesy mashed potatoes algorithm, an `if` statement might look like this
```
ingredient <- cheddar cheese
IF (ingredient is (a type of hard cheese))
grate(ingredient)
```
In that example, we've told the computer what to do _if_ the condition is true. We can also specify what to do if the condition is false.
For our cheesy mashed potatoes algorithm, we may want to cut cheese into cubes if it is not a hard cheese:
```
ingredient <- cheddar cheese
IF (ingredient is (a type of hard cheese))
grate(ingredient)
ELSE
cube(ingredient)
```
In pseudocode, a complete `if else` statement would look like:
```
IF (condition A is TRUE)
do something
ELSE
do something different
```
Here, `else` is used equivalent to "if not true", meaning `A == FALSE`.\
Furthermore, we are not limited to a single `TRUE`/`FALSE` check in an `if else` statement, where actions are limited to _"do something if true, in **all** other scenarios do something different"_. The `else if` (written as `elif` in some programming languages) concept allows us to add another sequential check if the `if` statement is not true.
An updated cheesy mashed potato narrative statement could be that if we have a hard cheese, we want to grate it, if we have a soft cheese we want to cube it, and if we have something that is neither hard nor soft cheese, we don't put it in the potatoes.
```
IF (ingredient is (a type of hard cheese))
grate(ingredient)
ELSE IF (ingredient is (a type of soft cheese))
cube(ingredient)
ELSE
don't use
```
In pseudocode, this updated statement would look like:
```
IF (condition A is TRUE)
do something
ELSE IF (condition B is true)
do something different
ELSE
do something even more different
```
## Exercise - Popcorn `if else` pseudocode
_Timing: 5 minutes_
Let's try a similar example with the popcorn algorithm from section 2.
Write out an `if else` statement specifying what appliance to use in the case of
different popcorn types: bagged popcorn (`bagged`), popcorn in an aluminum pan (`jiffy_pop`),
and loose kernels.\
Then, write out an `if, else if, else` statement that includes use of an air fryer for loose kernels.\
<details>
<summary>Example statement</summary>
```
IF (popcorn_type is `bagged`)
use microwave
ELSE (popcorn_type is `jiffy_pop`)
use stove
IF (popcorn_type is `bagged`)
use microwave
ELSE IF (popcorn_type is `jiffy_pop`)
use stove
ELSE
use air_fryer
```
Your version may look different, and that's fine! The fun of pseudocode is practicing with the logic of code, rather than getting lost in the details.
</details>\
## Comparing Things and Booleans
In programming, most things boil down to `true` or `false`. (Sometimes you may see true/false capitalized as `TRUE` and `FALSE`, but the concept is the same. We'll use both ways throughout.). `TRUE` and `FALSE` are formally a boolean data type. Programming languages use boolean operators and comparison operators to determine if a statement is `TRUE` or `FALSE` in order to make actions.
Common Boolean operators are:\
- `and` (may also see the ampersand, `&` or `&&` used)
- `or` (may also see the pipe symbol, `|` or `||` used)
- `not` (may also see `!` to indicate negation, for instance `!=` for "not equal")
Common comparison operators are:
- `>` Greater-than
- `<` Less-than
- `>=` Greater-than or equal-to
- `<=` Less-than or equal-to
- `==` *is equal to*
- you should note that `==` is very different from `=`. `==` is the comparison operator, while `=` is an assignment operator. Another assignment operator you may have noticed us using is `<-` which is commonly used in R.
- To practice, you can replace the words "is equal to" or "is assigned the value of" appropriately.
- `A = 6` (`A` is assigned the value of `6`)
- `B <- 8` (`B` is assigned the value of `8`)
- `B == 7` ("`B` is equal to `7`", where the statement is then evaluated to be `true` or `false`. In this case, it is `false`)
## Conditional Statements in Practice
Let's look at some examples of conditional statements in practice, first by using our cheesy mashed potatoes example, and then with actual code.
First, for our recipe example:
```
if cheese == hard:
print("Grate the cheese.")
else if cheese == hard:
print("Cube the cheese.")
else:
print("Do not use this in this recipe.")
```
If we have `cheese <- parmesan` we would expect this statement to print out `Grate the cheese`. If we have `cheese <- brie` we would expect the output to be `Cube the cheese`. And if we have `cheese <- broccoli` we would expect the output to be `Do not use this in the recipe`.
Sidenote: yes, this assumes that somewhere we have specified a list of hard cheese and soft cheeses. For this pseudocode example, we're using our cheese-based expertise to draw conclusions, but as we've covered, we would never assume a computer would know which cheeses were hard or soft!
### Exercise: `ifelse` Trace
_Timing: 5 minutes_
_For this exercise, want you to type the answer in the chat, but don't press enter until we tell you. We'll say, _3, 2, 1, enter_ then you press enter when we say _enter_._
For the code below, what will be the printed output?
```
x <- 37
y <- 42
if x == y:
print("values are equal")
else if x > y:
print("x greater than y")
else:
print("x must be less than y")
```
<details>
<summary>Answer</summary>
x must be less than y
</details>\
What would be the answer if we instead set `x` and `y` to:
```
x <- 75
y <- 9
if x == y:
print("values are equal")
else if x > y:
print("x greater than y")
else:
print("x must be less than y")
```
<details>
<summary>Answer</summary>
x greater than y
</details>\
## Caveats
We're going to cover some more formal processes and syntax. While this won't impact working with pseudocode, it is important to know when working with the computer.
### Order of operations in conditionals
Order of operations is critical for conditionals. The computer will go through each condition _in order_, so if an early condition is found as `true`, the statement will conclude there and not check the other conditions.
```
if (cheddar == cheese) OR (brie == cheese) OR (broccoli == cheese):
print("This is cheesy")
```
In this case, because `cheddar == cheese` is `true`, the computer doesn't bother checking the other two statements.
### Clarity and Order of Operations in math statements
Most of us know the standard order of operation in a math problem (PEMDAS), and most computer languages do, too.
` 3 + 10 * 2` is solved as `23` (and not `26`)
and so we don't need parentheses, but it is good practice to use parentheses to make your code more readable and clear.
` 3 + (10 * 2)` is preferred over ` 3 + 10 * 2`
just as
`(cheddar == cheese) OR (brie == cheese) OR (broccoli == cheese)`
is easier to read than
`cheddar == cheese OR brie == cheese OR broccoli == cheese`
### Matching parentheses
For complex nested conditionals, be sure to use parentheses, and be sure parentheses are matched properly.
The code below, without a closing parentheses after "equal", will continue to expect input.
```
if (x == y)
print("values are equal"
```
As far as the programming language is concerned, you haven't finished this `if` statement. So, depending on the language, it might wait to run until you have "completed your thought", so to speak, and provided the syntax (here the end paren `)`) indicating that this statement is complete and the program is ready to run.
Or if you have mismatched parentheses, the computer might give you an error message.
<hr>
Here's another example of fun with parentheses:
```
if (x == y)
print("values are equal"))
```
In this case, there is an extra closing parentheses `)` after `print("values are equal")` that doesn't have a matching `(` anywhere in the statement. The resulting error would look like:
```
Error: unexpected ')' in:
"if (x == y) {
print("values are equal"))"
```
## Language examples: Formatting may vary
Much like with `for` loops, programming languages may have specific formatting for conditional statements. This may mean certain brackets must be used, new lines are required between sections, or tab indents are needed.
**Python** requires indentation for code blocks. Code blocks in different structures must be aligned with the same indentation.
Programming structures, such as `if`, `else`, `elif`, or `for` expects `:` at the end of each statement with the subsequent code block indented by one
```python
if x == y:
print("values are equal")
elif x > y:
print("x greater than y")
else:
print("x must be less than y")
```
<hr>
**R** makes use of curly brackets `{}` to indicate each section of an `if else` statement. R does not require indentation for code blocks; however, indentation is used because it's easier for humans to read!
```r
if (x == y) {
print("values are equal")
} else if (x > y) {
print("x greater than y")
} else {
print("x must be less than y")
}
```
<hr>
**C/C++** syntax looks a lot like R, but requires semicolons at the end of each line to be executed in a code block and uses `cout` rather than `print` to specify what should be returned in the console.
```c
if (x == y) {
cout << "values are equal";
} else if (x > y) {
cout << "x greater than y";
} else {
cout << "x must be less than y";
}
```
<hr>
**PHP** is very similar to C/C++ with curly brackets and semicolons, but uses `echo` rather than `cout`.
```php
if (x == y) {
echo "values are equal";
} elseif (x > y) {
echo "x greater than y";
} else {
echo "x must be less than y";
}
```
<hr>
Here's a new language: **Bash**. This language is often used from the command line to perform operations on files. With **Bash**, you need to be careful of spaces around your operators and parentheses. (cheatsheets https://ss64.com/bash/if.html https://devhints.io/bash#conditionals)
This Bash script example compares numbers
```bash
if (( $x == $y )) ; then
echo "values are equal"
elif (( $x > $y )) ; then
echo "x greater than y"
else
echo "x must be less than y"
fi
```
This Bash script example compares text
```bash
if [[ "$x" == "$y" ]] ; then
echo "the text in x is the same as y"
else
echo "the text in x is not the same as y"
fi
```
<hr>
### Challenge
- What are some of the differences you can spot between the different languages?
- What are the similarities?