Skip to content

Commit b3cb4b0

Browse files
committed
chore: ch2 note - assignment expression
1 parent 92c83c1 commit b3cb4b0

File tree

1 file changed

+44
-8
lines changed

1 file changed

+44
-8
lines changed

02-array-seq/array-seq.ipynb

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@
114114
},
115115
{
116116
"cell_type": "code",
117-
"execution_count": 2,
117+
"execution_count": 5,
118118
"metadata": {},
119119
"outputs": [
120120
{
@@ -123,7 +123,7 @@
123123
"[36, 162, 163, 165, 8364, 164]"
124124
]
125125
},
126-
"execution_count": 2,
126+
"execution_count": 5,
127127
"metadata": {},
128128
"output_type": "execute_result"
129129
}
@@ -145,7 +145,7 @@
145145
},
146146
{
147147
"cell_type": "code",
148-
"execution_count": 3,
148+
"execution_count": 6,
149149
"metadata": {},
150150
"outputs": [
151151
{
@@ -154,7 +154,7 @@
154154
"'ABC'"
155155
]
156156
},
157-
"execution_count": 3,
157+
"execution_count": 6,
158158
"metadata": {},
159159
"output_type": "execute_result"
160160
}
@@ -167,7 +167,7 @@
167167
},
168168
{
169169
"cell_type": "code",
170-
"execution_count": 4,
170+
"execution_count": 7,
171171
"metadata": {},
172172
"outputs": [
173173
{
@@ -176,7 +176,7 @@
176176
"[65, 66, 67]"
177177
]
178178
},
179-
"execution_count": 4,
179+
"execution_count": 7,
180180
"metadata": {},
181181
"output_type": "execute_result"
182182
}
@@ -185,9 +185,21 @@
185185
"codes"
186186
]
187187
},
188+
{
189+
"cell_type": "markdown",
190+
"metadata": {},
191+
"source": [
192+
"`:=` 允許你在一個運算式中給變數賦值,且 scope 是封閉的函式 (enclosing function),所以在 listcomp 完成後還可以讀取。例如:\n",
193+
"```python\n",
194+
"if (n := len(data)) > 10:\n",
195+
" print(f\"Data is too long: {n}\")\n",
196+
"```\n",
197+
"這樣就不需要重複 `len(data)` 兩次。"
198+
]
199+
},
188200
{
189201
"cell_type": "code",
190-
"execution_count": 5,
202+
"execution_count": 8,
191203
"metadata": {
192204
"collapsed": false,
193205
"pycharm": {
@@ -201,7 +213,7 @@
201213
"67"
202214
]
203215
},
204-
"execution_count": 5,
216+
"execution_count": 8,
205217
"metadata": {},
206218
"output_type": "execute_result"
207219
}
@@ -211,6 +223,30 @@
211223
"last"
212224
]
213225
},
226+
{
227+
"cell_type": "code",
228+
"execution_count": 2,
229+
"metadata": {},
230+
"outputs": [
231+
{
232+
"name": "stdout",
233+
"output_type": "stream",
234+
"text": [
235+
"inside demo: 6\n",
236+
"global total: 0\n"
237+
]
238+
}
239+
],
240+
"source": [
241+
"def demo(data, total):\n",
242+
" _ = [total := total + v for v in data]\n",
243+
" print(\"inside demo:\", total)\n",
244+
"\n",
245+
"total = 0\n",
246+
"demo([1,2,3], 0)\n",
247+
"print(\"global total:\", total)"
248+
]
249+
},
214250
{
215251
"cell_type": "markdown",
216252
"metadata": {},

0 commit comments

Comments
 (0)