-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-04-02.qmd
301 lines (223 loc) · 6.71 KB
/
slides-04-02.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
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
---
title: "if statements (slides)"
format: revealjs
slide-number: true
---
# CSc 110 If statements
## Expression vs Statement
- *Expression* evaluates to value
- *Statement* does something
```{python}
#| echo: true
#| eval: false
3 + 4 # expression
print(3 + 4) # statement
a = 8 # statement
a != 9 # expression
print(a) # statement
```
## The if statement
- If statements can be used to **run code conditionally**
- **Before if-statements:** Code has pretty much just run in a straight line
- **With ifs:** Can run code optionally, depending on the value of a condition
This means our code can **branch** in different directions
## The if statement
```{=html}
<pre>
if condition:
statement 1
statement 2
. . .
statement N
</pre>
```
The condition is an expression that is evaluated to a bool.
Example:
```{python}
#| eval: false
#| echo: true
def greeting(name):
if name == "Bond":
return "Welcome on board 007."
else:
return "Hello, " + name
def main():
user_name = input("Enter your name:\n")
print( greeting(user_name) )
main()
```
## Improve the function
Instead of checking if the name entered is "Bond", also check whether the name is "James Bond".
## Conditional execution
The computer program branches out, or makes decisions
```{python}
#| echo: true
#| eval: true
def greater_than_zero(n):
if n > 0:
return "Greater than zero"
else:
return "Not greater than zero"
def main():
result = greater_than_zero(4)
print(result)
result = greater_than_zero(0)
print(result)
result = greater_than_zero(-3)
print(result)
main()
```
## Write a function
Write a Python function called `absolute` that takes one numeric argument (integer or float) `n`
and returns the absolute value of `n`: if `n` is positive, it results `n`, if `n` is negative, it returns `n * -1`
Test cases:
```{python}
#| echo: true
#| eval: false
print( absolute(4) ) # 4
print( absolute(-4) ) # 4
print( absolute(0) ) # 0
```
## Write a function -- solution 1
```{python}
#| echo: true
#| eval: true
def absolute(n):
if n > 0:
return n
else:
return -n
def main():
print( absolute(4) )
print( absolute(-4) )
print( absolute(0) )
main()
```
## Write a function -- solution 2
```{python}
#| echo: true
#| eval: true
def absolute(n):
if n > 0:
return n
return -n
def main():
print( absolute(4) )
print( absolute(-4) )
main()
```
Which lines run in the function `absolute`?
- When expression `n > 0` is `True`, line `3` runs (`return` is used to exit a function and returns a value)
- When expression `n > 0` is `False`, line `4` runs (skip line `3`)
## Write a function
1. Function `age_milestones` takes one integer `age`
2. It returns:
- 'You may apply to join the military.' if `age` is greater or equal to `18`
- 'You may drink.' if `age` greater or equal to `21`
- 'You may run for president.' if `age` greater or equal to `35`
3. The latter conditions include former so concatenate them
```{python}
#| echo: true
#| eval: false
print( age_milestones(18) ) # You may apply to join the military.
print( age_milestones(30) ) # You may apply to join the military. You may drink.
print( age_milestones(0) ) #
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def age_milestones(age):
'''
This function prints an informative message based on,
a person's age.
Args:
age: integer representing a person's age
Returns:
A string with a message to the user
'''
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 main():
print( age_milestones(18) ) # You may apply to join the military.
print( age_milestones(30) ) # You may apply to join the military. You may drink.
print( age_milestones(0) ) #
main()
```
## Quiz 04
<center>
<div class="cleanslate w24tz-current-time w24tz-large" style="display: inline-block !important; visibility: hidden !important; min-width:300px !important; min-height:145px !important;"><a href="//24timezones.com/Tucson/time" style="text-decoration: none" class="clock24" id="tz24-1695057604-c1393-eyJob3VydHlwZSI6IjEyIiwic2hvd2RhdGUiOiIwIiwic2hvd3NlY29uZHMiOiIwIiwiY29udGFpbmVyX2lkIjoiY2xvY2tfYmxvY2tfY2I2NTA4ODZjNDg0OWVlIiwidHlwZSI6ImRiIiwibGFuZyI6ImVuIn0=" title="World Time :: Tucson" target="_blank" rel="nofollow"></a>current time<div id="clock_block_cb650886c4849ee"></div></div>
<script type="text/javascript" src="//w.24timezones.com/l.js" async></script>
</center>
You have 10 minutes to complete the quiz.
No need to write `main()` function.
# Input validation
## String methods
In addition to having built-in **functions** (`len()`, `print()`, `int()`, `float()`, etc.), Python also has a number of **methods** we will be using in this class.
Check the [documentation](https://docs.python.org/3/library/stdtypes.html#str.isnumeric) for string methods and read what `.isnumeric()` does.
## Validating numbers
- The `input()` function always returns a `string`
- We can use the string built-in method `.isnumeric()` to determine if a string represents an integer
- `.isnumeric()` returns True if all the characters are numeric (0-9)
Try these out:
```{python}
#| eval: true
#| echo: true
name = "Jimmy42"
name.isnumeric()
```
```{python}
#| eval: false
#| echo: true
age = 37
age.isnumeric() # this throws an error
```
## Write a validation function
Write a Python function `validate_age` that takes a string argument `age`.
It returns `True` if `age` contains only 0-9 digit characters, and `False` otherwise.
In your previous file for age milestone, in the `main` function:
- call `input()` to type an age
- call `validate_age` to validate your input
- if it is `True`, call `age_milestones` to print messages
- if it is `False`, print 'Invalid age entered'
## Age milestones
```{python}
#| eval: false
#| echo: true
def age_milestones(age):
'''
This function prints an informative message based on,
a person's age.
Args:
age: integer representing a person's age
Returns:
A string with a message to the user
'''
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():
'''
This functions takes input from the user and calls the
check_age() functiont to print a message
'''
age = input('How old are you?\n')
if validate_age(age):
print(age_milestones(int(age)))
else:
print("Invalid age entered")
main()
```