@@ -53,7 +53,7 @@ print(y)
53
53
* Functions allow you to:
54
54
+ Reuse code
55
55
+ Break problems into smaller pieces
56
- + Scope defined by indentation
56
+ * Scope defined by indentation
57
57
* Defined using the ` def ` keyword
58
58
* Can take inputs (arguments) and return outputs
59
59
:::
@@ -101,6 +101,7 @@ def is_valid_password(password):
101
101
``` {python}
102
102
#| echo: true
103
103
#| output-location: fragment
104
+ #| code-line-numbers: "|1|2,3|4,5|"
104
105
def is_valid_password(password):
105
106
if len(password) >= 8:
106
107
return True
@@ -215,7 +216,7 @@ def longer_string(str1, str2=""):
215
216
``` {python}
216
217
#| echo: true
217
218
#| output-location: fragment
218
- #| code-line-numbers: "|1|2,4 |"
219
+ #| code-line-numbers: "|1|2,3|4,5|7 |"
219
220
220
221
def longer_string(str1, str2=""):
221
222
if len(str1) > len(str2):
@@ -225,8 +226,8 @@ def longer_string(str1, str2=""):
225
226
226
227
print(long_str)
227
228
228
- print( longer_string("apple", "banana") )
229
- print( longer_string("apple") )
229
+ longer_string("apple", "banana")
230
+ longer_string("apple")
230
231
```
231
232
232
233
## Using ` * ` and ` ** ` {.smaller}
@@ -241,26 +242,42 @@ print(longer_string("apple"))
241
242
``` {python}
242
243
#| echo: true
243
244
#| output-location: fragment
245
+ #| code-line-numbers: "|1|2,3|5,6|8,9|11,12|"
244
246
def my_func(*args, **kwargs):
245
- print(f"Unpacking list : {args}")
246
- print(f"Unpacking dictionary : {kwargs}")
247
+ print(f"Unpacking positional arguments : {args}")
248
+ print(f"Unpacking keyword arguments : {kwargs}")
247
249
248
250
my_list = [1, 2, 3, 4, 5]
249
251
my_dict = {'a': 1, 'b': 2, 'c': 3}
250
252
251
- print("Unpacking list:")
252
253
my_func(*my_list)
253
254
254
- print("Unpacking dictionary:")
255
255
my_func(**my_dict)
256
256
```
257
257
:::
258
258
259
+ ## Using ` * ` and ` ** ` {.smaller}
260
+
261
+ ::: {.fragment .fade-in}
262
+ ``` {python}
263
+ #| echo: true
264
+ #| output-location: fragment
265
+ def my_func(*args, **kwargs):
266
+ print(f"Unpacking positional arguments: {args}")
267
+ print(f"Unpacking keyword arguments: {kwargs}")
268
+
269
+ my_func(1, 'a', 3.14)
270
+ my_func(name="John", age=30)
271
+ my_func(1, 2, 3, name="Jane", city="New York")
272
+ ```
273
+ :::
274
+
259
275
## How are ` *args ` and ` **kwargs ` useful? {.smaller}
260
276
:::: {.columns}
261
277
::: {.column width="55%"}
262
278
::: {.incremental .smaller}
263
- * ` *args ` and ` **kwargs ` are useful when you don't know how many arguments will be passed to the function
279
+ * ` *args ` and ` **kwargs ` are useful when you don't know which arguments will be passed to the function
280
+ * Or when you wrap another function and want to pass all arguments to the wrapped function
264
281
:::
265
282
266
283
:::
0 commit comments