-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-05-01.qmd
267 lines (205 loc) · 5.35 KB
/
slides-05-01.qmd
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
---
title: "while loop intro (slides)"
format: revealjs
slide-number: true
---
# CSc 110 - Intro to While Loops
## Announcements
* Midterm 1 Febuary 19 -- BRING PHOTO ID
* Modules 1 to 5 -- study guide under [practice problems](practice-01.html) page on website
## While loops
- A **while** loop allows a programmer to repeat code
- You can think of it as an if-statement with the potential to repeat
```{python}
#| eval: false
#| echo: true
statements . . .
while conditionA:
statementA
statementB
. . .
statementN
statements . . .
```
## What will happen?
```{python}
#| eval: false
#| echo: true
number = 15
while number < 50:
print('number is less than 50')
```
## While loops
- What if the condition never evaluates to `False`?
- Infinite loop!
- There are two ways around this:
- Break (do not use in this class!)
- Designing the code such that the condition will eventually become `False`
## What will happen?
To ensure our condition (`number < 50`) will eventually be evaluated as `False`, we need to updated `number` inside our loop:
```{python}
#| eval: false
#| echo: true
number = 15
while number < 50:
print('number is less than 50')
number += 5
print('End')
```
## While loops -- visualization
Go to [Python Tutor](https://pythontutor.com/visualize.html#mode=edit) to visualize how the `while` loop runs.
## While loop -- example
Factorial: 5! = 1 * 2 * 3 * 4 * 5 = 120
```{python}
#| eval: true
#| echo: true
def factorial(n):
result = 1
current = 1
while current <= n:
result = result * current
current += 1
return result
def main():
print( factorial(5) )
print( factorial(6) )
main()
```
## `while` loops table
Consider `n = 5`, start with `result = 1`, `current = 1`:
| `current <= 5` | result = result * current | current += 1 |
| :-------: |:-------: |:-------: |
| True | result = 1 * 1 | current = 1 + 1 |
| True | result = 1 * 2 | current = 2 + 1 |
| True | result = 2 * 3 | current = 3 + 1 |
| True | result = 6 * 4 | current = 4 + 1 |
| True | result = 24 * 5 | current = 5 + 1 |
| False | - | - |
## Write a function
Write a function called `add_up_to` that takes an numeric argument `n`.
The function should add all numbers from 1 to `n` in a while loop, and then (outside the loop) return the sum
```{python}
#| eval: false
#| echo: true
print( add_up_to(5) ) # 15
print( add_up_to(10) ) # 55
```
Name your file `sum_up.py` and submit it to attendance on gradescope
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def add_up_to(n):
sum = 0
current = 0
while current <= n:
sum += current
current += 1
return sum
def main():
print( add_up_to(5) )
print( add_up_to(10) )
main()
```
## Age milestones
Modify `main` function: use a `while` loop to request a valid input from the user.
```{python}
#| eval: false
#| echo: true
def age_milestones(age):
message = ""
if age >= 18:
message += 'You may apply to join the military.'
if age >= 21:
message += ' You may drink.'
if age > 35:
message += ' You may run for president.'
return message
def validate_age(age):
return age.isnumeric()
def main():
str_age = input('How old are you?\n')
if validate_age(str_age):
age = int(str_age)
print(age_milestones(age))
else:
print("Invalid age entered.")
main()
```
## Age milestones continued
Program behavior in your standard output:
```{=html}
<pre style="font-size: 30px">
How old are you?
abc
How old are you?
10abc
How old are you?
55
You may apply to join the military. You may drink. You may
run for president.
</pre>
```
## Age milestones -- solution
Modify `main` function: use a `while` loop to request a valid input from the user.
```{python}
#| eval: false
#| echo: true
def age_milestones(age):
message = ""
if age >= 18:
message += 'You may apply to join the military.'
if age >= 21:
message += ' You may drink.'
if age > 35:
message += ' You may run for president.'
return message
def validate_age(age):
return age.isnumeric()
def main():
str_age = input('How old are you?\n')
while validate_age(str_age) == False:
str_age = input('How old are you?\n')
age = int(str_age)
print(age_milestones(age))
main()
```
## Write functions
1. Write a function `to_do` that takes a numeric argument `temp`.
2. It returns
- 'go for a swim' if is greater equal to `86` and less than `104`
- 'go for a hike' if is greater equal to `68` and less than `86`
- 'stay at home' for all other cases
3. Write a `main` function to request input from user until it is valid (only digits 0-9), print `"Let us"` and the message
## Write functions continued
Program behavior in your standard output:
```{=html}
<pre style="font-size: 30px">
Enter a temperature:
abc
Enter a temperature:
100abc
Enter a temperature:
89
Let us go for a swim
</pre>
```
## Write functions -- solution
```{python}
#| eval: false
#| echo: true
def to_do(temp):
if temp >= 86 and temp < 104:
return "go for a swim"
elif temp >= 68 and temp < 86:
return "go for a hike"
else:
return "stay at home"
def main():
str_temp = input("Enter a temperature:\n")
while str_temp.isnumeric() == False:
str_temp = input("Enter a temperature:\n")
message = to_do(int(str_temp))
print("Let us", message)
main()
```