├── .gitignore
├── 01calc.ipynb
├── 02variable.ipynb
├── 03control.ipynb
├── 04function.ipynb
├── 05module.ipynb
├── 06list.ipynb
├── 07tuple.ipynb
├── 08str.ipynb
├── 09dict.ipynb
├── 10set.ipynb
├── 11file.ipynb
├── 12immutable.ipynb
├── 13class.ipynb
├── 14exception.ipynb
├── 15iterator.ipynb
├── 16numpy1.ipynb
├── 17numpy2.ipynb
├── 18plot.ipynb
├── LICENSE.txt
├── README.md
├── _config.yml
├── _toc.yml
├── assets
└── image
│ ├── colab-clean.png
│ ├── colab-code.png
│ ├── colab-insert-text.png
│ ├── colab-new.png
│ ├── colab-rename.png
│ ├── colab-save.png
│ ├── colab-text.png
│ ├── colab-upload.png
│ ├── jupyter-lab.png
│ ├── jupyter-notebook.png
│ ├── jupyter-notebook2.png
│ ├── logo.png
│ └── scatter.gif
├── decorator.ipynb
├── index.md
├── jupyter.ipynb
├── material
├── card-a4.ai
└── python-note.png
├── modules.ipynb
├── optim.py
├── optim2.py
├── references.md
├── requirements.txt
└── tools
├── build.py
├── update-license.py
└── upload.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/01calc.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 基本的な計算"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "## Pythonことはじめ"
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "文字列はシングルクォーテーション(`'`)、またはダブルクォーテーション(`\"`)で囲む。出力するには`print()`を用いる。改行文字`'\\n'`を末尾に付けなくても改行される。"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {},
28 | "outputs": [
29 | {
30 | "name": "stdout",
31 | "output_type": "stream",
32 | "text": [
33 | "Hello, world!\n"
34 | ]
35 | }
36 | ],
37 | "source": [
38 | "print('Hello, world!')"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "Jupyter Notebookなどの対話的シェルでは、最後に書かれた式を評価した結果が出力される。"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 2,
51 | "metadata": {},
52 | "outputs": [
53 | {
54 | "data": {
55 | "text/plain": [
56 | "'Hello, world!!!'"
57 | ]
58 | },
59 | "execution_count": 2,
60 | "metadata": {},
61 | "output_type": "execute_result"
62 | }
63 | ],
64 | "source": [
65 | "'Hello, world!!!'"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {
71 | "editable": true,
72 | "slideshow": {
73 | "slide_type": ""
74 | },
75 | "tags": []
76 | },
77 | "source": [
78 | "`#`に続く記述はコメントとして扱われ、実行されない。処理内容の説明などを自由に記述できる。"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 3,
84 | "metadata": {
85 | "editable": true,
86 | "slideshow": {
87 | "slide_type": ""
88 | },
89 | "tags": []
90 | },
91 | "outputs": [
92 | {
93 | "name": "stdout",
94 | "output_type": "stream",
95 | "text": [
96 | "Hello, world!\n"
97 | ]
98 | }
99 | ],
100 | "source": [
101 | "# 'Hello, world!'という文字列を表示する。\n",
102 | "print('Hello, world!')"
103 | ]
104 | },
105 | {
106 | "cell_type": "markdown",
107 | "metadata": {
108 | "editable": true,
109 | "slideshow": {
110 | "slide_type": ""
111 | },
112 | "tags": []
113 | },
114 | "source": [
115 | "## 四則演算\n",
116 | "\n",
117 | "加算は`+`、減算は`-`、乗算は`*`、除算は`/`である。除算`/`の計算結果は常に浮動小数点数となる。"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": 4,
123 | "metadata": {
124 | "editable": true,
125 | "slideshow": {
126 | "slide_type": ""
127 | },
128 | "tags": []
129 | },
130 | "outputs": [
131 | {
132 | "data": {
133 | "text/plain": [
134 | "11"
135 | ]
136 | },
137 | "execution_count": 4,
138 | "metadata": {},
139 | "output_type": "execute_result"
140 | }
141 | ],
142 | "source": [
143 | "9 + 2"
144 | ]
145 | },
146 | {
147 | "cell_type": "code",
148 | "execution_count": 5,
149 | "metadata": {},
150 | "outputs": [
151 | {
152 | "data": {
153 | "text/plain": [
154 | "7"
155 | ]
156 | },
157 | "execution_count": 5,
158 | "metadata": {},
159 | "output_type": "execute_result"
160 | }
161 | ],
162 | "source": [
163 | "9 - 2"
164 | ]
165 | },
166 | {
167 | "cell_type": "code",
168 | "execution_count": 6,
169 | "metadata": {},
170 | "outputs": [
171 | {
172 | "data": {
173 | "text/plain": [
174 | "18"
175 | ]
176 | },
177 | "execution_count": 6,
178 | "metadata": {},
179 | "output_type": "execute_result"
180 | }
181 | ],
182 | "source": [
183 | "9 * 2"
184 | ]
185 | },
186 | {
187 | "cell_type": "code",
188 | "execution_count": 7,
189 | "metadata": {},
190 | "outputs": [
191 | {
192 | "data": {
193 | "text/plain": [
194 | "4.5"
195 | ]
196 | },
197 | "execution_count": 7,
198 | "metadata": {},
199 | "output_type": "execute_result"
200 | }
201 | ],
202 | "source": [
203 | "9 / 2"
204 | ]
205 | },
206 | {
207 | "cell_type": "markdown",
208 | "metadata": {},
209 | "source": [
210 | "除算の結果を整数で求めたいときは`//`を使う。"
211 | ]
212 | },
213 | {
214 | "cell_type": "code",
215 | "execution_count": 8,
216 | "metadata": {},
217 | "outputs": [
218 | {
219 | "data": {
220 | "text/plain": [
221 | "4"
222 | ]
223 | },
224 | "execution_count": 8,
225 | "metadata": {},
226 | "output_type": "execute_result"
227 | }
228 | ],
229 | "source": [
230 | "9 // 2"
231 | ]
232 | },
233 | {
234 | "cell_type": "markdown",
235 | "metadata": {},
236 | "source": [
237 | "演算子`//`の間に空白を入れると文法エラー(syntax error)となる。"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": 9,
243 | "metadata": {
244 | "tags": [
245 | "raises-exception"
246 | ]
247 | },
248 | "outputs": [
249 | {
250 | "ename": "SyntaxError",
251 | "evalue": "invalid syntax (333318335.py, line 1)",
252 | "output_type": "error",
253 | "traceback": [
254 | "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_206347/333318335.py\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m 9 / / 2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
255 | ]
256 | }
257 | ],
258 | "source": [
259 | "9 / / 2"
260 | ]
261 | },
262 | {
263 | "cell_type": "markdown",
264 | "metadata": {},
265 | "source": [
266 | "剰余算(割ったときの余り)は`%`で求める。"
267 | ]
268 | },
269 | {
270 | "cell_type": "code",
271 | "execution_count": 10,
272 | "metadata": {},
273 | "outputs": [
274 | {
275 | "data": {
276 | "text/plain": [
277 | "1"
278 | ]
279 | },
280 | "execution_count": 10,
281 | "metadata": {},
282 | "output_type": "execute_result"
283 | }
284 | ],
285 | "source": [
286 | "9 % 2"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": 11,
292 | "metadata": {},
293 | "outputs": [
294 | {
295 | "data": {
296 | "text/plain": [
297 | "0"
298 | ]
299 | },
300 | "execution_count": 11,
301 | "metadata": {},
302 | "output_type": "execute_result"
303 | }
304 | ],
305 | "source": [
306 | "10 % 2"
307 | ]
308 | },
309 | {
310 | "cell_type": "markdown",
311 | "metadata": {},
312 | "source": [
313 | "累乗は`**`で求める。"
314 | ]
315 | },
316 | {
317 | "cell_type": "code",
318 | "execution_count": 12,
319 | "metadata": {},
320 | "outputs": [
321 | {
322 | "data": {
323 | "text/plain": [
324 | "128"
325 | ]
326 | },
327 | "execution_count": 12,
328 | "metadata": {},
329 | "output_type": "execute_result"
330 | }
331 | ],
332 | "source": [
333 | "2 ** 7"
334 | ]
335 | },
336 | {
337 | "cell_type": "markdown",
338 | "metadata": {},
339 | "source": [
340 | "演算子`**`の間に空白を入れると文法エラーとなる。"
341 | ]
342 | },
343 | {
344 | "cell_type": "code",
345 | "execution_count": 13,
346 | "metadata": {
347 | "tags": [
348 | "raises-exception"
349 | ]
350 | },
351 | "outputs": [
352 | {
353 | "ename": "SyntaxError",
354 | "evalue": "invalid syntax (3091056297.py, line 1)",
355 | "output_type": "error",
356 | "traceback": [
357 | "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_206347/3091056297.py\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m 2 * * 7\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
358 | ]
359 | }
360 | ],
361 | "source": [
362 | "2 * * 7"
363 | ]
364 | },
365 | {
366 | "cell_type": "markdown",
367 | "metadata": {},
368 | "source": [
369 | "計算(演算子)の優先順位は数学の慣習に近い。優先順位は`**` > `-` (負の数を表現) > `*`, `/`, `//`, `%` > `+`, `-`"
370 | ]
371 | },
372 | {
373 | "cell_type": "code",
374 | "execution_count": 14,
375 | "metadata": {},
376 | "outputs": [
377 | {
378 | "data": {
379 | "text/plain": [
380 | "-0.5"
381 | ]
382 | },
383 | "execution_count": 14,
384 | "metadata": {},
385 | "output_type": "execute_result"
386 | }
387 | ],
388 | "source": [
389 | "3 + 7 / -2"
390 | ]
391 | },
392 | {
393 | "cell_type": "markdown",
394 | "metadata": {},
395 | "source": [
396 | "括弧`(` `)`を使って演算子の優先順位を変更できる。"
397 | ]
398 | },
399 | {
400 | "cell_type": "code",
401 | "execution_count": 15,
402 | "metadata": {},
403 | "outputs": [
404 | {
405 | "data": {
406 | "text/plain": [
407 | "-5.0"
408 | ]
409 | },
410 | "execution_count": 15,
411 | "metadata": {},
412 | "output_type": "execute_result"
413 | }
414 | ],
415 | "source": [
416 | "(3 + 7) / -2"
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "metadata": {},
422 | "source": [
423 | "## 浮動小数点数"
424 | ]
425 | },
426 | {
427 | "cell_type": "markdown",
428 | "metadata": {},
429 | "source": [
430 | "数に小数点が含まれると、その数は自動的に浮動小数点数で表現される(浮動小数点数を評価したので、出力に小数点が付いている)。"
431 | ]
432 | },
433 | {
434 | "cell_type": "code",
435 | "execution_count": 16,
436 | "metadata": {
437 | "editable": true,
438 | "slideshow": {
439 | "slide_type": ""
440 | },
441 | "tags": []
442 | },
443 | "outputs": [
444 | {
445 | "data": {
446 | "text/plain": [
447 | "1.0"
448 | ]
449 | },
450 | "execution_count": 16,
451 | "metadata": {},
452 | "output_type": "execute_result"
453 | }
454 | ],
455 | "source": [
456 | "1.0"
457 | ]
458 | },
459 | {
460 | "cell_type": "markdown",
461 | "metadata": {
462 | "editable": true,
463 | "slideshow": {
464 | "slide_type": ""
465 | },
466 | "tags": []
467 | },
468 | "source": [
469 | "これに対し、単に`1`と書くと浮動小数点数にならず、整数で表現される(整数を評価したので、出力に小数点が付いていない)。"
470 | ]
471 | },
472 | {
473 | "cell_type": "code",
474 | "execution_count": 17,
475 | "metadata": {
476 | "editable": true,
477 | "slideshow": {
478 | "slide_type": ""
479 | },
480 | "tags": []
481 | },
482 | "outputs": [
483 | {
484 | "data": {
485 | "text/plain": [
486 | "1"
487 | ]
488 | },
489 | "execution_count": 17,
490 | "metadata": {},
491 | "output_type": "execute_result"
492 | }
493 | ],
494 | "source": [
495 | "1"
496 | ]
497 | },
498 | {
499 | "cell_type": "markdown",
500 | "metadata": {
501 | "editable": true,
502 | "slideshow": {
503 | "slide_type": ""
504 | },
505 | "tags": []
506 | },
507 | "source": [
508 | "整数値を浮動小数点数で表現したいとき、小数点を末尾に付け、`0`を省略する書き方もある(`1.0`と書くのと同じである)。"
509 | ]
510 | },
511 | {
512 | "cell_type": "code",
513 | "execution_count": 18,
514 | "metadata": {
515 | "editable": true,
516 | "slideshow": {
517 | "slide_type": ""
518 | },
519 | "tags": []
520 | },
521 | "outputs": [
522 | {
523 | "data": {
524 | "text/plain": [
525 | "1.0"
526 | ]
527 | },
528 | "execution_count": 18,
529 | "metadata": {},
530 | "output_type": "execute_result"
531 | }
532 | ],
533 | "source": [
534 | "1."
535 | ]
536 | },
537 | {
538 | "cell_type": "markdown",
539 | "metadata": {
540 | "editable": true,
541 | "slideshow": {
542 | "slide_type": ""
543 | },
544 | "tags": []
545 | },
546 | "source": [
547 | "指数を用いた浮動小数点 $a \\times 10^b$ は`e`を用いて表現できる(C言語と同様)。例えば、$6.02 \\times 10^{23}$は、"
548 | ]
549 | },
550 | {
551 | "cell_type": "code",
552 | "execution_count": 19,
553 | "metadata": {},
554 | "outputs": [
555 | {
556 | "data": {
557 | "text/plain": [
558 | "6.02e+23"
559 | ]
560 | },
561 | "execution_count": 19,
562 | "metadata": {},
563 | "output_type": "execute_result"
564 | }
565 | ],
566 | "source": [
567 | "6.02e23"
568 | ]
569 | },
570 | {
571 | "cell_type": "markdown",
572 | "metadata": {},
573 | "source": [
574 | "$1.0 \\times 10^{-4}$は、"
575 | ]
576 | },
577 | {
578 | "cell_type": "code",
579 | "execution_count": 20,
580 | "metadata": {},
581 | "outputs": [
582 | {
583 | "data": {
584 | "text/plain": [
585 | "0.0001"
586 | ]
587 | },
588 | "execution_count": 20,
589 | "metadata": {},
590 | "output_type": "execute_result"
591 | }
592 | ],
593 | "source": [
594 | "1e-4"
595 | ]
596 | },
597 | {
598 | "cell_type": "markdown",
599 | "metadata": {
600 | "editable": true,
601 | "slideshow": {
602 | "slide_type": ""
603 | },
604 | "tags": []
605 | },
606 | "source": [
607 | "式の中に浮動小数点数が含まれる場合、計算結果(式の評価結果)も浮動小数点数になる。"
608 | ]
609 | },
610 | {
611 | "cell_type": "code",
612 | "execution_count": 21,
613 | "metadata": {
614 | "editable": true,
615 | "slideshow": {
616 | "slide_type": ""
617 | },
618 | "tags": []
619 | },
620 | "outputs": [
621 | {
622 | "data": {
623 | "text/plain": [
624 | "-7.0"
625 | ]
626 | },
627 | "execution_count": 21,
628 | "metadata": {},
629 | "output_type": "execute_result"
630 | }
631 | ],
632 | "source": [
633 | "-9.0 + 2"
634 | ]
635 | },
636 | {
637 | "cell_type": "markdown",
638 | "metadata": {},
639 | "source": [
640 | "浮動小数点数に対して`//`を使うと、結果は整数ではなく浮動小数点数となる。"
641 | ]
642 | },
643 | {
644 | "cell_type": "code",
645 | "execution_count": 22,
646 | "metadata": {},
647 | "outputs": [
648 | {
649 | "data": {
650 | "text/plain": [
651 | "-5.0"
652 | ]
653 | },
654 | "execution_count": 22,
655 | "metadata": {},
656 | "output_type": "execute_result"
657 | }
658 | ],
659 | "source": [
660 | "-9.0 // 2"
661 | ]
662 | },
663 | {
664 | "cell_type": "markdown",
665 | "metadata": {},
666 | "source": [
667 | "## 2進数と16進数"
668 | ]
669 | },
670 | {
671 | "cell_type": "markdown",
672 | "metadata": {},
673 | "source": [
674 | "2進数は先頭に`0b`を付ける。"
675 | ]
676 | },
677 | {
678 | "cell_type": "code",
679 | "execution_count": 23,
680 | "metadata": {},
681 | "outputs": [
682 | {
683 | "data": {
684 | "text/plain": [
685 | "44"
686 | ]
687 | },
688 | "execution_count": 23,
689 | "metadata": {},
690 | "output_type": "execute_result"
691 | }
692 | ],
693 | "source": [
694 | "0b00101100"
695 | ]
696 | },
697 | {
698 | "cell_type": "markdown",
699 | "metadata": {},
700 | "source": [
701 | "16進数は先頭に`0x`を付ける。"
702 | ]
703 | },
704 | {
705 | "cell_type": "code",
706 | "execution_count": 24,
707 | "metadata": {},
708 | "outputs": [
709 | {
710 | "data": {
711 | "text/plain": [
712 | "44"
713 | ]
714 | },
715 | "execution_count": 24,
716 | "metadata": {},
717 | "output_type": "execute_result"
718 | }
719 | ],
720 | "source": [
721 | "0x2C"
722 | ]
723 | },
724 | {
725 | "cell_type": "markdown",
726 | "metadata": {
727 | "editable": true,
728 | "slideshow": {
729 | "slide_type": ""
730 | },
731 | "tags": [
732 | "remove-cell"
733 | ]
734 | },
735 | "source": [
736 | "---\n",
737 | "\n",
738 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
739 | ]
740 | }
741 | ],
742 | "metadata": {
743 | "@context": {
744 | "CreativeWork": "http://schema.org/CreativeWork",
745 | "Organization": "http://schema.org/Organization",
746 | "Person": "http://schema.org/Person",
747 | "author": "http://schema.org/author",
748 | "copyrightHolder": "http://schema.org/copyrightHolder",
749 | "copyrightYear": "http://schema.org/copyrightYear",
750 | "license": "http://schema.org/license",
751 | "name": "http://schema.org/name",
752 | "title": "http://schema.org/name",
753 | "url": "http://schema.org/url"
754 | },
755 | "@type": "CreativeWork",
756 | "author": [
757 | {
758 | "@type": "Person",
759 | "name": "Naoaki Okazaki",
760 | "url": "https://www.chokkan.org/"
761 | }
762 | ],
763 | "copyrightHolder": [
764 | {
765 | "@type": "Person",
766 | "name": "Naoaki Okazaki",
767 | "url": "https://www.chokkan.org/"
768 | }
769 | ],
770 | "copyrightYear": 2024,
771 | "kernelspec": {
772 | "display_name": "Python 3 (ipykernel)",
773 | "language": "python",
774 | "name": "python3"
775 | },
776 | "language_info": {
777 | "codemirror_mode": {
778 | "name": "ipython",
779 | "version": 3
780 | },
781 | "file_extension": ".py",
782 | "mimetype": "text/x-python",
783 | "name": "python",
784 | "nbconvert_exporter": "python",
785 | "pygments_lexer": "ipython3",
786 | "version": "3.10.12"
787 | },
788 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
789 | "title": "Python早見帳"
790 | },
791 | "nbformat": 4,
792 | "nbformat_minor": 4
793 | }
794 |
--------------------------------------------------------------------------------
/02variable.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 変数"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {
13 | "editable": true,
14 | "slideshow": {
15 | "slide_type": ""
16 | },
17 | "tags": []
18 | },
19 | "source": [
20 | "## 基本\n",
21 | "\n",
22 | "代入文を書くと変数が作成され、その変数に値がセットされる。C言語とは異なり、変数の宣言時に型を指定しなくてもよい(Pythonは動的型付け言語である)。"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": 1,
28 | "metadata": {
29 | "editable": true,
30 | "slideshow": {
31 | "slide_type": ""
32 | },
33 | "tags": []
34 | },
35 | "outputs": [],
36 | "source": [
37 | "x = 3"
38 | ]
39 | },
40 | {
41 | "cell_type": "markdown",
42 | "metadata": {},
43 | "source": [
44 | "このように作成された変数は、Pythonのインタプリタが終了するまで保持される。変数の値を確認するには、その変数を評価させればよい。"
45 | ]
46 | },
47 | {
48 | "cell_type": "code",
49 | "execution_count": 2,
50 | "metadata": {},
51 | "outputs": [
52 | {
53 | "data": {
54 | "text/plain": [
55 | "3"
56 | ]
57 | },
58 | "execution_count": 2,
59 | "metadata": {},
60 | "output_type": "execute_result"
61 | }
62 | ],
63 | "source": [
64 | "x"
65 | ]
66 | },
67 | {
68 | "cell_type": "markdown",
69 | "metadata": {},
70 | "source": [
71 | "変数の型は[type](https://docs.python.org/ja/3/library/functions.html#type)関数で確認できる。整数は[int](https://docs.python.org/ja/3/library/stdtypes.html#numeric-types-int-float-complex)型で表現される。"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": 3,
77 | "metadata": {},
78 | "outputs": [
79 | {
80 | "data": {
81 | "text/plain": [
82 | "int"
83 | ]
84 | },
85 | "execution_count": 3,
86 | "metadata": {},
87 | "output_type": "execute_result"
88 | }
89 | ],
90 | "source": [
91 | "type(x)"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "$x \\leftarrow x + 1$といった変数の値の更新にも、代入演算子`=`が使える。"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 4,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "x = x + 1"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 5,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "data": {
117 | "text/plain": [
118 | "4"
119 | ]
120 | },
121 | "execution_count": 5,
122 | "metadata": {},
123 | "output_type": "execute_result"
124 | }
125 | ],
126 | "source": [
127 | "x"
128 | ]
129 | },
130 | {
131 | "cell_type": "markdown",
132 | "metadata": {},
133 | "source": [
134 | "上の更新処理は次のように書くこともできる(`+=`演算子はC言語にもあるが、C言語の`++`演算子に相当するものはない)。"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 6,
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "x += 1"
144 | ]
145 | },
146 | {
147 | "cell_type": "code",
148 | "execution_count": 7,
149 | "metadata": {},
150 | "outputs": [
151 | {
152 | "data": {
153 | "text/plain": [
154 | "5"
155 | ]
156 | },
157 | "execution_count": 7,
158 | "metadata": {},
159 | "output_type": "execute_result"
160 | }
161 | ],
162 | "source": [
163 | "x"
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "metadata": {},
169 | "source": [
170 | "同様に、`-=`, `*=`, `/=`という演算子が用意されている。なお、以下のコードでは変数の値の更新と、更新後の変数の評価(表示)を一つのセルで行っている。"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": 8,
176 | "metadata": {},
177 | "outputs": [
178 | {
179 | "data": {
180 | "text/plain": [
181 | "3"
182 | ]
183 | },
184 | "execution_count": 8,
185 | "metadata": {},
186 | "output_type": "execute_result"
187 | }
188 | ],
189 | "source": [
190 | "x -= 2\n",
191 | "x"
192 | ]
193 | },
194 | {
195 | "cell_type": "code",
196 | "execution_count": 9,
197 | "metadata": {},
198 | "outputs": [
199 | {
200 | "data": {
201 | "text/plain": [
202 | "6"
203 | ]
204 | },
205 | "execution_count": 9,
206 | "metadata": {},
207 | "output_type": "execute_result"
208 | }
209 | ],
210 | "source": [
211 | "x *= 2\n",
212 | "x"
213 | ]
214 | },
215 | {
216 | "cell_type": "code",
217 | "execution_count": 10,
218 | "metadata": {},
219 | "outputs": [
220 | {
221 | "data": {
222 | "text/plain": [
223 | "2.0"
224 | ]
225 | },
226 | "execution_count": 10,
227 | "metadata": {},
228 | "output_type": "execute_result"
229 | }
230 | ],
231 | "source": [
232 | "x /= 3\n",
233 | "x"
234 | ]
235 | },
236 | {
237 | "cell_type": "markdown",
238 | "metadata": {},
239 | "source": [
240 | "浮動小数点型の変数を作成するには、値を小数点付きで表現すればよい。"
241 | ]
242 | },
243 | {
244 | "cell_type": "code",
245 | "execution_count": 11,
246 | "metadata": {},
247 | "outputs": [
248 | {
249 | "data": {
250 | "text/plain": [
251 | "1.5"
252 | ]
253 | },
254 | "execution_count": 11,
255 | "metadata": {},
256 | "output_type": "execute_result"
257 | }
258 | ],
259 | "source": [
260 | "x = 1.5\n",
261 | "x"
262 | ]
263 | },
264 | {
265 | "cell_type": "markdown",
266 | "metadata": {},
267 | "source": [
268 | "浮動少数点数は[float](https://docs.python.org/ja/3/library/stdtypes.html#numeric-types-int-float-complex)型で表現される。"
269 | ]
270 | },
271 | {
272 | "cell_type": "code",
273 | "execution_count": 12,
274 | "metadata": {},
275 | "outputs": [
276 | {
277 | "data": {
278 | "text/plain": [
279 | "float"
280 | ]
281 | },
282 | "execution_count": 12,
283 | "metadata": {},
284 | "output_type": "execute_result"
285 | }
286 | ],
287 | "source": [
288 | "type(x)"
289 | ]
290 | },
291 | {
292 | "cell_type": "markdown",
293 | "metadata": {},
294 | "source": [
295 | "浮動小数点型から整数型に変換するには、[int](https://docs.python.org/ja/3/library/functions.html#int)関数を用いる。以下の例では`x`の値が切り捨てられる。"
296 | ]
297 | },
298 | {
299 | "cell_type": "code",
300 | "execution_count": 13,
301 | "metadata": {},
302 | "outputs": [
303 | {
304 | "data": {
305 | "text/plain": [
306 | "1"
307 | ]
308 | },
309 | "execution_count": 13,
310 | "metadata": {},
311 | "output_type": "execute_result"
312 | }
313 | ],
314 | "source": [
315 | "int(x)"
316 | ]
317 | },
318 | {
319 | "cell_type": "markdown",
320 | "metadata": {},
321 | "source": [
322 | "整数型から浮動小数点型に変換するには、[float](https://docs.python.org/ja/3/library/functions.html#float)関数を用いる。"
323 | ]
324 | },
325 | {
326 | "cell_type": "code",
327 | "execution_count": 14,
328 | "metadata": {},
329 | "outputs": [
330 | {
331 | "data": {
332 | "text/plain": [
333 | "2.0"
334 | ]
335 | },
336 | "execution_count": 14,
337 | "metadata": {},
338 | "output_type": "execute_result"
339 | }
340 | ],
341 | "source": [
342 | "float(2)"
343 | ]
344 | },
345 | {
346 | "cell_type": "markdown",
347 | "metadata": {},
348 | "source": [
349 | "変数(オブジェクト)の削除は[del](https://docs.python.org/ja/3/reference/simple_stmts.html#the-del-statement)文で行う。ただ、Pythonでは使わなくなったメモリ領域は自動的に開放される(ガーベージコレクション)ため、明示的にdel文で変数を削除することは稀である。"
350 | ]
351 | },
352 | {
353 | "cell_type": "code",
354 | "execution_count": 15,
355 | "metadata": {},
356 | "outputs": [],
357 | "source": [
358 | "del x"
359 | ]
360 | },
361 | {
362 | "cell_type": "markdown",
363 | "metadata": {},
364 | "source": [
365 | "変数`x`を削除すると、評価できなくなる。"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": 16,
371 | "metadata": {
372 | "tags": [
373 | "raises-exception"
374 | ]
375 | },
376 | "outputs": [
377 | {
378 | "ename": "NameError",
379 | "evalue": "name 'x' is not defined",
380 | "output_type": "error",
381 | "traceback": [
382 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
383 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
384 | "\u001b[0;32m/tmp/ipykernel_206365/32546335.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
385 | "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined"
386 | ]
387 | }
388 | ],
389 | "source": [
390 | "x"
391 | ]
392 | },
393 | {
394 | "cell_type": "markdown",
395 | "metadata": {},
396 | "source": [
397 | "## 変数の再評価"
398 | ]
399 | },
400 | {
401 | "cell_type": "markdown",
402 | "metadata": {},
403 | "source": [
404 | "$x = 1$として$y \\leftarrow x^2 + 2x + 1$を計算してみる。"
405 | ]
406 | },
407 | {
408 | "cell_type": "code",
409 | "execution_count": 17,
410 | "metadata": {},
411 | "outputs": [],
412 | "source": [
413 | "x = 1.\n",
414 | "y = x ** 2 + 2 * x + 1"
415 | ]
416 | },
417 | {
418 | "cell_type": "code",
419 | "execution_count": 18,
420 | "metadata": {},
421 | "outputs": [
422 | {
423 | "data": {
424 | "text/plain": [
425 | "4.0"
426 | ]
427 | },
428 | "execution_count": 18,
429 | "metadata": {},
430 | "output_type": "execute_result"
431 | }
432 | ],
433 | "source": [
434 | "y"
435 | ]
436 | },
437 | {
438 | "cell_type": "markdown",
439 | "metadata": {},
440 | "source": [
441 | "変数`x`の値を`2`に変更してから`y`を評価しても、変数`y`の値は再計算されない(元の値から変化しない)。"
442 | ]
443 | },
444 | {
445 | "cell_type": "code",
446 | "execution_count": 19,
447 | "metadata": {},
448 | "outputs": [],
449 | "source": [
450 | "x = 2"
451 | ]
452 | },
453 | {
454 | "cell_type": "code",
455 | "execution_count": 20,
456 | "metadata": {},
457 | "outputs": [
458 | {
459 | "data": {
460 | "text/plain": [
461 | "4.0"
462 | ]
463 | },
464 | "execution_count": 20,
465 | "metadata": {},
466 | "output_type": "execute_result"
467 | }
468 | ],
469 | "source": [
470 | "y"
471 | ]
472 | },
473 | {
474 | "cell_type": "markdown",
475 | "metadata": {},
476 | "source": [
477 | "再計算をするには、変数`y`の代入文を再度実行する必要がある。"
478 | ]
479 | },
480 | {
481 | "cell_type": "code",
482 | "execution_count": 21,
483 | "metadata": {},
484 | "outputs": [
485 | {
486 | "data": {
487 | "text/plain": [
488 | "9"
489 | ]
490 | },
491 | "execution_count": 21,
492 | "metadata": {},
493 | "output_type": "execute_result"
494 | }
495 | ],
496 | "source": [
497 | "y = x ** 2 + 2 * x + 1\n",
498 | "y"
499 | ]
500 | },
501 | {
502 | "cell_type": "markdown",
503 | "metadata": {},
504 | "source": [
505 | "## 複数の変数への代入"
506 | ]
507 | },
508 | {
509 | "cell_type": "markdown",
510 | "metadata": {},
511 | "source": [
512 | "一行で複数の変数にまとめて値を代入できる(厳密には後で説明するタプル型を介した代入である)。"
513 | ]
514 | },
515 | {
516 | "cell_type": "code",
517 | "execution_count": 22,
518 | "metadata": {},
519 | "outputs": [],
520 | "source": [
521 | "x, y = 3, 1"
522 | ]
523 | },
524 | {
525 | "cell_type": "code",
526 | "execution_count": 23,
527 | "metadata": {},
528 | "outputs": [
529 | {
530 | "data": {
531 | "text/plain": [
532 | "3"
533 | ]
534 | },
535 | "execution_count": 23,
536 | "metadata": {},
537 | "output_type": "execute_result"
538 | }
539 | ],
540 | "source": [
541 | "x"
542 | ]
543 | },
544 | {
545 | "cell_type": "code",
546 | "execution_count": 24,
547 | "metadata": {},
548 | "outputs": [
549 | {
550 | "data": {
551 | "text/plain": [
552 | "1"
553 | ]
554 | },
555 | "execution_count": 24,
556 | "metadata": {},
557 | "output_type": "execute_result"
558 | }
559 | ],
560 | "source": [
561 | "y"
562 | ]
563 | },
564 | {
565 | "cell_type": "markdown",
566 | "metadata": {},
567 | "source": [
568 | "変数の値の入れ替えも簡単に書ける(一時的な変数を使わずに書ける)。"
569 | ]
570 | },
571 | {
572 | "cell_type": "code",
573 | "execution_count": 25,
574 | "metadata": {},
575 | "outputs": [],
576 | "source": [
577 | "x, y = y, x"
578 | ]
579 | },
580 | {
581 | "cell_type": "code",
582 | "execution_count": 26,
583 | "metadata": {},
584 | "outputs": [
585 | {
586 | "data": {
587 | "text/plain": [
588 | "1"
589 | ]
590 | },
591 | "execution_count": 26,
592 | "metadata": {},
593 | "output_type": "execute_result"
594 | }
595 | ],
596 | "source": [
597 | "x"
598 | ]
599 | },
600 | {
601 | "cell_type": "code",
602 | "execution_count": 27,
603 | "metadata": {
604 | "editable": true,
605 | "slideshow": {
606 | "slide_type": ""
607 | },
608 | "tags": []
609 | },
610 | "outputs": [
611 | {
612 | "data": {
613 | "text/plain": [
614 | "3"
615 | ]
616 | },
617 | "execution_count": 27,
618 | "metadata": {},
619 | "output_type": "execute_result"
620 | }
621 | ],
622 | "source": [
623 | "y"
624 | ]
625 | },
626 | {
627 | "cell_type": "markdown",
628 | "metadata": {
629 | "editable": true,
630 | "slideshow": {
631 | "slide_type": ""
632 | },
633 | "tags": []
634 | },
635 | "source": [
636 | "## 変数の型アノテーション (Python 3.6以降)"
637 | ]
638 | },
639 | {
640 | "cell_type": "markdown",
641 | "metadata": {
642 | "editable": true,
643 | "slideshow": {
644 | "slide_type": ""
645 | },
646 | "tags": []
647 | },
648 | "source": [
649 | "Pythonでは型を指定して変数を作成することはできないが、変数の型の説明(型アノテーションや型ヒントと呼ばれる)を付けることができる。Pythonに入門したての頃は型アノテーションを使いこなす必要はないが、型アノテーションを使った変数を見ても驚かないように、例を示しておく。\n",
650 | "\n",
651 | "以下は変数`x`はint型であると説明しながら、`1`を代入する例である。"
652 | ]
653 | },
654 | {
655 | "cell_type": "code",
656 | "execution_count": 28,
657 | "metadata": {
658 | "editable": true,
659 | "slideshow": {
660 | "slide_type": ""
661 | },
662 | "tags": []
663 | },
664 | "outputs": [],
665 | "source": [
666 | "x: int = 1"
667 | ]
668 | },
669 | {
670 | "cell_type": "markdown",
671 | "metadata": {
672 | "editable": true,
673 | "slideshow": {
674 | "slide_type": ""
675 | },
676 | "tags": []
677 | },
678 | "source": [
679 | "以下は変数`x`はint型であると説明しておきながら、浮動小数点数である`1.0`を代入する例である。これは型アノテーションと変数の型が一致していない悪い例である。"
680 | ]
681 | },
682 | {
683 | "cell_type": "code",
684 | "execution_count": 29,
685 | "metadata": {
686 | "editable": true,
687 | "slideshow": {
688 | "slide_type": ""
689 | },
690 | "tags": []
691 | },
692 | "outputs": [],
693 | "source": [
694 | "x: int = 1."
695 | ]
696 | },
697 | {
698 | "cell_type": "markdown",
699 | "metadata": {
700 | "editable": true,
701 | "slideshow": {
702 | "slide_type": ""
703 | },
704 | "tags": []
705 | },
706 | "source": [
707 | "実際に、変数`x`の型を調べてみると、int型ではなくfloat型となっている。"
708 | ]
709 | },
710 | {
711 | "cell_type": "code",
712 | "execution_count": 30,
713 | "metadata": {
714 | "editable": true,
715 | "slideshow": {
716 | "slide_type": ""
717 | },
718 | "tags": []
719 | },
720 | "outputs": [
721 | {
722 | "data": {
723 | "text/plain": [
724 | "float"
725 | ]
726 | },
727 | "execution_count": 30,
728 | "metadata": {},
729 | "output_type": "execute_result"
730 | }
731 | ],
732 | "source": [
733 | "type(x)"
734 | ]
735 | },
736 | {
737 | "cell_type": "markdown",
738 | "metadata": {
739 | "editable": true,
740 | "slideshow": {
741 | "slide_type": ""
742 | },
743 | "tags": []
744 | },
745 | "source": [
746 | "このように、型アノテーションは変数の型を強制するものではないが、ソースコードの可読性の向上、エディタの自動補完機能、型チェックなどに用いられる。"
747 | ]
748 | },
749 | {
750 | "cell_type": "markdown",
751 | "metadata": {
752 | "editable": true,
753 | "slideshow": {
754 | "slide_type": ""
755 | },
756 | "tags": [
757 | "remove-cell"
758 | ]
759 | },
760 | "source": [
761 | "---\n",
762 | "\n",
763 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
764 | ]
765 | }
766 | ],
767 | "metadata": {
768 | "@context": {
769 | "CreativeWork": "http://schema.org/CreativeWork",
770 | "Organization": "http://schema.org/Organization",
771 | "Person": "http://schema.org/Person",
772 | "author": "http://schema.org/author",
773 | "copyrightHolder": "http://schema.org/copyrightHolder",
774 | "copyrightYear": "http://schema.org/copyrightYear",
775 | "license": "http://schema.org/license",
776 | "name": "http://schema.org/name",
777 | "title": "http://schema.org/name",
778 | "url": "http://schema.org/url"
779 | },
780 | "@type": "CreativeWork",
781 | "author": [
782 | {
783 | "@type": "Person",
784 | "name": "Naoaki Okazaki",
785 | "url": "https://www.chokkan.org/"
786 | }
787 | ],
788 | "copyrightHolder": [
789 | {
790 | "@type": "Person",
791 | "name": "Naoaki Okazaki",
792 | "url": "https://www.chokkan.org/"
793 | }
794 | ],
795 | "copyrightYear": 2024,
796 | "kernelspec": {
797 | "display_name": "Python 3 (ipykernel)",
798 | "language": "python",
799 | "name": "python3"
800 | },
801 | "language_info": {
802 | "codemirror_mode": {
803 | "name": "ipython",
804 | "version": 3
805 | },
806 | "file_extension": ".py",
807 | "mimetype": "text/x-python",
808 | "name": "python",
809 | "nbconvert_exporter": "python",
810 | "pygments_lexer": "ipython3",
811 | "version": "3.10.12"
812 | },
813 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
814 | "title": "Python早見帳"
815 | },
816 | "nbformat": 4,
817 | "nbformat_minor": 4
818 | }
819 |
--------------------------------------------------------------------------------
/05module.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# モジュール\n",
8 | "\n",
9 | "モジュールとは、Pythonのプログラムが記述されたテキストファイル(拡張子は.py)である。モジュールの主な使い方は以下の3つである。\n",
10 | "\n",
11 | "1. コマンドラインからスクリプトとして実行する\n",
12 | "1. 他のモジュールやJupyter Notebookから利用する\n",
13 | "1. (標準も含めて)インストールされているモジュール利用する\n",
14 | "\n",
15 | "まず、2と3を紹介し、その後1を紹介する。\n",
16 | "\n",
17 | "## 他のモジュールの取り込み\n",
18 | "\n",
19 | "別のファイルに書かれているPythonプログラムを利用するには、[import](https://docs.python.org/ja/3/reference/simple_stmts.html#import)文を使う。例えば、以下のソースコードがoptim.pyというファイルに書かれていて、実行しているJupyter Notebookと同じディレクトリにそのファイルが置かれているとする。\n",
20 | "\n",
21 | "```python\n",
22 | "def bisection(func, a, b, eps=1e-8):\n",
23 | " while True:\n",
24 | " x = (a + b) / 2\n",
25 | " fx = func(x)\n",
26 | " if -eps < fx < eps:\n",
27 | " return x\n",
28 | " fa = func(a)\n",
29 | " if fx * fa < 0:\n",
30 | " b = x\n",
31 | " else:\n",
32 | " a = x\n",
33 | "\n",
34 | "def newton_raphson(func_f, func_g, x=0, eps=1e-8):\n",
35 | " while True:\n",
36 | " fx, gx = func_f(x), func_g(x)\n",
37 | " if -eps < fx < eps:\n",
38 | " return x\n",
39 | " x -= fx / gx \n",
40 | "```"
41 | ]
42 | },
43 | {
44 | "cell_type": "markdown",
45 | "metadata": {},
46 | "source": [
47 | "このソースコードでは、bisectionとnewton_raphsonという2つの関数が定義されており、それぞれ二分法とニュートン・ラフソン法を実装している。optim.pyに書かれているbisection関数を呼び出すとき、何もせずにbisection関数を呼び出すとエラーになる。"
48 | ]
49 | },
50 | {
51 | "cell_type": "code",
52 | "execution_count": 1,
53 | "metadata": {
54 | "tags": [
55 | "raises-exception"
56 | ]
57 | },
58 | "outputs": [
59 | {
60 | "ename": "NameError",
61 | "evalue": "name 'bisection' is not defined",
62 | "output_type": "error",
63 | "traceback": [
64 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
65 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
66 | "\u001b[0;32m/tmp/ipykernel_204933/130988965.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m**\u001b[0m \u001b[0;36m2\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m2\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mbisection\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m-\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
67 | "\u001b[0;31mNameError\u001b[0m: name 'bisection' is not defined"
68 | ]
69 | }
70 | ],
71 | "source": [
72 | "def f(x):\n",
73 | " return x ** 2 + 2 * x - 3\n",
74 | "\n",
75 | "bisection(f, -2, 2)"
76 | ]
77 | },
78 | {
79 | "cell_type": "markdown",
80 | "metadata": {},
81 | "source": [
82 | "optim.pyのプログラムをインタプリタに取り込むには、import文を使う。このとき、optim.pyで定義されている関数や変数は先頭に`optim.`を付けることでアクセスできる(optimという名前空間で取り込まれる)。"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": 2,
88 | "metadata": {},
89 | "outputs": [],
90 | "source": [
91 | "import optim"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "optim.pyのbisection関数は`optim.bisection`という名前で呼び出すことができる。"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 3,
104 | "metadata": {},
105 | "outputs": [
106 | {
107 | "data": {
108 | "text/plain": [
109 | "1.0"
110 | ]
111 | },
112 | "execution_count": 3,
113 | "metadata": {},
114 | "output_type": "execute_result"
115 | }
116 | ],
117 | "source": [
118 | "def f(x):\n",
119 | " return x ** 2 + 2 * x - 3\n",
120 | "\n",
121 | "optim.bisection(f, -2, 2)"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "同様に、optim.pyのnewton_raphson関数は`optim.newton_raphson`という名前で呼び出すことができる。"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": 4,
134 | "metadata": {},
135 | "outputs": [
136 | {
137 | "data": {
138 | "text/plain": [
139 | "1.000000000000002"
140 | ]
141 | },
142 | "execution_count": 4,
143 | "metadata": {},
144 | "output_type": "execute_result"
145 | }
146 | ],
147 | "source": [
148 | "def f(x):\n",
149 | " return x ** 2 + 2 * x - 3\n",
150 | "\n",
151 | "def g(x):\n",
152 | " return 2 * x + 2\n",
153 | "\n",
154 | "optim.newton_raphson(f, g, 0)"
155 | ]
156 | },
157 | {
158 | "cell_type": "markdown",
159 | "metadata": {},
160 | "source": [
161 | "### fromを使ったインポート"
162 | ]
163 | },
164 | {
165 | "cell_type": "markdown",
166 | "metadata": {},
167 | "source": [
168 | "先ほどの方法では、optim.pyで定義されている関数がoptimという名前空間に取り込まれた。名前空間を付けずに、関数をそのまま(現在の名前空間に)取り込むには、from文を用いる。以下は、optim.pyのbisection関数を取り込む例である。"
169 | ]
170 | },
171 | {
172 | "cell_type": "code",
173 | "execution_count": 5,
174 | "metadata": {},
175 | "outputs": [],
176 | "source": [
177 | "from optim import bisection"
178 | ]
179 | },
180 | {
181 | "cell_type": "markdown",
182 | "metadata": {},
183 | "source": [
184 | "すると、optim.pyで定義された関数をそのまま(`optim.`なしで)呼び出すことができる。"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": 6,
190 | "metadata": {},
191 | "outputs": [
192 | {
193 | "data": {
194 | "text/plain": [
195 | "1.0"
196 | ]
197 | },
198 | "execution_count": 6,
199 | "metadata": {},
200 | "output_type": "execute_result"
201 | }
202 | ],
203 | "source": [
204 | "bisection(f, -2, 2)"
205 | ]
206 | },
207 | {
208 | "cell_type": "markdown",
209 | "metadata": {},
210 | "source": [
211 | "newton_raphson関数は現在の名前空間に取り込まれていないので、呼び出すことができない。"
212 | ]
213 | },
214 | {
215 | "cell_type": "code",
216 | "execution_count": 7,
217 | "metadata": {
218 | "tags": [
219 | "raises-exception"
220 | ]
221 | },
222 | "outputs": [
223 | {
224 | "ename": "NameError",
225 | "evalue": "name 'newton_raphson' is not defined",
226 | "output_type": "error",
227 | "traceback": [
228 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
229 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
230 | "\u001b[0;32m/tmp/ipykernel_204933/3347386978.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnewton_raphson\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
231 | "\u001b[0;31mNameError\u001b[0m: name 'newton_raphson' is not defined"
232 | ]
233 | }
234 | ],
235 | "source": [
236 | "newton_raphson(f, g, 0)"
237 | ]
238 | },
239 | {
240 | "cell_type": "markdown",
241 | "metadata": {},
242 | "source": [
243 | "optim.pyのbisection関数、newton_raphson関数を現在の名前空間に取り込む。"
244 | ]
245 | },
246 | {
247 | "cell_type": "code",
248 | "execution_count": 8,
249 | "metadata": {},
250 | "outputs": [],
251 | "source": [
252 | "from optim import bisection, newton_raphson"
253 | ]
254 | },
255 | {
256 | "cell_type": "code",
257 | "execution_count": 9,
258 | "metadata": {},
259 | "outputs": [
260 | {
261 | "data": {
262 | "text/plain": [
263 | "1.000000000000002"
264 | ]
265 | },
266 | "execution_count": 9,
267 | "metadata": {},
268 | "output_type": "execute_result"
269 | }
270 | ],
271 | "source": [
272 | "newton_raphson(f, g, 0)"
273 | ]
274 | },
275 | {
276 | "cell_type": "markdown",
277 | "metadata": {},
278 | "source": [
279 | "optim.pyの全ての識別子(関数や変数など)を取り込む。"
280 | ]
281 | },
282 | {
283 | "cell_type": "code",
284 | "execution_count": 10,
285 | "metadata": {},
286 | "outputs": [],
287 | "source": [
288 | "from optim import *"
289 | ]
290 | },
291 | {
292 | "cell_type": "code",
293 | "execution_count": 11,
294 | "metadata": {},
295 | "outputs": [
296 | {
297 | "data": {
298 | "text/plain": [
299 | "1.000000000000002"
300 | ]
301 | },
302 | "execution_count": 11,
303 | "metadata": {},
304 | "output_type": "execute_result"
305 | }
306 | ],
307 | "source": [
308 | "newton_raphson(f, g, 0)"
309 | ]
310 | },
311 | {
312 | "cell_type": "markdown",
313 | "metadata": {},
314 | "source": [
315 | "### 名前空間の変更"
316 | ]
317 | },
318 | {
319 | "cell_type": "markdown",
320 | "metadata": {},
321 | "source": [
322 | "import文を呼び出したとき、通常はモジュールのファイル名が名前空間となるが、それを変更するにはasを使えばよい。"
323 | ]
324 | },
325 | {
326 | "cell_type": "code",
327 | "execution_count": 12,
328 | "metadata": {},
329 | "outputs": [],
330 | "source": [
331 | "import optim as opt"
332 | ]
333 | },
334 | {
335 | "cell_type": "code",
336 | "execution_count": 13,
337 | "metadata": {},
338 | "outputs": [
339 | {
340 | "data": {
341 | "text/plain": [
342 | "1.0"
343 | ]
344 | },
345 | "execution_count": 13,
346 | "metadata": {},
347 | "output_type": "execute_result"
348 | }
349 | ],
350 | "source": [
351 | "opt.bisection(f, -2, 2)"
352 | ]
353 | },
354 | {
355 | "cell_type": "code",
356 | "execution_count": 14,
357 | "metadata": {},
358 | "outputs": [
359 | {
360 | "data": {
361 | "text/plain": [
362 | "1.000000000000002"
363 | ]
364 | },
365 | "execution_count": 14,
366 | "metadata": {},
367 | "output_type": "execute_result"
368 | }
369 | ],
370 | "source": [
371 | "opt.newton_raphson(f, g, 0)"
372 | ]
373 | },
374 | {
375 | "cell_type": "markdown",
376 | "metadata": {},
377 | "source": [
378 | "## インストールされたモジュールの利用\n",
379 | "\n",
380 | "Pythonには標準でインストールされているモジュール([Python標準ライブラリ](https://docs.python.org/ja/3/library/index.html))がある。これらのモジュールを利用するときもimport文を用いる。"
381 | ]
382 | },
383 | {
384 | "cell_type": "markdown",
385 | "metadata": {},
386 | "source": [
387 | "以下は、[math](https://docs.python.org/ja/3/library/math.html)モジュールをインポートして、$\\sqrt{2}$を計算する例である。"
388 | ]
389 | },
390 | {
391 | "cell_type": "code",
392 | "execution_count": 15,
393 | "metadata": {},
394 | "outputs": [
395 | {
396 | "data": {
397 | "text/plain": [
398 | "1.4142135623730951"
399 | ]
400 | },
401 | "execution_count": 15,
402 | "metadata": {},
403 | "output_type": "execute_result"
404 | }
405 | ],
406 | "source": [
407 | "import math\n",
408 | "\n",
409 | "math.sqrt(2)"
410 | ]
411 | },
412 | {
413 | "cell_type": "markdown",
414 | "metadata": {},
415 | "source": [
416 | "## コマンドラインからの実行\n",
417 | "\n",
418 | "[Jupyter Notebook](https://jupyter.org/)やその前身の[IPython Notebook](https://ipython.org/notebook.html)が登場する前までは、Pythonのプログラムを.pyのファイルに記述し、コマンドライン等から実行することが基本であった。例えば、以下のソースコードがoptim2.pyというファイルに書かれているとする。"
419 | ]
420 | },
421 | {
422 | "cell_type": "markdown",
423 | "metadata": {},
424 | "source": [
425 | "```python\n",
426 | "def bisection(func, a, b, eps=1e-8):\n",
427 | " while True:\n",
428 | " x = (a + b) / 2\n",
429 | " fx = func(x)\n",
430 | " if -eps < fx < eps:\n",
431 | " return x\n",
432 | " fa = func(a)\n",
433 | " if fx * fa < 0:\n",
434 | " b = x\n",
435 | " else:\n",
436 | " a = x\n",
437 | "\n",
438 | "def newton_raphson(func_f, func_g, x=0, eps=1e-8):\n",
439 | " while True:\n",
440 | " fx, gx = func_f(x), func_g(x)\n",
441 | " if -eps < fx < eps:\n",
442 | " return x\n",
443 | " x -= fx / gx\n",
444 | " \n",
445 | "if __name__ == '__main__':\n",
446 | " print(bisection(f, -2, 2))\n",
447 | " print(newton_raphson(f, g, 0))\n",
448 | "```"
449 | ]
450 | },
451 | {
452 | "cell_type": "markdown",
453 | "metadata": {},
454 | "source": [
455 | "このプログラムを起動したときに実行する処理は、`if __name__ == '__main__':`のブロック以下に記述する。このプログラムをコマンドラインから実行するには、\n",
456 | "\n",
457 | "```bash\n",
458 | "python optim2.py\n",
459 | "```\n",
460 | "\n",
461 | "とすればよい。Jupyter Notebook上でコマンドを実行するには、先頭に`!`を付ければよい。"
462 | ]
463 | },
464 | {
465 | "cell_type": "code",
466 | "execution_count": 16,
467 | "metadata": {},
468 | "outputs": [
469 | {
470 | "name": "stdout",
471 | "output_type": "stream",
472 | "text": [
473 | "1.0\n",
474 | "1.000000000000002\n"
475 | ]
476 | }
477 | ],
478 | "source": [
479 | "!python optim2.py"
480 | ]
481 | },
482 | {
483 | "cell_type": "markdown",
484 | "metadata": {
485 | "tags": [
486 | "remove-cell"
487 | ]
488 | },
489 | "source": [
490 | "---\n",
491 | "\n",
492 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
493 | ]
494 | }
495 | ],
496 | "metadata": {
497 | "@context": {
498 | "CreativeWork": "http://schema.org/CreativeWork",
499 | "Organization": "http://schema.org/Organization",
500 | "Person": "http://schema.org/Person",
501 | "author": "http://schema.org/author",
502 | "copyrightHolder": "http://schema.org/copyrightHolder",
503 | "copyrightYear": "http://schema.org/copyrightYear",
504 | "license": "http://schema.org/license",
505 | "name": "http://schema.org/name",
506 | "title": "http://schema.org/name",
507 | "url": "http://schema.org/url"
508 | },
509 | "@type": "CreativeWork",
510 | "author": [
511 | {
512 | "@type": "Person",
513 | "name": "Naoaki Okazaki",
514 | "url": "https://www.chokkan.org/"
515 | }
516 | ],
517 | "copyrightHolder": [
518 | {
519 | "@type": "Person",
520 | "name": "Naoaki Okazaki",
521 | "url": "https://www.chokkan.org/"
522 | }
523 | ],
524 | "copyrightYear": 2024,
525 | "kernelspec": {
526 | "display_name": "Python 3 (ipykernel)",
527 | "language": "python",
528 | "name": "python3"
529 | },
530 | "language_info": {
531 | "codemirror_mode": {
532 | "name": "ipython",
533 | "version": 3
534 | },
535 | "file_extension": ".py",
536 | "mimetype": "text/x-python",
537 | "name": "python",
538 | "nbconvert_exporter": "python",
539 | "pygments_lexer": "ipython3",
540 | "version": "3.10.12"
541 | },
542 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
543 | "title": "Python早見帳"
544 | },
545 | "nbformat": 4,
546 | "nbformat_minor": 4
547 | }
548 |
--------------------------------------------------------------------------------
/07tuple.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "(ch:tuple)=\n",
8 | "# タプル"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "## 基本\n",
16 | "\n",
17 | "リストと同様に、タプルも複数の値・オブジェクトをまとめる。要素を`,`で区切って並べ、全体を`( )`で囲んで作成する。"
18 | ]
19 | },
20 | {
21 | "cell_type": "code",
22 | "execution_count": 1,
23 | "metadata": {},
24 | "outputs": [],
25 | "source": [
26 | "t = (0, 1, 4, 9, 16, 25, 36, 49)"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": 2,
32 | "metadata": {},
33 | "outputs": [
34 | {
35 | "data": {
36 | "text/plain": [
37 | "(0, 1, 4, 9, 16, 25, 36, 49)"
38 | ]
39 | },
40 | "execution_count": 2,
41 | "metadata": {},
42 | "output_type": "execute_result"
43 | }
44 | ],
45 | "source": [
46 | "t"
47 | ]
48 | },
49 | {
50 | "cell_type": "code",
51 | "execution_count": 3,
52 | "metadata": {},
53 | "outputs": [
54 | {
55 | "data": {
56 | "text/plain": [
57 | "tuple"
58 | ]
59 | },
60 | "execution_count": 3,
61 | "metadata": {},
62 | "output_type": "execute_result"
63 | }
64 | ],
65 | "source": [
66 | "type(t)"
67 | ]
68 | },
69 | {
70 | "cell_type": "markdown",
71 | "metadata": {},
72 | "source": [
73 | "リストと同じように要素にアクセスできる。"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 4,
79 | "metadata": {},
80 | "outputs": [
81 | {
82 | "data": {
83 | "text/plain": [
84 | "0"
85 | ]
86 | },
87 | "execution_count": 4,
88 | "metadata": {},
89 | "output_type": "execute_result"
90 | }
91 | ],
92 | "source": [
93 | "t[0]"
94 | ]
95 | },
96 | {
97 | "cell_type": "code",
98 | "execution_count": 5,
99 | "metadata": {},
100 | "outputs": [
101 | {
102 | "data": {
103 | "text/plain": [
104 | "49"
105 | ]
106 | },
107 | "execution_count": 5,
108 | "metadata": {},
109 | "output_type": "execute_result"
110 | }
111 | ],
112 | "source": [
113 | "t[-1]"
114 | ]
115 | },
116 | {
117 | "cell_type": "code",
118 | "execution_count": 6,
119 | "metadata": {},
120 | "outputs": [
121 | {
122 | "data": {
123 | "text/plain": [
124 | "(49, 36, 25, 16, 9, 4, 1, 0)"
125 | ]
126 | },
127 | "execution_count": 6,
128 | "metadata": {},
129 | "output_type": "execute_result"
130 | }
131 | ],
132 | "source": [
133 | "t[::-1]"
134 | ]
135 | },
136 | {
137 | "cell_type": "markdown",
138 | "metadata": {},
139 | "source": [
140 | "リストと同じように、タプルにある要素が含まれるかどうかチェックできる。"
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": 7,
146 | "metadata": {},
147 | "outputs": [
148 | {
149 | "data": {
150 | "text/plain": [
151 | "True"
152 | ]
153 | },
154 | "execution_count": 7,
155 | "metadata": {},
156 | "output_type": "execute_result"
157 | }
158 | ],
159 | "source": [
160 | "16 in t"
161 | ]
162 | },
163 | {
164 | "cell_type": "code",
165 | "execution_count": 8,
166 | "metadata": {},
167 | "outputs": [
168 | {
169 | "data": {
170 | "text/plain": [
171 | "False"
172 | ]
173 | },
174 | "execution_count": 8,
175 | "metadata": {},
176 | "output_type": "execute_result"
177 | }
178 | ],
179 | "source": [
180 | "16 not in t"
181 | ]
182 | },
183 | {
184 | "cell_type": "markdown",
185 | "metadata": {},
186 | "source": [
187 | "タプルは不変なオブジェクトであるため、タプルの要素は変更できない({ref}`ch:immutable`を参照)。"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 9,
193 | "metadata": {
194 | "tags": [
195 | "raises-exception"
196 | ]
197 | },
198 | "outputs": [
199 | {
200 | "ename": "TypeError",
201 | "evalue": "'tuple' object does not support item assignment",
202 | "output_type": "error",
203 | "traceback": [
204 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
205 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
206 | "\u001b[0;32m/tmp/ipykernel_204970/1253691622.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
207 | "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
208 | ]
209 | }
210 | ],
211 | "source": [
212 | "t[0] = 1"
213 | ]
214 | },
215 | {
216 | "cell_type": "markdown",
217 | "metadata": {},
218 | "source": [
219 | "タプルに要素を追加することもできない。"
220 | ]
221 | },
222 | {
223 | "cell_type": "code",
224 | "execution_count": 10,
225 | "metadata": {
226 | "tags": [
227 | "raises-exception"
228 | ]
229 | },
230 | "outputs": [
231 | {
232 | "ename": "AttributeError",
233 | "evalue": "'tuple' object has no attribute 'append'",
234 | "output_type": "error",
235 | "traceback": [
236 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
237 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
238 | "\u001b[0;32m/tmp/ipykernel_204970/1701743339.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m64\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
239 | "\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'"
240 | ]
241 | }
242 | ],
243 | "source": [
244 | "t.append(64)"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "metadata": {},
250 | "source": [
251 | "## パック・アンパック"
252 | ]
253 | },
254 | {
255 | "cell_type": "markdown",
256 | "metadata": {},
257 | "source": [
258 | "タプルを作成するときの括弧は省略できる。"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 11,
264 | "metadata": {},
265 | "outputs": [
266 | {
267 | "data": {
268 | "text/plain": [
269 | "(2, 4, 6)"
270 | ]
271 | },
272 | "execution_count": 11,
273 | "metadata": {},
274 | "output_type": "execute_result"
275 | }
276 | ],
277 | "source": [
278 | "t = 2, 4, 6\n",
279 | "t"
280 | ]
281 | },
282 | {
283 | "cell_type": "code",
284 | "execution_count": 12,
285 | "metadata": {},
286 | "outputs": [
287 | {
288 | "data": {
289 | "text/plain": [
290 | "tuple"
291 | ]
292 | },
293 | "execution_count": 12,
294 | "metadata": {},
295 | "output_type": "execute_result"
296 | }
297 | ],
298 | "source": [
299 | "type(t)"
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {},
305 | "source": [
306 | "タプルの各要素の値を取り出しながら代入できる(「アンパック」と呼ばれる)。"
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "execution_count": 13,
312 | "metadata": {},
313 | "outputs": [],
314 | "source": [
315 | "x, y, z = t"
316 | ]
317 | },
318 | {
319 | "cell_type": "code",
320 | "execution_count": 14,
321 | "metadata": {},
322 | "outputs": [
323 | {
324 | "data": {
325 | "text/plain": [
326 | "2"
327 | ]
328 | },
329 | "execution_count": 14,
330 | "metadata": {},
331 | "output_type": "execute_result"
332 | }
333 | ],
334 | "source": [
335 | "x"
336 | ]
337 | },
338 | {
339 | "cell_type": "code",
340 | "execution_count": 15,
341 | "metadata": {},
342 | "outputs": [
343 | {
344 | "data": {
345 | "text/plain": [
346 | "4"
347 | ]
348 | },
349 | "execution_count": 15,
350 | "metadata": {},
351 | "output_type": "execute_result"
352 | }
353 | ],
354 | "source": [
355 | "y"
356 | ]
357 | },
358 | {
359 | "cell_type": "code",
360 | "execution_count": 16,
361 | "metadata": {},
362 | "outputs": [
363 | {
364 | "data": {
365 | "text/plain": [
366 | "6"
367 | ]
368 | },
369 | "execution_count": 16,
370 | "metadata": {},
371 | "output_type": "execute_result"
372 | }
373 | ],
374 | "source": [
375 | "z"
376 | ]
377 | },
378 | {
379 | "cell_type": "markdown",
380 | "metadata": {},
381 | "source": [
382 | "要素数が合わないとアンパックできない。"
383 | ]
384 | },
385 | {
386 | "cell_type": "code",
387 | "execution_count": 17,
388 | "metadata": {
389 | "tags": [
390 | "raises-exception"
391 | ]
392 | },
393 | "outputs": [
394 | {
395 | "ename": "ValueError",
396 | "evalue": "too many values to unpack (expected 2)",
397 | "output_type": "error",
398 | "traceback": [
399 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
400 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
401 | "\u001b[0;32m/tmp/ipykernel_204970/2108149690.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
402 | "\u001b[0;31mValueError\u001b[0m: too many values to unpack (expected 2)"
403 | ]
404 | }
405 | ],
406 | "source": [
407 | "x, y = t"
408 | ]
409 | },
410 | {
411 | "cell_type": "code",
412 | "execution_count": 18,
413 | "metadata": {
414 | "tags": [
415 | "raises-exception"
416 | ]
417 | },
418 | "outputs": [
419 | {
420 | "ename": "ValueError",
421 | "evalue": "not enough values to unpack (expected 4, got 3)",
422 | "output_type": "error",
423 | "traceback": [
424 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
425 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
426 | "\u001b[0;32m/tmp/ipykernel_204970/2150772074.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mz\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
427 | "\u001b[0;31mValueError\u001b[0m: not enough values to unpack (expected 4, got 3)"
428 | ]
429 | }
430 | ],
431 | "source": [
432 | "x, y, z, a = t"
433 | ]
434 | },
435 | {
436 | "cell_type": "markdown",
437 | "metadata": {},
438 | "source": [
439 | "カンマ(`,`)で区切ることで、複数の変数に値をまとめて代入できるのは、右辺の複数の値がタプルにまとめられ(「パック」と呼ばれる)、そのタプルの各要素が左辺でアンパックされて代入されることによる。"
440 | ]
441 | },
442 | {
443 | "cell_type": "code",
444 | "execution_count": 19,
445 | "metadata": {},
446 | "outputs": [],
447 | "source": [
448 | "x, y, z = 1, 3, 5"
449 | ]
450 | },
451 | {
452 | "cell_type": "code",
453 | "execution_count": 20,
454 | "metadata": {},
455 | "outputs": [
456 | {
457 | "data": {
458 | "text/plain": [
459 | "1"
460 | ]
461 | },
462 | "execution_count": 20,
463 | "metadata": {},
464 | "output_type": "execute_result"
465 | }
466 | ],
467 | "source": [
468 | "x"
469 | ]
470 | },
471 | {
472 | "cell_type": "code",
473 | "execution_count": 21,
474 | "metadata": {},
475 | "outputs": [
476 | {
477 | "data": {
478 | "text/plain": [
479 | "3"
480 | ]
481 | },
482 | "execution_count": 21,
483 | "metadata": {},
484 | "output_type": "execute_result"
485 | }
486 | ],
487 | "source": [
488 | "y"
489 | ]
490 | },
491 | {
492 | "cell_type": "code",
493 | "execution_count": 22,
494 | "metadata": {},
495 | "outputs": [
496 | {
497 | "data": {
498 | "text/plain": [
499 | "5"
500 | ]
501 | },
502 | "execution_count": 22,
503 | "metadata": {},
504 | "output_type": "execute_result"
505 | }
506 | ],
507 | "source": [
508 | "z"
509 | ]
510 | },
511 | {
512 | "cell_type": "markdown",
513 | "metadata": {},
514 | "source": [
515 | "ひとつのセルの中で複数の変数や値をカンマで区切って評価させ、コードセルの出力として確認できるのは、カンマで区切った値がタプルとしてパックされるからである。"
516 | ]
517 | },
518 | {
519 | "cell_type": "code",
520 | "execution_count": 23,
521 | "metadata": {},
522 | "outputs": [
523 | {
524 | "data": {
525 | "text/plain": [
526 | "(1, 3, 5, 7)"
527 | ]
528 | },
529 | "execution_count": 23,
530 | "metadata": {},
531 | "output_type": "execute_result"
532 | }
533 | ],
534 | "source": [
535 | "x, y, z, 7"
536 | ]
537 | },
538 | {
539 | "cell_type": "markdown",
540 | "metadata": {},
541 | "source": [
542 | "一時変数を使うこと無く、以下のコードで変数の値の交換ができるのは、タプルのパックとアンパックによる動作である。"
543 | ]
544 | },
545 | {
546 | "cell_type": "code",
547 | "execution_count": 24,
548 | "metadata": {},
549 | "outputs": [],
550 | "source": [
551 | "y, z, x = x, y, z"
552 | ]
553 | },
554 | {
555 | "cell_type": "code",
556 | "execution_count": 25,
557 | "metadata": {},
558 | "outputs": [
559 | {
560 | "data": {
561 | "text/plain": [
562 | "(5, 1, 3)"
563 | ]
564 | },
565 | "execution_count": 25,
566 | "metadata": {},
567 | "output_type": "execute_result"
568 | }
569 | ],
570 | "source": [
571 | "x, y, z"
572 | ]
573 | },
574 | {
575 | "cell_type": "markdown",
576 | "metadata": {},
577 | "source": [
578 | "関数が複数の値を返すことができるのは、関数の戻り値がタプルに変換(パック)されるからである。"
579 | ]
580 | },
581 | {
582 | "cell_type": "code",
583 | "execution_count": 26,
584 | "metadata": {},
585 | "outputs": [],
586 | "source": [
587 | "def fg(x):\n",
588 | " return x ** 2 - 2, 2 * x"
589 | ]
590 | },
591 | {
592 | "cell_type": "code",
593 | "execution_count": 27,
594 | "metadata": {},
595 | "outputs": [],
596 | "source": [
597 | "r = fg(1)"
598 | ]
599 | },
600 | {
601 | "cell_type": "code",
602 | "execution_count": 28,
603 | "metadata": {},
604 | "outputs": [
605 | {
606 | "data": {
607 | "text/plain": [
608 | "(-1, 2)"
609 | ]
610 | },
611 | "execution_count": 28,
612 | "metadata": {},
613 | "output_type": "execute_result"
614 | }
615 | ],
616 | "source": [
617 | "r"
618 | ]
619 | },
620 | {
621 | "cell_type": "code",
622 | "execution_count": 29,
623 | "metadata": {},
624 | "outputs": [
625 | {
626 | "data": {
627 | "text/plain": [
628 | "tuple"
629 | ]
630 | },
631 | "execution_count": 29,
632 | "metadata": {},
633 | "output_type": "execute_result"
634 | }
635 | ],
636 | "source": [
637 | "type(r)"
638 | ]
639 | },
640 | {
641 | "cell_type": "code",
642 | "execution_count": 30,
643 | "metadata": {},
644 | "outputs": [],
645 | "source": [
646 | "fx, gx = r"
647 | ]
648 | },
649 | {
650 | "cell_type": "code",
651 | "execution_count": 31,
652 | "metadata": {},
653 | "outputs": [
654 | {
655 | "data": {
656 | "text/plain": [
657 | "-1"
658 | ]
659 | },
660 | "execution_count": 31,
661 | "metadata": {},
662 | "output_type": "execute_result"
663 | }
664 | ],
665 | "source": [
666 | "fx"
667 | ]
668 | },
669 | {
670 | "cell_type": "code",
671 | "execution_count": 32,
672 | "metadata": {},
673 | "outputs": [
674 | {
675 | "data": {
676 | "text/plain": [
677 | "2"
678 | ]
679 | },
680 | "execution_count": 32,
681 | "metadata": {},
682 | "output_type": "execute_result"
683 | }
684 | ],
685 | "source": [
686 | "gx"
687 | ]
688 | },
689 | {
690 | "cell_type": "markdown",
691 | "metadata": {},
692 | "source": [
693 | "リストから要素をアンパックすることもできる。"
694 | ]
695 | },
696 | {
697 | "cell_type": "code",
698 | "execution_count": 33,
699 | "metadata": {},
700 | "outputs": [],
701 | "source": [
702 | "a = [0, 2, 4]\n",
703 | "x, y, z = a"
704 | ]
705 | },
706 | {
707 | "cell_type": "code",
708 | "execution_count": 34,
709 | "metadata": {},
710 | "outputs": [
711 | {
712 | "data": {
713 | "text/plain": [
714 | "0"
715 | ]
716 | },
717 | "execution_count": 34,
718 | "metadata": {},
719 | "output_type": "execute_result"
720 | }
721 | ],
722 | "source": [
723 | "x"
724 | ]
725 | },
726 | {
727 | "cell_type": "code",
728 | "execution_count": 35,
729 | "metadata": {},
730 | "outputs": [
731 | {
732 | "data": {
733 | "text/plain": [
734 | "2"
735 | ]
736 | },
737 | "execution_count": 35,
738 | "metadata": {},
739 | "output_type": "execute_result"
740 | }
741 | ],
742 | "source": [
743 | "y"
744 | ]
745 | },
746 | {
747 | "cell_type": "code",
748 | "execution_count": 36,
749 | "metadata": {},
750 | "outputs": [
751 | {
752 | "data": {
753 | "text/plain": [
754 | "4"
755 | ]
756 | },
757 | "execution_count": 36,
758 | "metadata": {},
759 | "output_type": "execute_result"
760 | }
761 | ],
762 | "source": [
763 | "z"
764 | ]
765 | },
766 | {
767 | "cell_type": "markdown",
768 | "metadata": {},
769 | "source": [
770 | "## 特殊なタプルの作成"
771 | ]
772 | },
773 | {
774 | "cell_type": "markdown",
775 | "metadata": {},
776 | "source": [
777 | "1つの要素からなるタプルを作成する目的で、以下のコードを実行してもタプルにはならない。"
778 | ]
779 | },
780 | {
781 | "cell_type": "code",
782 | "execution_count": 37,
783 | "metadata": {},
784 | "outputs": [],
785 | "source": [
786 | "t = (1)"
787 | ]
788 | },
789 | {
790 | "cell_type": "code",
791 | "execution_count": 38,
792 | "metadata": {},
793 | "outputs": [
794 | {
795 | "data": {
796 | "text/plain": [
797 | "1"
798 | ]
799 | },
800 | "execution_count": 38,
801 | "metadata": {},
802 | "output_type": "execute_result"
803 | }
804 | ],
805 | "source": [
806 | "t"
807 | ]
808 | },
809 | {
810 | "cell_type": "code",
811 | "execution_count": 39,
812 | "metadata": {},
813 | "outputs": [
814 | {
815 | "data": {
816 | "text/plain": [
817 | "int"
818 | ]
819 | },
820 | "execution_count": 39,
821 | "metadata": {},
822 | "output_type": "execute_result"
823 | }
824 | ],
825 | "source": [
826 | "type(t)"
827 | ]
828 | },
829 | {
830 | "cell_type": "markdown",
831 | "metadata": {},
832 | "source": [
833 | "1つの要素からなるタプルを作成するには、末尾にカンマ`,`を付ける。"
834 | ]
835 | },
836 | {
837 | "cell_type": "code",
838 | "execution_count": 40,
839 | "metadata": {},
840 | "outputs": [],
841 | "source": [
842 | "t = (1,)"
843 | ]
844 | },
845 | {
846 | "cell_type": "code",
847 | "execution_count": 41,
848 | "metadata": {},
849 | "outputs": [
850 | {
851 | "data": {
852 | "text/plain": [
853 | "(1,)"
854 | ]
855 | },
856 | "execution_count": 41,
857 | "metadata": {},
858 | "output_type": "execute_result"
859 | }
860 | ],
861 | "source": [
862 | "t"
863 | ]
864 | },
865 | {
866 | "cell_type": "markdown",
867 | "metadata": {},
868 | "source": [
869 | "空のタプルは`tuple`関数を用いて作る。"
870 | ]
871 | },
872 | {
873 | "cell_type": "code",
874 | "execution_count": 42,
875 | "metadata": {},
876 | "outputs": [],
877 | "source": [
878 | "t = tuple()"
879 | ]
880 | },
881 | {
882 | "cell_type": "code",
883 | "execution_count": 43,
884 | "metadata": {},
885 | "outputs": [
886 | {
887 | "data": {
888 | "text/plain": [
889 | "()"
890 | ]
891 | },
892 | "execution_count": 43,
893 | "metadata": {},
894 | "output_type": "execute_result"
895 | }
896 | ],
897 | "source": [
898 | "t"
899 | ]
900 | },
901 | {
902 | "cell_type": "markdown",
903 | "metadata": {},
904 | "source": [
905 | "## リストとタプルの相互変換"
906 | ]
907 | },
908 | {
909 | "cell_type": "markdown",
910 | "metadata": {},
911 | "source": [
912 | "オブジェクトをリストからタプルに変換するには、[tuple](https://docs.python.org/ja/3/library/stdtypes.html#tuple)関数を呼び出す。"
913 | ]
914 | },
915 | {
916 | "cell_type": "code",
917 | "execution_count": 44,
918 | "metadata": {},
919 | "outputs": [],
920 | "source": [
921 | "a = [1, 3, 5]"
922 | ]
923 | },
924 | {
925 | "cell_type": "code",
926 | "execution_count": 45,
927 | "metadata": {},
928 | "outputs": [
929 | {
930 | "data": {
931 | "text/plain": [
932 | "[1, 3, 5]"
933 | ]
934 | },
935 | "execution_count": 45,
936 | "metadata": {},
937 | "output_type": "execute_result"
938 | }
939 | ],
940 | "source": [
941 | "a"
942 | ]
943 | },
944 | {
945 | "cell_type": "code",
946 | "execution_count": 46,
947 | "metadata": {},
948 | "outputs": [
949 | {
950 | "data": {
951 | "text/plain": [
952 | "list"
953 | ]
954 | },
955 | "execution_count": 46,
956 | "metadata": {},
957 | "output_type": "execute_result"
958 | }
959 | ],
960 | "source": [
961 | "type(a)"
962 | ]
963 | },
964 | {
965 | "cell_type": "code",
966 | "execution_count": 47,
967 | "metadata": {},
968 | "outputs": [],
969 | "source": [
970 | "b = tuple(a)"
971 | ]
972 | },
973 | {
974 | "cell_type": "code",
975 | "execution_count": 48,
976 | "metadata": {},
977 | "outputs": [
978 | {
979 | "data": {
980 | "text/plain": [
981 | "(1, 3, 5)"
982 | ]
983 | },
984 | "execution_count": 48,
985 | "metadata": {},
986 | "output_type": "execute_result"
987 | }
988 | ],
989 | "source": [
990 | "b"
991 | ]
992 | },
993 | {
994 | "cell_type": "code",
995 | "execution_count": 49,
996 | "metadata": {},
997 | "outputs": [
998 | {
999 | "data": {
1000 | "text/plain": [
1001 | "tuple"
1002 | ]
1003 | },
1004 | "execution_count": 49,
1005 | "metadata": {},
1006 | "output_type": "execute_result"
1007 | }
1008 | ],
1009 | "source": [
1010 | "type(b)"
1011 | ]
1012 | },
1013 | {
1014 | "cell_type": "markdown",
1015 | "metadata": {},
1016 | "source": [
1017 | "オブジェクトをタプルからリストに変換するには[list](https://docs.python.org/ja/3/library/stdtypes.html#list)関数を呼び出す。"
1018 | ]
1019 | },
1020 | {
1021 | "cell_type": "code",
1022 | "execution_count": 50,
1023 | "metadata": {},
1024 | "outputs": [],
1025 | "source": [
1026 | "c = list(b)"
1027 | ]
1028 | },
1029 | {
1030 | "cell_type": "code",
1031 | "execution_count": 51,
1032 | "metadata": {},
1033 | "outputs": [
1034 | {
1035 | "data": {
1036 | "text/plain": [
1037 | "[1, 3, 5]"
1038 | ]
1039 | },
1040 | "execution_count": 51,
1041 | "metadata": {},
1042 | "output_type": "execute_result"
1043 | }
1044 | ],
1045 | "source": [
1046 | "c"
1047 | ]
1048 | },
1049 | {
1050 | "cell_type": "code",
1051 | "execution_count": 52,
1052 | "metadata": {},
1053 | "outputs": [
1054 | {
1055 | "data": {
1056 | "text/plain": [
1057 | "list"
1058 | ]
1059 | },
1060 | "execution_count": 52,
1061 | "metadata": {},
1062 | "output_type": "execute_result"
1063 | }
1064 | ],
1065 | "source": [
1066 | "type(c)"
1067 | ]
1068 | },
1069 | {
1070 | "cell_type": "markdown",
1071 | "metadata": {
1072 | "tags": [
1073 | "remove-cell"
1074 | ]
1075 | },
1076 | "source": [
1077 | "---\n",
1078 | "\n",
1079 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
1080 | ]
1081 | }
1082 | ],
1083 | "metadata": {
1084 | "@context": {
1085 | "CreativeWork": "http://schema.org/CreativeWork",
1086 | "Organization": "http://schema.org/Organization",
1087 | "Person": "http://schema.org/Person",
1088 | "author": "http://schema.org/author",
1089 | "copyrightHolder": "http://schema.org/copyrightHolder",
1090 | "copyrightYear": "http://schema.org/copyrightYear",
1091 | "license": "http://schema.org/license",
1092 | "name": "http://schema.org/name",
1093 | "title": "http://schema.org/name",
1094 | "url": "http://schema.org/url"
1095 | },
1096 | "@type": "CreativeWork",
1097 | "author": [
1098 | {
1099 | "@type": "Person",
1100 | "name": "Naoaki Okazaki",
1101 | "url": "https://www.chokkan.org/"
1102 | }
1103 | ],
1104 | "copyrightHolder": [
1105 | {
1106 | "@type": "Person",
1107 | "name": "Naoaki Okazaki",
1108 | "url": "https://www.chokkan.org/"
1109 | }
1110 | ],
1111 | "copyrightYear": 2024,
1112 | "kernelspec": {
1113 | "display_name": "Python 3 (ipykernel)",
1114 | "language": "python",
1115 | "name": "python3"
1116 | },
1117 | "language_info": {
1118 | "codemirror_mode": {
1119 | "name": "ipython",
1120 | "version": 3
1121 | },
1122 | "file_extension": ".py",
1123 | "mimetype": "text/x-python",
1124 | "name": "python",
1125 | "nbconvert_exporter": "python",
1126 | "pygments_lexer": "ipython3",
1127 | "version": "3.10.12"
1128 | },
1129 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
1130 | "title": "Python早見帳"
1131 | },
1132 | "nbformat": 4,
1133 | "nbformat_minor": 4
1134 | }
1135 |
--------------------------------------------------------------------------------
/10set.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 集合\n",
8 | "\n",
9 | "## 基本\n",
10 | "\n",
11 | "集合はユニークな(重複のない)要素をまとめて保持する。「値」のない辞書と考えると分かりやすいかもしれない。"
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 1,
17 | "metadata": {},
18 | "outputs": [],
19 | "source": [
20 | "S = {'東京', '神奈川', '千葉', '埼玉'}"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": 2,
26 | "metadata": {},
27 | "outputs": [
28 | {
29 | "data": {
30 | "text/plain": [
31 | "{'千葉', '埼玉', '東京', '神奈川'}"
32 | ]
33 | },
34 | "execution_count": 2,
35 | "metadata": {},
36 | "output_type": "execute_result"
37 | }
38 | ],
39 | "source": [
40 | "S"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": 3,
46 | "metadata": {},
47 | "outputs": [
48 | {
49 | "data": {
50 | "text/plain": [
51 | "set"
52 | ]
53 | },
54 | "execution_count": 3,
55 | "metadata": {},
56 | "output_type": "execute_result"
57 | }
58 | ],
59 | "source": [
60 | "type(S)"
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": 4,
66 | "metadata": {},
67 | "outputs": [
68 | {
69 | "data": {
70 | "text/plain": [
71 | "4"
72 | ]
73 | },
74 | "execution_count": 4,
75 | "metadata": {},
76 | "output_type": "execute_result"
77 | }
78 | ],
79 | "source": [
80 | "len(S)"
81 | ]
82 | },
83 | {
84 | "cell_type": "markdown",
85 | "metadata": {},
86 | "source": [
87 | "集合に要素が含まれているかどうか`in`演算子で調べることができる。"
88 | ]
89 | },
90 | {
91 | "cell_type": "code",
92 | "execution_count": 5,
93 | "metadata": {},
94 | "outputs": [
95 | {
96 | "data": {
97 | "text/plain": [
98 | "True"
99 | ]
100 | },
101 | "execution_count": 5,
102 | "metadata": {},
103 | "output_type": "execute_result"
104 | }
105 | ],
106 | "source": [
107 | "'東京' in S"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 6,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "data": {
117 | "text/plain": [
118 | "False"
119 | ]
120 | },
121 | "execution_count": 6,
122 | "metadata": {},
123 | "output_type": "execute_result"
124 | }
125 | ],
126 | "source": [
127 | "'栃木' in S"
128 | ]
129 | },
130 | {
131 | "cell_type": "markdown",
132 | "metadata": {},
133 | "source": [
134 | "集合に要素を追加するには、addメソッドを用いる。"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 7,
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "S.add('栃木')"
144 | ]
145 | },
146 | {
147 | "cell_type": "code",
148 | "execution_count": 8,
149 | "metadata": {},
150 | "outputs": [
151 | {
152 | "data": {
153 | "text/plain": [
154 | "True"
155 | ]
156 | },
157 | "execution_count": 8,
158 | "metadata": {},
159 | "output_type": "execute_result"
160 | }
161 | ],
162 | "source": [
163 | "'栃木' in S"
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "metadata": {},
169 | "source": [
170 | "集合から要素を削除するには、removeメソッドを用いる。"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": 9,
176 | "metadata": {},
177 | "outputs": [],
178 | "source": [
179 | "S.remove('栃木')"
180 | ]
181 | },
182 | {
183 | "cell_type": "code",
184 | "execution_count": 10,
185 | "metadata": {},
186 | "outputs": [
187 | {
188 | "data": {
189 | "text/plain": [
190 | "False"
191 | ]
192 | },
193 | "execution_count": 10,
194 | "metadata": {},
195 | "output_type": "execute_result"
196 | }
197 | ],
198 | "source": [
199 | "'栃木' in S"
200 | ]
201 | },
202 | {
203 | "cell_type": "markdown",
204 | "metadata": {},
205 | "source": [
206 | "集合の要素になっていないものをremoveメソッドで取り除こうとすると、エラーになる。"
207 | ]
208 | },
209 | {
210 | "cell_type": "code",
211 | "execution_count": 11,
212 | "metadata": {
213 | "tags": [
214 | "raises-exception"
215 | ]
216 | },
217 | "outputs": [
218 | {
219 | "ename": "KeyError",
220 | "evalue": "'栃木'",
221 | "output_type": "error",
222 | "traceback": [
223 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
224 | "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
225 | "\u001b[0;32m/tmp/ipykernel_205042/85130292.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mS\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'栃木'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
226 | "\u001b[0;31mKeyError\u001b[0m: '栃木'"
227 | ]
228 | }
229 | ],
230 | "source": [
231 | "S.remove('栃木')"
232 | ]
233 | },
234 | {
235 | "cell_type": "markdown",
236 | "metadata": {},
237 | "source": [
238 | "集合の要素になっているときだけ削除するには、discardメソッドを用いる。"
239 | ]
240 | },
241 | {
242 | "cell_type": "code",
243 | "execution_count": 12,
244 | "metadata": {},
245 | "outputs": [],
246 | "source": [
247 | "S.discard('栃木')"
248 | ]
249 | },
250 | {
251 | "cell_type": "markdown",
252 | "metadata": {},
253 | "source": [
254 | "要素が空の集合(空集合)はset関数で作成する(`{}`は辞書となってしまうため、集合とは異なるオブジェクトになってしまう)。"
255 | ]
256 | },
257 | {
258 | "cell_type": "code",
259 | "execution_count": 13,
260 | "metadata": {},
261 | "outputs": [
262 | {
263 | "data": {
264 | "text/plain": [
265 | "set()"
266 | ]
267 | },
268 | "execution_count": 13,
269 | "metadata": {},
270 | "output_type": "execute_result"
271 | }
272 | ],
273 | "source": [
274 | "S = set()\n",
275 | "S"
276 | ]
277 | },
278 | {
279 | "cell_type": "markdown",
280 | "metadata": {},
281 | "source": [
282 | "## 集合の内包表記"
283 | ]
284 | },
285 | {
286 | "cell_type": "markdown",
287 | "metadata": {},
288 | "source": [
289 | "九九の3の段を表現する集合オブジェクトを作成してみる。"
290 | ]
291 | },
292 | {
293 | "cell_type": "code",
294 | "execution_count": 14,
295 | "metadata": {},
296 | "outputs": [
297 | {
298 | "data": {
299 | "text/plain": [
300 | "{0, 3, 6, 9, 12, 15, 18, 21, 24, 27}"
301 | ]
302 | },
303 | "execution_count": 14,
304 | "metadata": {},
305 | "output_type": "execute_result"
306 | }
307 | ],
308 | "source": [
309 | "m3 = set()\n",
310 | "for i in range(10):\n",
311 | " m3.add(i * 3)\n",
312 | "m3"
313 | ]
314 | },
315 | {
316 | "cell_type": "markdown",
317 | "metadata": {},
318 | "source": [
319 | "このオブジェクトは、次のように集合の内包表記で構築することもできる。「i times 3 for all i in the range of ten」のように英語読みすると分かりやすいかもしれない。"
320 | ]
321 | },
322 | {
323 | "cell_type": "code",
324 | "execution_count": 15,
325 | "metadata": {},
326 | "outputs": [
327 | {
328 | "data": {
329 | "text/plain": [
330 | "{0, 3, 6, 9, 12, 15, 18, 21, 24, 27}"
331 | ]
332 | },
333 | "execution_count": 15,
334 | "metadata": {},
335 | "output_type": "execute_result"
336 | }
337 | ],
338 | "source": [
339 | "m3n = {i*3 for i in range(10)}\n",
340 | "m3n"
341 | ]
342 | },
343 | {
344 | "cell_type": "markdown",
345 | "metadata": {},
346 | "source": [
347 | "また、「0から29の範囲の中で3で割ったあまりが0になる数字の集合」というアイディアに基づいた実装をすると、以下のようになる。"
348 | ]
349 | },
350 | {
351 | "cell_type": "code",
352 | "execution_count": 16,
353 | "metadata": {},
354 | "outputs": [
355 | {
356 | "data": {
357 | "text/plain": [
358 | "{0, 3, 6, 9, 12, 15, 18, 21, 24, 27}"
359 | ]
360 | },
361 | "execution_count": 16,
362 | "metadata": {},
363 | "output_type": "execute_result"
364 | }
365 | ],
366 | "source": [
367 | "m3nn = {i for i in range(30) if i % 3 == 0}\n",
368 | "m3nn"
369 | ]
370 | },
371 | {
372 | "cell_type": "markdown",
373 | "metadata": {},
374 | "source": [
375 | "集合の内包表記をネストさせることで、九九で出てくる数字を表す集合を作成できる。"
376 | ]
377 | },
378 | {
379 | "cell_type": "code",
380 | "execution_count": 17,
381 | "metadata": {},
382 | "outputs": [],
383 | "source": [
384 | "M = {i*j for j in range(10) for i in range(10)}"
385 | ]
386 | },
387 | {
388 | "cell_type": "code",
389 | "execution_count": 18,
390 | "metadata": {},
391 | "outputs": [
392 | {
393 | "data": {
394 | "text/plain": [
395 | "{0,\n",
396 | " 1,\n",
397 | " 2,\n",
398 | " 3,\n",
399 | " 4,\n",
400 | " 5,\n",
401 | " 6,\n",
402 | " 7,\n",
403 | " 8,\n",
404 | " 9,\n",
405 | " 10,\n",
406 | " 12,\n",
407 | " 14,\n",
408 | " 15,\n",
409 | " 16,\n",
410 | " 18,\n",
411 | " 20,\n",
412 | " 21,\n",
413 | " 24,\n",
414 | " 25,\n",
415 | " 27,\n",
416 | " 28,\n",
417 | " 30,\n",
418 | " 32,\n",
419 | " 35,\n",
420 | " 36,\n",
421 | " 40,\n",
422 | " 42,\n",
423 | " 45,\n",
424 | " 48,\n",
425 | " 49,\n",
426 | " 54,\n",
427 | " 56,\n",
428 | " 63,\n",
429 | " 64,\n",
430 | " 72,\n",
431 | " 81}"
432 | ]
433 | },
434 | "execution_count": 18,
435 | "metadata": {},
436 | "output_type": "execute_result"
437 | }
438 | ],
439 | "source": [
440 | "M"
441 | ]
442 | },
443 | {
444 | "cell_type": "markdown",
445 | "metadata": {},
446 | "source": [
447 | "## 集合間の演算"
448 | ]
449 | },
450 | {
451 | "cell_type": "markdown",
452 | "metadata": {},
453 | "source": [
454 | "$1$以上$n$以下の自然数を$\\mathbb{N}_n$と書くことにする。$1$以上$30$以下の$2$の倍数と$3$の倍数を表す集合はそれぞれ、\n",
455 | "\n",
456 | "$$\n",
457 | "M_2 = \\{i \\in \\mathbb{N}_{30} \\mid i \\equiv 0 \\pmod{2} \\} \\\\\n",
458 | "M_3 = \\{i \\in \\mathbb{N}_{30} \\mid i \\equiv 0 \\pmod{3} \\}\n",
459 | "$$\n",
460 | "\n",
461 | "と書ける。$\\mathbb{N}_{30}$と$M_2$、$M_3$をそれぞれ、集合型のオブジェクト`N`と`M2`、`M3`で表す。"
462 | ]
463 | },
464 | {
465 | "cell_type": "code",
466 | "execution_count": 19,
467 | "metadata": {},
468 | "outputs": [],
469 | "source": [
470 | "N = set(range(1, 31))\n",
471 | "M2 = {i for i in N if i % 2 == 0}\n",
472 | "M3 = {i for i in N if i % 3 == 0}"
473 | ]
474 | },
475 | {
476 | "cell_type": "code",
477 | "execution_count": 20,
478 | "metadata": {},
479 | "outputs": [
480 | {
481 | "data": {
482 | "text/plain": [
483 | "{2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}"
484 | ]
485 | },
486 | "execution_count": 20,
487 | "metadata": {},
488 | "output_type": "execute_result"
489 | }
490 | ],
491 | "source": [
492 | "M2"
493 | ]
494 | },
495 | {
496 | "cell_type": "code",
497 | "execution_count": 21,
498 | "metadata": {},
499 | "outputs": [
500 | {
501 | "data": {
502 | "text/plain": [
503 | "{3, 6, 9, 12, 15, 18, 21, 24, 27, 30}"
504 | ]
505 | },
506 | "execution_count": 21,
507 | "metadata": {},
508 | "output_type": "execute_result"
509 | }
510 | ],
511 | "source": [
512 | "M3"
513 | ]
514 | },
515 | {
516 | "cell_type": "markdown",
517 | "metadata": {},
518 | "source": [
519 | "$M_2$と$M_3$の積集合$M_2 \\cap M_3$は`&`演算子で求められる。"
520 | ]
521 | },
522 | {
523 | "cell_type": "code",
524 | "execution_count": 22,
525 | "metadata": {},
526 | "outputs": [
527 | {
528 | "data": {
529 | "text/plain": [
530 | "{6, 12, 18, 24, 30}"
531 | ]
532 | },
533 | "execution_count": 22,
534 | "metadata": {},
535 | "output_type": "execute_result"
536 | }
537 | ],
538 | "source": [
539 | "M2 & M3"
540 | ]
541 | },
542 | {
543 | "cell_type": "markdown",
544 | "metadata": {},
545 | "source": [
546 | "$M_2$と$M_3$の和集合$M_2 \\cup M_3$は`|`演算子で求められる。"
547 | ]
548 | },
549 | {
550 | "cell_type": "code",
551 | "execution_count": 23,
552 | "metadata": {},
553 | "outputs": [
554 | {
555 | "data": {
556 | "text/plain": [
557 | "{2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 26, 27, 28, 30}"
558 | ]
559 | },
560 | "execution_count": 23,
561 | "metadata": {},
562 | "output_type": "execute_result"
563 | }
564 | ],
565 | "source": [
566 | "M2 | M3"
567 | ]
568 | },
569 | {
570 | "cell_type": "markdown",
571 | "metadata": {},
572 | "source": [
573 | "$\\mathbb{N}_{30}$と$M_2$の差集合$\\mathbb{N}_{30} \\setminus M_2$は`-`演算子で求められる。"
574 | ]
575 | },
576 | {
577 | "cell_type": "code",
578 | "execution_count": 24,
579 | "metadata": {},
580 | "outputs": [
581 | {
582 | "data": {
583 | "text/plain": [
584 | "{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29}"
585 | ]
586 | },
587 | "execution_count": 24,
588 | "metadata": {},
589 | "output_type": "execute_result"
590 | }
591 | ],
592 | "source": [
593 | "N - M2"
594 | ]
595 | },
596 | {
597 | "cell_type": "markdown",
598 | "metadata": {},
599 | "source": [
600 | "$M_2$か$M_3$のいずれか一方に含まれる要素を集めた集合は`^`演算子で求められる。"
601 | ]
602 | },
603 | {
604 | "cell_type": "code",
605 | "execution_count": 25,
606 | "metadata": {},
607 | "outputs": [
608 | {
609 | "data": {
610 | "text/plain": [
611 | "{2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 21, 22, 26, 27, 28}"
612 | ]
613 | },
614 | "execution_count": 25,
615 | "metadata": {},
616 | "output_type": "execute_result"
617 | }
618 | ],
619 | "source": [
620 | "M2 ^ M3"
621 | ]
622 | },
623 | {
624 | "cell_type": "markdown",
625 | "metadata": {},
626 | "source": [
627 | "2つの集合が部分集合の関係にあるかどうかは、`<`演算子で調べられる。"
628 | ]
629 | },
630 | {
631 | "cell_type": "code",
632 | "execution_count": 26,
633 | "metadata": {},
634 | "outputs": [
635 | {
636 | "data": {
637 | "text/plain": [
638 | "True"
639 | ]
640 | },
641 | "execution_count": 26,
642 | "metadata": {},
643 | "output_type": "execute_result"
644 | }
645 | ],
646 | "source": [
647 | "M2 < N"
648 | ]
649 | },
650 | {
651 | "cell_type": "code",
652 | "execution_count": 27,
653 | "metadata": {},
654 | "outputs": [
655 | {
656 | "data": {
657 | "text/plain": [
658 | "False"
659 | ]
660 | },
661 | "execution_count": 27,
662 | "metadata": {},
663 | "output_type": "execute_result"
664 | }
665 | ],
666 | "source": [
667 | "M2 < M3"
668 | ]
669 | },
670 | {
671 | "cell_type": "markdown",
672 | "metadata": {},
673 | "source": [
674 | "2つの集合の要素が全て等しい/等しくないかは、`==`演算子および`!=`演算子で調べられる。"
675 | ]
676 | },
677 | {
678 | "cell_type": "code",
679 | "execution_count": 28,
680 | "metadata": {},
681 | "outputs": [
682 | {
683 | "data": {
684 | "text/plain": [
685 | "{2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}"
686 | ]
687 | },
688 | "execution_count": 28,
689 | "metadata": {},
690 | "output_type": "execute_result"
691 | }
692 | ],
693 | "source": [
694 | "X = set(range(2, 31, 2))\n",
695 | "X"
696 | ]
697 | },
698 | {
699 | "cell_type": "code",
700 | "execution_count": 29,
701 | "metadata": {},
702 | "outputs": [
703 | {
704 | "data": {
705 | "text/plain": [
706 | "True"
707 | ]
708 | },
709 | "execution_count": 29,
710 | "metadata": {},
711 | "output_type": "execute_result"
712 | }
713 | ],
714 | "source": [
715 | "X == M2"
716 | ]
717 | },
718 | {
719 | "cell_type": "code",
720 | "execution_count": 30,
721 | "metadata": {},
722 | "outputs": [
723 | {
724 | "data": {
725 | "text/plain": [
726 | "False"
727 | ]
728 | },
729 | "execution_count": 30,
730 | "metadata": {},
731 | "output_type": "execute_result"
732 | }
733 | ],
734 | "source": [
735 | "X != M2"
736 | ]
737 | },
738 | {
739 | "cell_type": "code",
740 | "execution_count": 31,
741 | "metadata": {},
742 | "outputs": [
743 | {
744 | "data": {
745 | "text/plain": [
746 | "False"
747 | ]
748 | },
749 | "execution_count": 31,
750 | "metadata": {},
751 | "output_type": "execute_result"
752 | }
753 | ],
754 | "source": [
755 | "X == M3"
756 | ]
757 | },
758 | {
759 | "cell_type": "code",
760 | "execution_count": 32,
761 | "metadata": {},
762 | "outputs": [
763 | {
764 | "data": {
765 | "text/plain": [
766 | "True"
767 | ]
768 | },
769 | "execution_count": 32,
770 | "metadata": {},
771 | "output_type": "execute_result"
772 | }
773 | ],
774 | "source": [
775 | "X != M3"
776 | ]
777 | },
778 | {
779 | "cell_type": "markdown",
780 | "metadata": {
781 | "tags": [
782 | "remove-cell"
783 | ]
784 | },
785 | "source": [
786 | "---\n",
787 | "\n",
788 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
789 | ]
790 | }
791 | ],
792 | "metadata": {
793 | "@context": {
794 | "CreativeWork": "http://schema.org/CreativeWork",
795 | "Organization": "http://schema.org/Organization",
796 | "Person": "http://schema.org/Person",
797 | "author": "http://schema.org/author",
798 | "copyrightHolder": "http://schema.org/copyrightHolder",
799 | "copyrightYear": "http://schema.org/copyrightYear",
800 | "license": "http://schema.org/license",
801 | "name": "http://schema.org/name",
802 | "title": "http://schema.org/name",
803 | "url": "http://schema.org/url"
804 | },
805 | "@type": "CreativeWork",
806 | "author": [
807 | {
808 | "@type": "Person",
809 | "name": "Naoaki Okazaki",
810 | "url": "https://www.chokkan.org/"
811 | }
812 | ],
813 | "copyrightHolder": [
814 | {
815 | "@type": "Person",
816 | "name": "Naoaki Okazaki",
817 | "url": "https://www.chokkan.org/"
818 | }
819 | ],
820 | "copyrightYear": 2024,
821 | "kernelspec": {
822 | "display_name": "Python 3 (ipykernel)",
823 | "language": "python",
824 | "name": "python3"
825 | },
826 | "language_info": {
827 | "codemirror_mode": {
828 | "name": "ipython",
829 | "version": 3
830 | },
831 | "file_extension": ".py",
832 | "mimetype": "text/x-python",
833 | "name": "python",
834 | "nbconvert_exporter": "python",
835 | "pygments_lexer": "ipython3",
836 | "version": "3.10.12"
837 | },
838 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
839 | "title": "Python早見帳"
840 | },
841 | "nbformat": 4,
842 | "nbformat_minor": 4
843 | }
844 |
--------------------------------------------------------------------------------
/11file.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# ファイルの入出力"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "## ファイルへの書き込み"
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "ここでは、以下のオブジェクトの内容をテキストファイルとして書き出す例を示す。"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {},
28 | "outputs": [],
29 | "source": [
30 | "d = {\n",
31 | " '東京': ['とうきょう', 'Tokyo'],\n",
32 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
33 | " '千葉': ['ちば', 'Chiba'],\n",
34 | " '埼玉': ['さいたま', 'Saitama']\n",
35 | "}"
36 | ]
37 | },
38 | {
39 | "cell_type": "markdown",
40 | "metadata": {},
41 | "source": [
42 | "まず、インタプリタ上でこのオブジェクトの内容を表示するコードは以下の通り。"
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": 2,
48 | "metadata": {},
49 | "outputs": [
50 | {
51 | "name": "stdout",
52 | "output_type": "stream",
53 | "text": [
54 | "東京 とうきょう Tokyo\n",
55 | "神奈川 かながわ Kanagawa\n",
56 | "千葉 ちば Chiba\n",
57 | "埼玉 さいたま Saitama\n"
58 | ]
59 | }
60 | ],
61 | "source": [
62 | "for ja, (yomi, en) in d.items():\n",
63 | " print(ja, yomi, en)"
64 | ]
65 | },
66 | {
67 | "cell_type": "markdown",
68 | "metadata": {},
69 | "source": [
70 | "ファイルを書き込みモードで開くには、[open](https://docs.python.org/ja/3/library/functions.html#open)関数の第1引数にファイル名、第2引数に`'w'`を指定し、戻り値としてファイルオブジェクトを受け取る。そして、print関数を呼び出すときに、`file`という引数にファイルオブジェクトを渡す。ファイルへの書き出しが終わったら、close関数でファイルを閉じる。"
71 | ]
72 | },
73 | {
74 | "cell_type": "code",
75 | "execution_count": 3,
76 | "metadata": {},
77 | "outputs": [],
78 | "source": [
79 | "fo = open('prefecture.txt', 'w')\n",
80 | "for ja, (yomi, en) in d.items():\n",
81 | " print(ja, yomi, en, file=fo)\n",
82 | "fo.close()"
83 | ]
84 | },
85 | {
86 | "cell_type": "markdown",
87 | "metadata": {},
88 | "source": [
89 | "catコマンド(ファイルの内容を表示するコマンド)で出力内容を確認してみる。"
90 | ]
91 | },
92 | {
93 | "cell_type": "code",
94 | "execution_count": 4,
95 | "metadata": {},
96 | "outputs": [
97 | {
98 | "name": "stdout",
99 | "output_type": "stream",
100 | "text": [
101 | "東京 とうきょう Tokyo\n",
102 | "神奈川 かながわ Kanagawa\n",
103 | "千葉 ちば Chiba\n",
104 | "埼玉 さいたま Saitama\n"
105 | ]
106 | }
107 | ],
108 | "source": [
109 | "!cat prefecture.txt"
110 | ]
111 | },
112 | {
113 | "cell_type": "markdown",
114 | "metadata": {},
115 | "source": [
116 | "なお、close関数を呼び出すのを忘れると、ファイルに内容が書き込まれないことがある。"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "execution_count": 5,
122 | "metadata": {},
123 | "outputs": [],
124 | "source": [
125 | "fo = open('prefecture2.txt', 'w')\n",
126 | "for ja, (yomi, en) in d.items():\n",
127 | " print(ja, yomi, en, file=fo)"
128 | ]
129 | },
130 | {
131 | "cell_type": "markdown",
132 | "metadata": {},
133 | "source": [
134 | "catコマンドを呼び出しても、書き出した内容が表示されない。"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 6,
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "!cat prefecture2.txt"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {},
149 | "source": [
150 | "ここでclose関数を呼び出すと、ファイルに内容が書き込まれる。"
151 | ]
152 | },
153 | {
154 | "cell_type": "code",
155 | "execution_count": 7,
156 | "metadata": {},
157 | "outputs": [],
158 | "source": [
159 | "fo.close()"
160 | ]
161 | },
162 | {
163 | "cell_type": "markdown",
164 | "metadata": {},
165 | "source": [
166 | "今度はcatコマンドで書き出した内容が表示された。"
167 | ]
168 | },
169 | {
170 | "cell_type": "code",
171 | "execution_count": 8,
172 | "metadata": {},
173 | "outputs": [
174 | {
175 | "name": "stdout",
176 | "output_type": "stream",
177 | "text": [
178 | "東京 とうきょう Tokyo\n",
179 | "神奈川 かながわ Kanagawa\n",
180 | "千葉 ちば Chiba\n",
181 | "埼玉 さいたま Saitama\n"
182 | ]
183 | }
184 | ],
185 | "source": [
186 | "!cat prefecture2.txt"
187 | ]
188 | },
189 | {
190 | "cell_type": "markdown",
191 | "metadata": {},
192 | "source": [
193 | "ファイルの閉じ忘れを防ぐ構文として[with](https://docs.python.org/ja/3/reference/compound_stmts.html#with)文が便利。普段から以下のように記述しておくとよい。"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": 9,
199 | "metadata": {},
200 | "outputs": [],
201 | "source": [
202 | "with open('prefecture3.txt', 'w') as fo:\n",
203 | " for ja, (yomi, en) in d.items():\n",
204 | " print(ja, yomi, en, file=fo)"
205 | ]
206 | },
207 | {
208 | "cell_type": "code",
209 | "execution_count": 10,
210 | "metadata": {},
211 | "outputs": [
212 | {
213 | "name": "stdout",
214 | "output_type": "stream",
215 | "text": [
216 | "東京 とうきょう Tokyo\n",
217 | "神奈川 かながわ Kanagawa\n",
218 | "千葉 ちば Chiba\n",
219 | "埼玉 さいたま Saitama\n"
220 | ]
221 | }
222 | ],
223 | "source": [
224 | "!cat prefecture3.txt"
225 | ]
226 | },
227 | {
228 | "cell_type": "markdown",
229 | "metadata": {},
230 | "source": [
231 | "print関数の代わりに、ファイルオブジェクトの[write](https://docs.python.org/ja/3/library/io.html#io.BufferedIOBase.write)関数を用い、文字列を書き出すこともできる。write関数を用いる場合は、改行が出力されないので、出力する文字列の中に改行を含める。"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": 11,
237 | "metadata": {},
238 | "outputs": [],
239 | "source": [
240 | "with open('prefecture4.txt', 'w') as fo:\n",
241 | " for ja, (yomi, en) in d.items():\n",
242 | " fo.write(f'{ja} {yomi} {en}\\n')"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": 12,
248 | "metadata": {},
249 | "outputs": [
250 | {
251 | "name": "stdout",
252 | "output_type": "stream",
253 | "text": [
254 | "東京 とうきょう Tokyo\n",
255 | "神奈川 かながわ Kanagawa\n",
256 | "千葉 ちば Chiba\n",
257 | "埼玉 さいたま Saitama\n"
258 | ]
259 | }
260 | ],
261 | "source": [
262 | "!cat prefecture4.txt"
263 | ]
264 | },
265 | {
266 | "cell_type": "markdown",
267 | "metadata": {},
268 | "source": [
269 | "## ファイルからの読み込み"
270 | ]
271 | },
272 | {
273 | "cell_type": "markdown",
274 | "metadata": {},
275 | "source": [
276 | "ファイルを読み込みモードで開くには、[open](https://docs.python.org/ja/3/library/functions.html#open)関数の第1引数にファイル名を指定するだけでよい(第2引数に`'r'`がデフォルトで指定される)。ファイルオブジェクトに対してfor文で反復処理を行うと、ファイルから1行ずつ読み出すことができる。ただし、読み出された各行(`line`)の末尾の改行は取り除かれない。"
277 | ]
278 | },
279 | {
280 | "cell_type": "code",
281 | "execution_count": 13,
282 | "metadata": {},
283 | "outputs": [
284 | {
285 | "name": "stdout",
286 | "output_type": "stream",
287 | "text": [
288 | "東京 とうきょう Tokyo\n",
289 | "\n",
290 | "神奈川 かながわ Kanagawa\n",
291 | "\n",
292 | "千葉 ちば Chiba\n",
293 | "\n",
294 | "埼玉 さいたま Saitama\n",
295 | "\n"
296 | ]
297 | }
298 | ],
299 | "source": [
300 | "with open('prefecture.txt') as fi:\n",
301 | " for line in fi:\n",
302 | " print(line)"
303 | ]
304 | },
305 | {
306 | "cell_type": "markdown",
307 | "metadata": {},
308 | "source": [
309 | "末尾の改行を取り除くには、strip関数などを用いる。"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": 14,
315 | "metadata": {},
316 | "outputs": [
317 | {
318 | "name": "stdout",
319 | "output_type": "stream",
320 | "text": [
321 | "東京 とうきょう Tokyo\n",
322 | "神奈川 かながわ Kanagawa\n",
323 | "千葉 ちば Chiba\n",
324 | "埼玉 さいたま Saitama\n"
325 | ]
326 | }
327 | ],
328 | "source": [
329 | "with open('prefecture.txt') as fi:\n",
330 | " for line in fi:\n",
331 | " print(line.strip('\\n'))"
332 | ]
333 | },
334 | {
335 | "cell_type": "markdown",
336 | "metadata": {},
337 | "source": [
338 | "各行はスペース区切りで値が格納されているので、split関数で値を取り出し、辞書にセットすることで、元のオブジェクト`d`を復元できる。"
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": 15,
344 | "metadata": {},
345 | "outputs": [],
346 | "source": [
347 | "r = {}\n",
348 | "with open('prefecture.txt') as fi:\n",
349 | " for line in fi:\n",
350 | " values = line.strip('\\n').split(' ')\n",
351 | " r[values[0]] = values[1:]"
352 | ]
353 | },
354 | {
355 | "cell_type": "code",
356 | "execution_count": 16,
357 | "metadata": {},
358 | "outputs": [
359 | {
360 | "data": {
361 | "text/plain": [
362 | "{'東京': ['とうきょう', 'Tokyo'],\n",
363 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
364 | " '千葉': ['ちば', 'Chiba'],\n",
365 | " '埼玉': ['さいたま', 'Saitama']}"
366 | ]
367 | },
368 | "execution_count": 16,
369 | "metadata": {},
370 | "output_type": "execute_result"
371 | }
372 | ],
373 | "source": [
374 | "r"
375 | ]
376 | },
377 | {
378 | "cell_type": "markdown",
379 | "metadata": {},
380 | "source": [
381 | "## CSV"
382 | ]
383 | },
384 | {
385 | "cell_type": "markdown",
386 | "metadata": {},
387 | "source": [
388 | "コンマ区切り形式(CSV)ファイルの読み書きには、csvモジュールが便利である。"
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 17,
394 | "metadata": {},
395 | "outputs": [],
396 | "source": [
397 | "import csv"
398 | ]
399 | },
400 | {
401 | "cell_type": "markdown",
402 | "metadata": {},
403 | "source": [
404 | "以下のオブジェクトをCSV形式で書き出す例を示す。。"
405 | ]
406 | },
407 | {
408 | "cell_type": "code",
409 | "execution_count": 18,
410 | "metadata": {},
411 | "outputs": [],
412 | "source": [
413 | "d = {\n",
414 | " '東京': ['とうきょう', 'Tokyo'],\n",
415 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
416 | " '千葉': ['ちば', 'Chiba'],\n",
417 | " '埼玉': ['さいたま', 'Saitama']\n",
418 | "}"
419 | ]
420 | },
421 | {
422 | "cell_type": "markdown",
423 | "metadata": {},
424 | "source": [
425 | "CSVファイルに書き出すには、[csv.writer](https://docs.python.org/ja/3/library/csv.html#csv.writer)オブジェクトを作成し、[writerow](https://docs.python.org/ja/3/library/csv.html#csv.writer)メソッドなどを呼び出せばよい。"
426 | ]
427 | },
428 | {
429 | "cell_type": "code",
430 | "execution_count": 19,
431 | "metadata": {},
432 | "outputs": [],
433 | "source": [
434 | "with open('prefecture.csv', 'w') as fo:\n",
435 | " writer = csv.writer(fo)\n",
436 | " for ja, (yomi, en) in d.items():\n",
437 | " writer.writerow((ja, yomi, en))"
438 | ]
439 | },
440 | {
441 | "cell_type": "code",
442 | "execution_count": 20,
443 | "metadata": {},
444 | "outputs": [
445 | {
446 | "name": "stdout",
447 | "output_type": "stream",
448 | "text": [
449 | "東京,とうきょう,Tokyo\n",
450 | "神奈川,かながわ,Kanagawa\n",
451 | "千葉,ちば,Chiba\n",
452 | "埼玉,さいたま,Saitama\n"
453 | ]
454 | }
455 | ],
456 | "source": [
457 | "!cat prefecture.csv"
458 | ]
459 | },
460 | {
461 | "cell_type": "markdown",
462 | "metadata": {},
463 | "source": [
464 | "CSVファイルを読み込むには、[csv.reader](https://docs.python.org/ja/3/library/csv.html#reader-objects)を用いる。"
465 | ]
466 | },
467 | {
468 | "cell_type": "code",
469 | "execution_count": 21,
470 | "metadata": {},
471 | "outputs": [
472 | {
473 | "data": {
474 | "text/plain": [
475 | "{'東京': ['とうきょう', 'Tokyo'],\n",
476 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
477 | " '千葉': ['ちば', 'Chiba'],\n",
478 | " '埼玉': ['さいたま', 'Saitama']}"
479 | ]
480 | },
481 | "execution_count": 21,
482 | "metadata": {},
483 | "output_type": "execute_result"
484 | }
485 | ],
486 | "source": [
487 | "r = {}\n",
488 | "with open('prefecture.csv') as fi:\n",
489 | " reader = csv.reader(fi)\n",
490 | " for row in reader:\n",
491 | " r[row[0]] = row[1:]\n",
492 | "r"
493 | ]
494 | },
495 | {
496 | "cell_type": "markdown",
497 | "metadata": {},
498 | "source": [
499 | "## JSON\n",
500 | "\n",
501 | "JavaScript Object Notation (JSON) は、オブジェクトの内容をJavaScriptとして解釈できる形式で表現するものである。オブジェクトをCSV形式で保存する場合、オブジェクトの構造と平坦化されたカンマ区切りのリストの間で読み書きの処理が必要であったが、JSON形式を用いると構造を保持したままオブジェクトのそのまま書き出すことができる。最近では、多くのプログラミング言語でJSONを読み書きできるようになっているため、プログラミング言語に依存せずにデータのやり取りを行うために用いられる。JSON形式の読み書きを行うには、[json](https://docs.python.org/ja/3/library/json.html)モジュールをロードする。"
502 | ]
503 | },
504 | {
505 | "cell_type": "code",
506 | "execution_count": 22,
507 | "metadata": {},
508 | "outputs": [],
509 | "source": [
510 | "import json"
511 | ]
512 | },
513 | {
514 | "cell_type": "markdown",
515 | "metadata": {},
516 | "source": [
517 | "以下のオブジェクトをJSON形式で書き出す例を示す。。"
518 | ]
519 | },
520 | {
521 | "cell_type": "code",
522 | "execution_count": 23,
523 | "metadata": {},
524 | "outputs": [],
525 | "source": [
526 | "d = {\n",
527 | " '東京': ['とうきょう', 'Tokyo'],\n",
528 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
529 | " '千葉': ['ちば', 'Chiba'],\n",
530 | " '埼玉': ['さいたま', 'Saitama']\n",
531 | "}"
532 | ]
533 | },
534 | {
535 | "cell_type": "markdown",
536 | "metadata": {},
537 | "source": [
538 | "オブジェクトをJSON形式でファイルに書き出すには、[json.dump](https://docs.python.org/ja/3/library/json.html#json.dump)関数に書き出したいオブジェクトを渡せばよい。"
539 | ]
540 | },
541 | {
542 | "cell_type": "code",
543 | "execution_count": 24,
544 | "metadata": {},
545 | "outputs": [],
546 | "source": [
547 | "with open('prefecture.json', 'w') as fo:\n",
548 | " json.dump(d, fo)"
549 | ]
550 | },
551 | {
552 | "cell_type": "markdown",
553 | "metadata": {},
554 | "source": [
555 | "デフォルトでは日本語などのASCIIではない文字列がエスケープされてしまうので、書き出された内容が読みづらくなることがある。"
556 | ]
557 | },
558 | {
559 | "cell_type": "code",
560 | "execution_count": 25,
561 | "metadata": {},
562 | "outputs": [
563 | {
564 | "name": "stdout",
565 | "output_type": "stream",
566 | "text": [
567 | "{\"\\u6771\\u4eac\": [\"\\u3068\\u3046\\u304d\\u3087\\u3046\", \"Tokyo\"], \"\\u795e\\u5948\\u5ddd\": [\"\\u304b\\u306a\\u304c\\u308f\", \"Kanagawa\"], \"\\u5343\\u8449\": [\"\\u3061\\u3070\", \"Chiba\"], \"\\u57fc\\u7389\": [\"\\u3055\\u3044\\u305f\\u307e\", \"Saitama\"]}"
568 | ]
569 | }
570 | ],
571 | "source": [
572 | "!cat prefecture.json"
573 | ]
574 | },
575 | {
576 | "cell_type": "markdown",
577 | "metadata": {},
578 | "source": [
579 | "そのようなときは、json.dump関数の引数に`ensure_ascii=False`を渡せばよい。"
580 | ]
581 | },
582 | {
583 | "cell_type": "code",
584 | "execution_count": 26,
585 | "metadata": {},
586 | "outputs": [],
587 | "source": [
588 | "with open('prefecture.json', 'w') as fo:\n",
589 | " json.dump(d, fo, ensure_ascii=False)"
590 | ]
591 | },
592 | {
593 | "cell_type": "markdown",
594 | "metadata": {},
595 | "source": [
596 | "書き出されたJSONの表記は、ほぼPythonのオブジェクトの表記と同じである。"
597 | ]
598 | },
599 | {
600 | "cell_type": "code",
601 | "execution_count": 27,
602 | "metadata": {},
603 | "outputs": [
604 | {
605 | "name": "stdout",
606 | "output_type": "stream",
607 | "text": [
608 | "{\"東京\": [\"とうきょう\", \"Tokyo\"], \"神奈川\": [\"かながわ\", \"Kanagawa\"], \"千葉\": [\"ちば\", \"Chiba\"], \"埼玉\": [\"さいたま\", \"Saitama\"]}"
609 | ]
610 | }
611 | ],
612 | "source": [
613 | "!cat prefecture.json"
614 | ]
615 | },
616 | {
617 | "cell_type": "markdown",
618 | "metadata": {},
619 | "source": [
620 | "さらに、`indent`引数にインデントの文字数を設定すると、書き出されたJSON表記が読みやすくなる。"
621 | ]
622 | },
623 | {
624 | "cell_type": "code",
625 | "execution_count": 28,
626 | "metadata": {},
627 | "outputs": [],
628 | "source": [
629 | "with open('prefecture.json', 'w') as fo:\n",
630 | " json.dump(d, fo, ensure_ascii=False, indent=2)"
631 | ]
632 | },
633 | {
634 | "cell_type": "code",
635 | "execution_count": 29,
636 | "metadata": {},
637 | "outputs": [
638 | {
639 | "name": "stdout",
640 | "output_type": "stream",
641 | "text": [
642 | "{\n",
643 | " \"東京\": [\n",
644 | " \"とうきょう\",\n",
645 | " \"Tokyo\"\n",
646 | " ],\n",
647 | " \"神奈川\": [\n",
648 | " \"かながわ\",\n",
649 | " \"Kanagawa\"\n",
650 | " ],\n",
651 | " \"千葉\": [\n",
652 | " \"ちば\",\n",
653 | " \"Chiba\"\n",
654 | " ],\n",
655 | " \"埼玉\": [\n",
656 | " \"さいたま\",\n",
657 | " \"Saitama\"\n",
658 | " ]\n",
659 | "}"
660 | ]
661 | }
662 | ],
663 | "source": [
664 | "!cat prefecture.json"
665 | ]
666 | },
667 | {
668 | "cell_type": "markdown",
669 | "metadata": {},
670 | "source": [
671 | "JSONファイルを読み出すには、[json.load](https://docs.python.org/ja/3/library/json.html#json.load)関数を呼び出せばよい(これまでにJSON形式で書き出した全ファイルは、JSONとして解釈すれば同じ内容のオブジェクトとして読み出される)。"
672 | ]
673 | },
674 | {
675 | "cell_type": "code",
676 | "execution_count": 30,
677 | "metadata": {},
678 | "outputs": [
679 | {
680 | "data": {
681 | "text/plain": [
682 | "{'東京': ['とうきょう', 'Tokyo'],\n",
683 | " '神奈川': ['かながわ', 'Kanagawa'],\n",
684 | " '千葉': ['ちば', 'Chiba'],\n",
685 | " '埼玉': ['さいたま', 'Saitama']}"
686 | ]
687 | },
688 | "execution_count": 30,
689 | "metadata": {},
690 | "output_type": "execute_result"
691 | }
692 | ],
693 | "source": [
694 | "with open('prefecture.json') as fi:\n",
695 | " r = json.load(fi)\n",
696 | "r"
697 | ]
698 | },
699 | {
700 | "cell_type": "markdown",
701 | "metadata": {},
702 | "source": [
703 | "## 文字コードを指定したファイルオブジェクト"
704 | ]
705 | },
706 | {
707 | "cell_type": "markdown",
708 | "metadata": {},
709 | "source": [
710 | "東京都の[くらしと統計2019 運輸・観光](https://www.toukei.metro.tokyo.lg.jp/kurasi/2019/ku19-18.htm)のウェブサイトから[主な駅の乗車人員数(平成28年度)のCSVファイル](https://www.toukei.metro.tokyo.lg.jp/kurasi/2019/csv/ku19rv1810.csv)をダウンロードする。ダウンロードには[wget](https://www.gnu.org/software/wget/)というコマンドを利用している。"
711 | ]
712 | },
713 | {
714 | "cell_type": "code",
715 | "execution_count": 31,
716 | "metadata": {},
717 | "outputs": [
718 | {
719 | "name": "stdout",
720 | "output_type": "stream",
721 | "text": [
722 | "--2024-11-24 14:22:31-- https://www.toukei.metro.tokyo.lg.jp/kurasi/2019/csv/ku19rv1810.csv\n",
723 | "Resolving www.toukei.metro.tokyo.lg.jp (www.toukei.metro.tokyo.lg.jp)... 3.164.143.93, 3.164.143.8, 3.164.143.45, ...\n",
724 | "Connecting to www.toukei.metro.tokyo.lg.jp (www.toukei.metro.tokyo.lg.jp)|3.164.143.93|:443... connected.\n",
725 | "HTTP request sent, awaiting response... 404 Not Found\n",
726 | "2024-11-24 14:22:31 ERROR 404: Not Found.\n",
727 | "\n"
728 | ]
729 | }
730 | ],
731 | "source": [
732 | "!wget -O station.csv https://www.toukei.metro.tokyo.lg.jp/kurasi/2019/csv/ku19rv1810.csv"
733 | ]
734 | },
735 | {
736 | "cell_type": "markdown",
737 | "metadata": {},
738 | "source": [
739 | "catコマンドを使ってダウンロードしたファイルの内容を確認する(文字化けすることはよくある)。"
740 | ]
741 | },
742 | {
743 | "cell_type": "code",
744 | "execution_count": 32,
745 | "metadata": {},
746 | "outputs": [],
747 | "source": [
748 | "!cat station.csv"
749 | ]
750 | },
751 | {
752 | "cell_type": "markdown",
753 | "metadata": {},
754 | "source": [
755 | "ファイルの文字コードはおそらくShift_JIS (cp932) だろうと推測し、iconvで文字コードを変換してみる。"
756 | ]
757 | },
758 | {
759 | "cell_type": "code",
760 | "execution_count": 33,
761 | "metadata": {},
762 | "outputs": [],
763 | "source": [
764 | "!cat station.csv | iconv -f cp932"
765 | ]
766 | },
767 | {
768 | "cell_type": "markdown",
769 | "metadata": {},
770 | "source": [
771 | "open関数では、ファイルの読み書き時に使用する文字コードを`encoding`パラメータで指定できる。"
772 | ]
773 | },
774 | {
775 | "cell_type": "code",
776 | "execution_count": 34,
777 | "metadata": {},
778 | "outputs": [],
779 | "source": [
780 | "with open('station.csv', encoding='cp932') as fi:\n",
781 | " for line in fi:\n",
782 | " print(line.strip('\\n'))"
783 | ]
784 | },
785 | {
786 | "cell_type": "markdown",
787 | "metadata": {
788 | "tags": [
789 | "remove-cell"
790 | ]
791 | },
792 | "source": [
793 | "---\n",
794 | "\n",
795 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
796 | ]
797 | }
798 | ],
799 | "metadata": {
800 | "@context": {
801 | "CreativeWork": "http://schema.org/CreativeWork",
802 | "Organization": "http://schema.org/Organization",
803 | "Person": "http://schema.org/Person",
804 | "author": "http://schema.org/author",
805 | "copyrightHolder": "http://schema.org/copyrightHolder",
806 | "copyrightYear": "http://schema.org/copyrightYear",
807 | "license": "http://schema.org/license",
808 | "name": "http://schema.org/name",
809 | "title": "http://schema.org/name",
810 | "url": "http://schema.org/url"
811 | },
812 | "@type": "CreativeWork",
813 | "author": [
814 | {
815 | "@type": "Person",
816 | "name": "Naoaki Okazaki",
817 | "url": "https://www.chokkan.org/"
818 | }
819 | ],
820 | "copyrightHolder": [
821 | {
822 | "@type": "Person",
823 | "name": "Naoaki Okazaki",
824 | "url": "https://www.chokkan.org/"
825 | }
826 | ],
827 | "copyrightYear": 2024,
828 | "kernelspec": {
829 | "display_name": "Python 3 (ipykernel)",
830 | "language": "python",
831 | "name": "python3"
832 | },
833 | "language_info": {
834 | "codemirror_mode": {
835 | "name": "ipython",
836 | "version": 3
837 | },
838 | "file_extension": ".py",
839 | "mimetype": "text/x-python",
840 | "name": "python",
841 | "nbconvert_exporter": "python",
842 | "pygments_lexer": "ipython3",
843 | "version": "3.10.12"
844 | },
845 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
846 | "title": "Python早見帳"
847 | },
848 | "nbformat": 4,
849 | "nbformat_minor": 4
850 | }
851 |
--------------------------------------------------------------------------------
/12immutable.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "(ch:immutable)=\n",
8 | "# 可変と不変"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "Pythonのオブジェクトには不変な(immutable)ものと、可変な(mutable)なものがある。\n",
16 | "\n",
17 | "+ 不変: 整数、浮動小数点数、文字列、タプルなど\n",
18 | "+ 可変: リスト、辞書、集合など"
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "metadata": {},
24 | "source": [
25 | "## 不変なオブジェクト"
26 | ]
27 | },
28 | {
29 | "cell_type": "markdown",
30 | "metadata": {},
31 | "source": [
32 | "整数値が不変とはどういうことか? 実際に変数`x`に整数値`1`を代入して、変数`x`が参照しているオブジェクトの識別値を`id`関数で調べてみる。なお、オブジェクトの識別値は、(Pythonインタプリタの実装にもよるが)オブジェクトが格納されているメモリ空間上のアドレスに相当する。"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": 1,
38 | "metadata": {},
39 | "outputs": [],
40 | "source": [
41 | "x = 1"
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": 2,
47 | "metadata": {},
48 | "outputs": [
49 | {
50 | "data": {
51 | "text/plain": [
52 | "140283206549744"
53 | ]
54 | },
55 | "execution_count": 2,
56 | "metadata": {},
57 | "output_type": "execute_result"
58 | }
59 | ],
60 | "source": [
61 | "id(x)"
62 | ]
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {},
67 | "source": [
68 | "続いて、変数`x`に1を加算すると、変数`x`の識別値も変化する。"
69 | ]
70 | },
71 | {
72 | "cell_type": "code",
73 | "execution_count": 3,
74 | "metadata": {},
75 | "outputs": [
76 | {
77 | "data": {
78 | "text/plain": [
79 | "2"
80 | ]
81 | },
82 | "execution_count": 3,
83 | "metadata": {},
84 | "output_type": "execute_result"
85 | }
86 | ],
87 | "source": [
88 | "x += 1\n",
89 | "x"
90 | ]
91 | },
92 | {
93 | "cell_type": "code",
94 | "execution_count": 4,
95 | "metadata": {},
96 | "outputs": [
97 | {
98 | "data": {
99 | "text/plain": [
100 | "140283206549776"
101 | ]
102 | },
103 | "execution_count": 4,
104 | "metadata": {},
105 | "output_type": "execute_result"
106 | }
107 | ],
108 | "source": [
109 | "id(x)"
110 | ]
111 | },
112 | {
113 | "cell_type": "markdown",
114 | "metadata": {},
115 | "source": [
116 | "2つのオブジェクトに異なる識別値が割り当てられた場合、それらのオブジェクトの実体(メモリ空間上で格納されている場所)は異なることを意味する。先ほどのコードでは、変数`x`が参照しているオブジェクトの値(`1`)が変更されたのではなく、変数`x`の参照先が整数`2`を表すオブジェクトに変更されたことを表している。このように、不変なオブジェクトを参照している変数の値を変更する時は、オブジェクトの内容を変更するのではなく、その変数の参照先が更新後の値を表すオブジェクトに変更される。"
117 | ]
118 | },
119 | {
120 | "cell_type": "markdown",
121 | "metadata": {},
122 | "source": [
123 | "以上の動作は、単なる代入でも同様である。代入文の実行後に変数`x`の識別値が変化する。"
124 | ]
125 | },
126 | {
127 | "cell_type": "code",
128 | "execution_count": 5,
129 | "metadata": {},
130 | "outputs": [
131 | {
132 | "data": {
133 | "text/plain": [
134 | "140283206549712"
135 | ]
136 | },
137 | "execution_count": 5,
138 | "metadata": {},
139 | "output_type": "execute_result"
140 | }
141 | ],
142 | "source": [
143 | "x = 0\n",
144 | "id(x)"
145 | ]
146 | },
147 | {
148 | "cell_type": "markdown",
149 | "metadata": {},
150 | "source": [
151 | "代入文の本質的な動作は「左辺の変数の参照先を右辺のオブジェクトに変更する」ことである。例えば、以下の代入文では変数`y`と変数`x`は同一のオブジェクトを参照することになる。ゆえに、変数`x`と`y`の識別値は一致し、変数`x`と`y`の評価結果は同じになる。"
152 | ]
153 | },
154 | {
155 | "cell_type": "code",
156 | "execution_count": 6,
157 | "metadata": {},
158 | "outputs": [],
159 | "source": [
160 | "y = x"
161 | ]
162 | },
163 | {
164 | "cell_type": "code",
165 | "execution_count": 7,
166 | "metadata": {},
167 | "outputs": [
168 | {
169 | "data": {
170 | "text/plain": [
171 | "0"
172 | ]
173 | },
174 | "execution_count": 7,
175 | "metadata": {},
176 | "output_type": "execute_result"
177 | }
178 | ],
179 | "source": [
180 | "x"
181 | ]
182 | },
183 | {
184 | "cell_type": "code",
185 | "execution_count": 8,
186 | "metadata": {},
187 | "outputs": [
188 | {
189 | "data": {
190 | "text/plain": [
191 | "140283206549712"
192 | ]
193 | },
194 | "execution_count": 8,
195 | "metadata": {},
196 | "output_type": "execute_result"
197 | }
198 | ],
199 | "source": [
200 | "id(x)"
201 | ]
202 | },
203 | {
204 | "cell_type": "code",
205 | "execution_count": 9,
206 | "metadata": {},
207 | "outputs": [
208 | {
209 | "data": {
210 | "text/plain": [
211 | "0"
212 | ]
213 | },
214 | "execution_count": 9,
215 | "metadata": {},
216 | "output_type": "execute_result"
217 | }
218 | ],
219 | "source": [
220 | "y"
221 | ]
222 | },
223 | {
224 | "cell_type": "code",
225 | "execution_count": 10,
226 | "metadata": {},
227 | "outputs": [
228 | {
229 | "data": {
230 | "text/plain": [
231 | "140283206549712"
232 | ]
233 | },
234 | "execution_count": 10,
235 | "metadata": {},
236 | "output_type": "execute_result"
237 | }
238 | ],
239 | "source": [
240 | "id(y)"
241 | ]
242 | },
243 | {
244 | "cell_type": "markdown",
245 | "metadata": {},
246 | "source": [
247 | "`x`と`y`の値は等しい。"
248 | ]
249 | },
250 | {
251 | "cell_type": "code",
252 | "execution_count": 11,
253 | "metadata": {},
254 | "outputs": [
255 | {
256 | "data": {
257 | "text/plain": [
258 | "True"
259 | ]
260 | },
261 | "execution_count": 11,
262 | "metadata": {},
263 | "output_type": "execute_result"
264 | }
265 | ],
266 | "source": [
267 | "x == y"
268 | ]
269 | },
270 | {
271 | "cell_type": "markdown",
272 | "metadata": {},
273 | "source": [
274 | "`is`演算子は2つのオブジェクトの識別値が等しいかどうかを評価する。以下の結果からも、`x`と`y`は同一のオブジェクトを参照していることが分かる。"
275 | ]
276 | },
277 | {
278 | "cell_type": "code",
279 | "execution_count": 12,
280 | "metadata": {},
281 | "outputs": [
282 | {
283 | "data": {
284 | "text/plain": [
285 | "True"
286 | ]
287 | },
288 | "execution_count": 12,
289 | "metadata": {},
290 | "output_type": "execute_result"
291 | }
292 | ],
293 | "source": [
294 | "x is y"
295 | ]
296 | },
297 | {
298 | "cell_type": "markdown",
299 | "metadata": {},
300 | "source": [
301 | "ここで、変数`y`に値をインクリメントすると、変数`x`と`y`の参照先が同じなので、変数`x`の値も変更されてしまうのではないかと思うかもしれない。ところが、`y`が参照しているオブジェクト(=`x`が参照しているオブジェクト)が不変であるため、変数`y`が参照しているオブジェクトの値を変更するのではなく、変数`y`の参照先がインクリメント後の計算結果を格納するオブジェクトに変更される。"
302 | ]
303 | },
304 | {
305 | "cell_type": "code",
306 | "execution_count": 13,
307 | "metadata": {},
308 | "outputs": [],
309 | "source": [
310 | "y += 1"
311 | ]
312 | },
313 | {
314 | "cell_type": "markdown",
315 | "metadata": {},
316 | "source": [
317 | "したがって、`y += 1`を実行したことにより、変数`x`と`y`は異なるオブジェクトを参照するようになる。これにより、変数`x`の値は変更されず、変数`y`の値が変更される、という(我々が通常期待する通りの)動作になる。"
318 | ]
319 | },
320 | {
321 | "cell_type": "code",
322 | "execution_count": 14,
323 | "metadata": {},
324 | "outputs": [
325 | {
326 | "data": {
327 | "text/plain": [
328 | "0"
329 | ]
330 | },
331 | "execution_count": 14,
332 | "metadata": {},
333 | "output_type": "execute_result"
334 | }
335 | ],
336 | "source": [
337 | "x"
338 | ]
339 | },
340 | {
341 | "cell_type": "code",
342 | "execution_count": 15,
343 | "metadata": {},
344 | "outputs": [
345 | {
346 | "data": {
347 | "text/plain": [
348 | "140283206549712"
349 | ]
350 | },
351 | "execution_count": 15,
352 | "metadata": {},
353 | "output_type": "execute_result"
354 | }
355 | ],
356 | "source": [
357 | "id(x)"
358 | ]
359 | },
360 | {
361 | "cell_type": "code",
362 | "execution_count": 16,
363 | "metadata": {},
364 | "outputs": [
365 | {
366 | "data": {
367 | "text/plain": [
368 | "1"
369 | ]
370 | },
371 | "execution_count": 16,
372 | "metadata": {},
373 | "output_type": "execute_result"
374 | }
375 | ],
376 | "source": [
377 | "y"
378 | ]
379 | },
380 | {
381 | "cell_type": "code",
382 | "execution_count": 17,
383 | "metadata": {},
384 | "outputs": [
385 | {
386 | "data": {
387 | "text/plain": [
388 | "140283206549744"
389 | ]
390 | },
391 | "execution_count": 17,
392 | "metadata": {},
393 | "output_type": "execute_result"
394 | }
395 | ],
396 | "source": [
397 | "id(y)"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": 18,
403 | "metadata": {},
404 | "outputs": [
405 | {
406 | "data": {
407 | "text/plain": [
408 | "False"
409 | ]
410 | },
411 | "execution_count": 18,
412 | "metadata": {},
413 | "output_type": "execute_result"
414 | }
415 | ],
416 | "source": [
417 | "x == y"
418 | ]
419 | },
420 | {
421 | "cell_type": "markdown",
422 | "metadata": {},
423 | "source": [
424 | "`x`と`y`の識別値は異なるので、以下の評価結果も偽となる。"
425 | ]
426 | },
427 | {
428 | "cell_type": "code",
429 | "execution_count": 19,
430 | "metadata": {},
431 | "outputs": [
432 | {
433 | "data": {
434 | "text/plain": [
435 | "False"
436 | ]
437 | },
438 | "execution_count": 19,
439 | "metadata": {},
440 | "output_type": "execute_result"
441 | }
442 | ],
443 | "source": [
444 | "x is y"
445 | ]
446 | },
447 | {
448 | "cell_type": "markdown",
449 | "metadata": {},
450 | "source": [
451 | "## 可変なオブジェクト"
452 | ]
453 | },
454 | {
455 | "cell_type": "markdown",
456 | "metadata": {},
457 | "source": [
458 | "オブジェクトが可変のときはどのようになるのか? 実際に変数`x`にリストを代入して、変数`x`の識別値を調べてみる。"
459 | ]
460 | },
461 | {
462 | "cell_type": "code",
463 | "execution_count": 20,
464 | "metadata": {},
465 | "outputs": [
466 | {
467 | "data": {
468 | "text/plain": [
469 | "[1]"
470 | ]
471 | },
472 | "execution_count": 20,
473 | "metadata": {},
474 | "output_type": "execute_result"
475 | }
476 | ],
477 | "source": [
478 | "x = [1]\n",
479 | "x"
480 | ]
481 | },
482 | {
483 | "cell_type": "code",
484 | "execution_count": 21,
485 | "metadata": {},
486 | "outputs": [
487 | {
488 | "data": {
489 | "text/plain": [
490 | "140283101596992"
491 | ]
492 | },
493 | "execution_count": 21,
494 | "metadata": {},
495 | "output_type": "execute_result"
496 | }
497 | ],
498 | "source": [
499 | "id(x)"
500 | ]
501 | },
502 | {
503 | "cell_type": "markdown",
504 | "metadata": {},
505 | "source": [
506 | "続いて、変数`x`に要素を追加してみる。先ほどの不変のオブジェクトに対する操作とは異なり、変数`x`の識別値は変化しない。"
507 | ]
508 | },
509 | {
510 | "cell_type": "code",
511 | "execution_count": 22,
512 | "metadata": {},
513 | "outputs": [
514 | {
515 | "data": {
516 | "text/plain": [
517 | "[1, 1]"
518 | ]
519 | },
520 | "execution_count": 22,
521 | "metadata": {},
522 | "output_type": "execute_result"
523 | }
524 | ],
525 | "source": [
526 | "x += [1]\n",
527 | "x"
528 | ]
529 | },
530 | {
531 | "cell_type": "code",
532 | "execution_count": 23,
533 | "metadata": {},
534 | "outputs": [
535 | {
536 | "data": {
537 | "text/plain": [
538 | "140283101596992"
539 | ]
540 | },
541 | "execution_count": 23,
542 | "metadata": {},
543 | "output_type": "execute_result"
544 | }
545 | ],
546 | "source": [
547 | "id(x)"
548 | ]
549 | },
550 | {
551 | "cell_type": "markdown",
552 | "metadata": {},
553 | "source": [
554 | "これは、変数`x`が参照しているオブジェクトの内容が直接変更されたことを意味している。このように、可変なオブジェクトを参照している変数の値を変更する操作を行うと、その変数の参照先は変更されず、オブジェクトの中身が変更される。"
555 | ]
556 | },
557 | {
558 | "cell_type": "markdown",
559 | "metadata": {},
560 | "source": [
561 | "先ほども説明したとおり、代入文の本質的な動作は「左辺の変数の参照先を右辺のオブジェクトに変更すること」である。例えば、以下の代入文では変数`y`と変数`x`は同一のオブジェクトを参照することになる。ゆえに、変数`x`と`y`の識別値は一致し、変数`x`と`y`の評価結果は同じになる。"
562 | ]
563 | },
564 | {
565 | "cell_type": "code",
566 | "execution_count": 24,
567 | "metadata": {},
568 | "outputs": [],
569 | "source": [
570 | "y = x"
571 | ]
572 | },
573 | {
574 | "cell_type": "code",
575 | "execution_count": 25,
576 | "metadata": {},
577 | "outputs": [
578 | {
579 | "data": {
580 | "text/plain": [
581 | "[1, 1]"
582 | ]
583 | },
584 | "execution_count": 25,
585 | "metadata": {},
586 | "output_type": "execute_result"
587 | }
588 | ],
589 | "source": [
590 | "x"
591 | ]
592 | },
593 | {
594 | "cell_type": "code",
595 | "execution_count": 26,
596 | "metadata": {},
597 | "outputs": [
598 | {
599 | "data": {
600 | "text/plain": [
601 | "[1, 1]"
602 | ]
603 | },
604 | "execution_count": 26,
605 | "metadata": {},
606 | "output_type": "execute_result"
607 | }
608 | ],
609 | "source": [
610 | "y"
611 | ]
612 | },
613 | {
614 | "cell_type": "code",
615 | "execution_count": 27,
616 | "metadata": {},
617 | "outputs": [
618 | {
619 | "data": {
620 | "text/plain": [
621 | "True"
622 | ]
623 | },
624 | "execution_count": 27,
625 | "metadata": {},
626 | "output_type": "execute_result"
627 | }
628 | ],
629 | "source": [
630 | "x == y"
631 | ]
632 | },
633 | {
634 | "cell_type": "code",
635 | "execution_count": 28,
636 | "metadata": {},
637 | "outputs": [
638 | {
639 | "data": {
640 | "text/plain": [
641 | "True"
642 | ]
643 | },
644 | "execution_count": 28,
645 | "metadata": {},
646 | "output_type": "execute_result"
647 | }
648 | ],
649 | "source": [
650 | "x is y"
651 | ]
652 | },
653 | {
654 | "cell_type": "markdown",
655 | "metadata": {},
656 | "source": [
657 | "ここで、変数`y`に要素を追加すると、変数`x`と`y`の参照先が同じなので、変数`x`の値も変更されたように見える。実際には、変数`x`と`y`は全く同一のオブジェクトを指しており、そのオブジェクトの内容を更新したので、当然の結果と言える。同じオブジェクトの内容を変数`x`や`y`を通して評価しているだけである。"
658 | ]
659 | },
660 | {
661 | "cell_type": "code",
662 | "execution_count": 29,
663 | "metadata": {},
664 | "outputs": [],
665 | "source": [
666 | "y += [1]"
667 | ]
668 | },
669 | {
670 | "cell_type": "code",
671 | "execution_count": 30,
672 | "metadata": {},
673 | "outputs": [
674 | {
675 | "data": {
676 | "text/plain": [
677 | "[1, 1, 1]"
678 | ]
679 | },
680 | "execution_count": 30,
681 | "metadata": {},
682 | "output_type": "execute_result"
683 | }
684 | ],
685 | "source": [
686 | "x"
687 | ]
688 | },
689 | {
690 | "cell_type": "code",
691 | "execution_count": 31,
692 | "metadata": {},
693 | "outputs": [
694 | {
695 | "data": {
696 | "text/plain": [
697 | "140283101596992"
698 | ]
699 | },
700 | "execution_count": 31,
701 | "metadata": {},
702 | "output_type": "execute_result"
703 | }
704 | ],
705 | "source": [
706 | "id(x)"
707 | ]
708 | },
709 | {
710 | "cell_type": "code",
711 | "execution_count": 32,
712 | "metadata": {},
713 | "outputs": [
714 | {
715 | "data": {
716 | "text/plain": [
717 | "[1, 1, 1]"
718 | ]
719 | },
720 | "execution_count": 32,
721 | "metadata": {},
722 | "output_type": "execute_result"
723 | }
724 | ],
725 | "source": [
726 | "y"
727 | ]
728 | },
729 | {
730 | "cell_type": "code",
731 | "execution_count": 33,
732 | "metadata": {},
733 | "outputs": [
734 | {
735 | "data": {
736 | "text/plain": [
737 | "140283101596992"
738 | ]
739 | },
740 | "execution_count": 33,
741 | "metadata": {},
742 | "output_type": "execute_result"
743 | }
744 | ],
745 | "source": [
746 | "id(y)"
747 | ]
748 | },
749 | {
750 | "cell_type": "code",
751 | "execution_count": 34,
752 | "metadata": {},
753 | "outputs": [
754 | {
755 | "data": {
756 | "text/plain": [
757 | "True"
758 | ]
759 | },
760 | "execution_count": 34,
761 | "metadata": {},
762 | "output_type": "execute_result"
763 | }
764 | ],
765 | "source": [
766 | "x == y"
767 | ]
768 | },
769 | {
770 | "cell_type": "code",
771 | "execution_count": 35,
772 | "metadata": {},
773 | "outputs": [
774 | {
775 | "data": {
776 | "text/plain": [
777 | "True"
778 | ]
779 | },
780 | "execution_count": 35,
781 | "metadata": {},
782 | "output_type": "execute_result"
783 | }
784 | ],
785 | "source": [
786 | "x is y"
787 | ]
788 | },
789 | {
790 | "cell_type": "markdown",
791 | "metadata": {},
792 | "source": [
793 | "変数`x`が参照しているリストのコピーを作成し、変数`z`に代入する。`x`と`z`の内容は等しいが、`x`と`z`の識別値は異なる。"
794 | ]
795 | },
796 | {
797 | "cell_type": "code",
798 | "execution_count": 36,
799 | "metadata": {},
800 | "outputs": [],
801 | "source": [
802 | "z = x[:]"
803 | ]
804 | },
805 | {
806 | "cell_type": "code",
807 | "execution_count": 37,
808 | "metadata": {},
809 | "outputs": [
810 | {
811 | "data": {
812 | "text/plain": [
813 | "[1, 1, 1]"
814 | ]
815 | },
816 | "execution_count": 37,
817 | "metadata": {},
818 | "output_type": "execute_result"
819 | }
820 | ],
821 | "source": [
822 | "x"
823 | ]
824 | },
825 | {
826 | "cell_type": "code",
827 | "execution_count": 38,
828 | "metadata": {},
829 | "outputs": [
830 | {
831 | "data": {
832 | "text/plain": [
833 | "140283101596992"
834 | ]
835 | },
836 | "execution_count": 38,
837 | "metadata": {},
838 | "output_type": "execute_result"
839 | }
840 | ],
841 | "source": [
842 | "id(x)"
843 | ]
844 | },
845 | {
846 | "cell_type": "code",
847 | "execution_count": 39,
848 | "metadata": {},
849 | "outputs": [
850 | {
851 | "data": {
852 | "text/plain": [
853 | "[1, 1, 1]"
854 | ]
855 | },
856 | "execution_count": 39,
857 | "metadata": {},
858 | "output_type": "execute_result"
859 | }
860 | ],
861 | "source": [
862 | "z"
863 | ]
864 | },
865 | {
866 | "cell_type": "code",
867 | "execution_count": 40,
868 | "metadata": {},
869 | "outputs": [
870 | {
871 | "data": {
872 | "text/plain": [
873 | "140283101495936"
874 | ]
875 | },
876 | "execution_count": 40,
877 | "metadata": {},
878 | "output_type": "execute_result"
879 | }
880 | ],
881 | "source": [
882 | "id(z)"
883 | ]
884 | },
885 | {
886 | "cell_type": "markdown",
887 | "metadata": {},
888 | "source": [
889 | "`x`と`z`の内容(要素)は等しいが、`x`と`z`は同一のオブジェクトを指しているわけではない。"
890 | ]
891 | },
892 | {
893 | "cell_type": "code",
894 | "execution_count": 41,
895 | "metadata": {},
896 | "outputs": [
897 | {
898 | "data": {
899 | "text/plain": [
900 | "True"
901 | ]
902 | },
903 | "execution_count": 41,
904 | "metadata": {},
905 | "output_type": "execute_result"
906 | }
907 | ],
908 | "source": [
909 | "x == z"
910 | ]
911 | },
912 | {
913 | "cell_type": "code",
914 | "execution_count": 42,
915 | "metadata": {},
916 | "outputs": [
917 | {
918 | "data": {
919 | "text/plain": [
920 | "False"
921 | ]
922 | },
923 | "execution_count": 42,
924 | "metadata": {},
925 | "output_type": "execute_result"
926 | }
927 | ],
928 | "source": [
929 | "x is z"
930 | ]
931 | },
932 | {
933 | "cell_type": "markdown",
934 | "metadata": {},
935 | "source": [
936 | "## 関数への参照渡しと不変・可変"
937 | ]
938 | },
939 | {
940 | "cell_type": "markdown",
941 | "metadata": {},
942 | "source": [
943 | "Pythonでは、関数の引数は**すべて参照渡し**となる。関数にオブジェクトの参照を渡すと、原理上はその関数内でオブジェクトへの内容を変更できる。"
944 | ]
945 | },
946 | {
947 | "cell_type": "markdown",
948 | "metadata": {},
949 | "source": [
950 | "ところが、数値や文字列などの不変なオブジェクトを関数の引数として変数で渡した場合、関数内で引数として渡された変数を変更しても、呼び出し元には影響が波及しない。"
951 | ]
952 | },
953 | {
954 | "cell_type": "code",
955 | "execution_count": 43,
956 | "metadata": {},
957 | "outputs": [],
958 | "source": [
959 | "def add(x):\n",
960 | " x += 1"
961 | ]
962 | },
963 | {
964 | "cell_type": "code",
965 | "execution_count": 44,
966 | "metadata": {},
967 | "outputs": [
968 | {
969 | "data": {
970 | "text/plain": [
971 | "1"
972 | ]
973 | },
974 | "execution_count": 44,
975 | "metadata": {},
976 | "output_type": "execute_result"
977 | }
978 | ],
979 | "source": [
980 | "x = 1\n",
981 | "add(x)\n",
982 | "x"
983 | ]
984 | },
985 | {
986 | "cell_type": "markdown",
987 | "metadata": {},
988 | "source": [
989 | "比較のため、以上のコードをC言語風に書くと、次のようになる。これを読む限りは、呼び出し元の変数`x`の値が変更されそうに思える。\n",
990 | "\n",
991 | "```c\n",
992 | "void add(int *x)\n",
993 | "{\n",
994 | " (*x) += 1;\n",
995 | "}\n",
996 | "\n",
997 | "int main()\n",
998 | "{\n",
999 | " int x = 1;\n",
1000 | " add(&x);\n",
1001 | " printf(\"%d\\n\", x);\n",
1002 | " return 0;\n",
1003 | "}\n",
1004 | "```"
1005 | ]
1006 | },
1007 | {
1008 | "cell_type": "markdown",
1009 | "metadata": {},
1010 | "source": [
1011 | "しかしながら、変数`x`のオブジェクトは不変であるため、`add`関数内で`x`の値を更新する際に、変数`x`の識別子が変化する。これは、先ほど説明した不変なオブジェクトへの値の変更の動作と一貫している。この動作のため、関数に不変なオブジェクトを参照渡ししても、関数内でそのオブジェクトの値が変更されることなく、値の変更の影響が関数内に留まる。"
1012 | ]
1013 | },
1014 | {
1015 | "cell_type": "code",
1016 | "execution_count": 45,
1017 | "metadata": {},
1018 | "outputs": [
1019 | {
1020 | "name": "stdout",
1021 | "output_type": "stream",
1022 | "text": [
1023 | "更新前の識別値 140283206549744\n",
1024 | "更新後の識別値 140283206549776\n",
1025 | "呼び出し元の識別値 140283206549744\n"
1026 | ]
1027 | },
1028 | {
1029 | "data": {
1030 | "text/plain": [
1031 | "1"
1032 | ]
1033 | },
1034 | "execution_count": 45,
1035 | "metadata": {},
1036 | "output_type": "execute_result"
1037 | }
1038 | ],
1039 | "source": [
1040 | "def add(x):\n",
1041 | " print('更新前の識別値', id(x))\n",
1042 | " x += 1\n",
1043 | " print('更新後の識別値', id(x))\n",
1044 | " \n",
1045 | "a = 1\n",
1046 | "add(a)\n",
1047 | "print('呼び出し元の識別値', id(a))\n",
1048 | "a"
1049 | ]
1050 | },
1051 | {
1052 | "cell_type": "markdown",
1053 | "metadata": {},
1054 | "source": [
1055 | "これに対し、リストを参照渡しで関数に与えると、その関数内でそのリストの内容を変更できるし、その変更結果は関数の呼び出し元にも波及する。"
1056 | ]
1057 | },
1058 | {
1059 | "cell_type": "code",
1060 | "execution_count": 46,
1061 | "metadata": {},
1062 | "outputs": [],
1063 | "source": [
1064 | "def add(x):\n",
1065 | " x += [1]"
1066 | ]
1067 | },
1068 | {
1069 | "cell_type": "code",
1070 | "execution_count": 47,
1071 | "metadata": {},
1072 | "outputs": [
1073 | {
1074 | "data": {
1075 | "text/plain": [
1076 | "[1, 1]"
1077 | ]
1078 | },
1079 | "execution_count": 47,
1080 | "metadata": {},
1081 | "output_type": "execute_result"
1082 | }
1083 | ],
1084 | "source": [
1085 | "x = [1]\n",
1086 | "add(x)\n",
1087 | "x"
1088 | ]
1089 | },
1090 | {
1091 | "cell_type": "markdown",
1092 | "metadata": {},
1093 | "source": [
1094 | "これは、変数`x`のオブジェクト(リスト)は可変であるため、`add`関数内で`x`に要素を追加する際に、変数`x`の識別子が変化しない。これも、先ほど説明した可変なオブジェクトへの変更の動作と一貫している。この動作のため、関数に可変なオブジェクトを参照渡しをした場合、関数内でそのオブジェクトの内容が変更されると、その影響が関数の呼び出し元にも波及する。"
1095 | ]
1096 | },
1097 | {
1098 | "cell_type": "code",
1099 | "execution_count": 48,
1100 | "metadata": {},
1101 | "outputs": [
1102 | {
1103 | "name": "stdout",
1104 | "output_type": "stream",
1105 | "text": [
1106 | "更新前の識別値 140283101599232\n",
1107 | "更新後の識別値 140283101599232\n",
1108 | "呼び出し元の識別値 140283101599232\n"
1109 | ]
1110 | },
1111 | {
1112 | "data": {
1113 | "text/plain": [
1114 | "[1, 1]"
1115 | ]
1116 | },
1117 | "execution_count": 48,
1118 | "metadata": {},
1119 | "output_type": "execute_result"
1120 | }
1121 | ],
1122 | "source": [
1123 | "def add(x):\n",
1124 | " print('更新前の識別値', id(x))\n",
1125 | " x += [1]\n",
1126 | " print('更新後の識別値', id(x))\n",
1127 | " \n",
1128 | "a = [1]\n",
1129 | "add(a)\n",
1130 | "print('呼び出し元の識別値', id(a))\n",
1131 | "a"
1132 | ]
1133 | },
1134 | {
1135 | "cell_type": "markdown",
1136 | "metadata": {
1137 | "tags": [
1138 | "remove-cell"
1139 | ]
1140 | },
1141 | "source": [
1142 | "---\n",
1143 | "\n",
1144 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
1145 | ]
1146 | }
1147 | ],
1148 | "metadata": {
1149 | "@context": {
1150 | "CreativeWork": "http://schema.org/CreativeWork",
1151 | "Organization": "http://schema.org/Organization",
1152 | "Person": "http://schema.org/Person",
1153 | "author": "http://schema.org/author",
1154 | "copyrightHolder": "http://schema.org/copyrightHolder",
1155 | "copyrightYear": "http://schema.org/copyrightYear",
1156 | "license": "http://schema.org/license",
1157 | "name": "http://schema.org/name",
1158 | "title": "http://schema.org/name",
1159 | "url": "http://schema.org/url"
1160 | },
1161 | "@type": "CreativeWork",
1162 | "author": [
1163 | {
1164 | "@type": "Person",
1165 | "name": "Naoaki Okazaki",
1166 | "url": "https://www.chokkan.org/"
1167 | }
1168 | ],
1169 | "copyrightHolder": [
1170 | {
1171 | "@type": "Person",
1172 | "name": "Naoaki Okazaki",
1173 | "url": "https://www.chokkan.org/"
1174 | }
1175 | ],
1176 | "copyrightYear": 2024,
1177 | "kernelspec": {
1178 | "display_name": "Python 3 (ipykernel)",
1179 | "language": "python",
1180 | "name": "python3"
1181 | },
1182 | "language_info": {
1183 | "codemirror_mode": {
1184 | "name": "ipython",
1185 | "version": 3
1186 | },
1187 | "file_extension": ".py",
1188 | "mimetype": "text/x-python",
1189 | "name": "python",
1190 | "nbconvert_exporter": "python",
1191 | "pygments_lexer": "ipython3",
1192 | "version": "3.10.12"
1193 | },
1194 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
1195 | "title": "Python早見帳"
1196 | },
1197 | "nbformat": 4,
1198 | "nbformat_minor": 4
1199 | }
1200 |
--------------------------------------------------------------------------------
/14exception.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# 例外"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "## 例外の捕捉"
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "以下のコードは数値を$0$で割るため、実行するとエラー(例外)が発生する。"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {
28 | "tags": [
29 | "raises-exception"
30 | ]
31 | },
32 | "outputs": [
33 | {
34 | "ename": "ZeroDivisionError",
35 | "evalue": "float division by zero",
36 | "output_type": "error",
37 | "traceback": [
38 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
39 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)",
40 | "\u001b[0;32m/tmp/ipykernel_205130/4032807262.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;36m2.\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
41 | "\u001b[0;31mZeroDivisionError\u001b[0m: float division by zero"
42 | ]
43 | }
44 | ],
45 | "source": [
46 | "2. / 0"
47 | ]
48 | },
49 | {
50 | "cell_type": "markdown",
51 | "metadata": {},
52 | "source": [
53 | "プログラム中でエラーが発生したときは、例外クラスのオブジェクトが作成・送出される。例えば、上の例では[ZeroDivisionError](https://docs.python.org/ja/3/library/exceptions.html#ZeroDivisionError)という例外クラスのオブジェクトが`'float division by zero'`というメッセージ付きで送出されている。\n",
54 | "\n",
55 | "プログラムの実行中に例外が発生するとPythonインタプリタの実行が直ちに停止されるが、 [try](https://docs.python.org/ja/3/reference/compound_stmts.html#the-try-statement)文およびexcept節を用いて、例外をプログラム中で捕捉することも可能である。"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 2,
61 | "metadata": {},
62 | "outputs": [
63 | {
64 | "name": "stdout",
65 | "output_type": "stream",
66 | "text": [
67 | "ゼロ除算: float division by zero\n"
68 | ]
69 | }
70 | ],
71 | "source": [
72 | "try:\n",
73 | " 2. / 0\n",
74 | "except ZeroDivisionError as e:\n",
75 | " print('ゼロ除算:', e)"
76 | ]
77 | },
78 | {
79 | "cell_type": "markdown",
80 | "metadata": {},
81 | "source": [
82 | "try文を用いても、except節で指定した例外クラス以外の例外が発生した場合は、except節は実行されずPythonインタプリタの実行が止まってしまう。以下のプログラムで発生する例外は[OverflowError](https://docs.python.org/ja/3/library/exceptions.html#OverflowError)であるため、ZeroDivisionErrorに関するexcept節では捕捉しきれない。"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": 3,
88 | "metadata": {
89 | "tags": [
90 | "raises-exception"
91 | ]
92 | },
93 | "outputs": [
94 | {
95 | "ename": "OverflowError",
96 | "evalue": "(34, 'Numerical result out of range')",
97 | "output_type": "error",
98 | "traceback": [
99 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
100 | "\u001b[0;31mOverflowError\u001b[0m Traceback (most recent call last)",
101 | "\u001b[0;32m/tmp/ipykernel_205130/1994322563.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;36m2.\u001b[0m \u001b[0;34m**\u001b[0m \u001b[0;36m1024\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mZeroDivisionError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
102 | "\u001b[0;31mOverflowError\u001b[0m: (34, 'Numerical result out of range')"
103 | ]
104 | }
105 | ],
106 | "source": [
107 | "try:\n",
108 | " 2. ** 1024\n",
109 | "except ZeroDivisionError as e:\n",
110 | " print(e)"
111 | ]
112 | },
113 | {
114 | "cell_type": "markdown",
115 | "metadata": {},
116 | "source": [
117 | "except節を複数並べることで、異なる複数の例外に対する処理を記述できる。"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": 4,
123 | "metadata": {},
124 | "outputs": [
125 | {
126 | "name": "stdout",
127 | "output_type": "stream",
128 | "text": [
129 | "オーバーフロー: (34, 'Numerical result out of range')\n"
130 | ]
131 | }
132 | ],
133 | "source": [
134 | "try:\n",
135 | " 2. ** 1024\n",
136 | "except ZeroDivisionError as e:\n",
137 | " print('ゼロ除算:', e)\n",
138 | "except OverflowError as e:\n",
139 | " print('オーバーフロー:', e)"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": 5,
145 | "metadata": {},
146 | "outputs": [
147 | {
148 | "name": "stdout",
149 | "output_type": "stream",
150 | "text": [
151 | "ゼロ除算: float division by zero\n"
152 | ]
153 | }
154 | ],
155 | "source": [
156 | "try:\n",
157 | " 2. / 0\n",
158 | "except ZeroDivisionError as e:\n",
159 | " print('ゼロ除算:', e)\n",
160 | "except OverflowError as e:\n",
161 | " print('オーバーフロー:', e)"
162 | ]
163 | },
164 | {
165 | "cell_type": "markdown",
166 | "metadata": {},
167 | "source": [
168 | "except節に例外クラスをタプルとしてまとめることで、異なる複数の例外に対する処理をまとめて記述できる。"
169 | ]
170 | },
171 | {
172 | "cell_type": "code",
173 | "execution_count": 6,
174 | "metadata": {},
175 | "outputs": [
176 | {
177 | "name": "stdout",
178 | "output_type": "stream",
179 | "text": [
180 | "例外: (34, 'Numerical result out of range')\n"
181 | ]
182 | }
183 | ],
184 | "source": [
185 | "try:\n",
186 | " 2. ** 1024\n",
187 | "except (ZeroDivisionError, OverflowError) as e:\n",
188 | " print('例外:', type(e), e)"
189 | ]
190 | },
191 | {
192 | "cell_type": "code",
193 | "execution_count": 7,
194 | "metadata": {},
195 | "outputs": [
196 | {
197 | "name": "stdout",
198 | "output_type": "stream",
199 | "text": [
200 | "例外: float division by zero\n"
201 | ]
202 | }
203 | ],
204 | "source": [
205 | "try:\n",
206 | " 2. / 0\n",
207 | "except (ZeroDivisionError, OverflowError) as e:\n",
208 | " print('例外:', type(e), e)"
209 | ]
210 | },
211 | {
212 | "cell_type": "markdown",
213 | "metadata": {},
214 | "source": [
215 | "なお、ZeroDivisionErrorやOverflowErrorなどの組み込み例外の基底クラスは[Exception](https://docs.python.org/ja/3/library/exceptions.html#Exception)であるため、except節でExceptionクラスを指定すると、異なる種類の例外をまとめて捕捉できる。"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": 8,
221 | "metadata": {},
222 | "outputs": [
223 | {
224 | "name": "stdout",
225 | "output_type": "stream",
226 | "text": [
227 | "例外: (34, 'Numerical result out of range')\n"
228 | ]
229 | }
230 | ],
231 | "source": [
232 | "try:\n",
233 | " 2. ** 1024\n",
234 | "except Exception as e:\n",
235 | " print('例外:', type(e), e)"
236 | ]
237 | },
238 | {
239 | "cell_type": "code",
240 | "execution_count": 9,
241 | "metadata": {},
242 | "outputs": [
243 | {
244 | "name": "stdout",
245 | "output_type": "stream",
246 | "text": [
247 | "例外: float division by zero\n"
248 | ]
249 | }
250 | ],
251 | "source": [
252 | "try:\n",
253 | " 2. / 0\n",
254 | "except Exception as e:\n",
255 | " print('例外:', type(e), e)"
256 | ]
257 | },
258 | {
259 | "cell_type": "markdown",
260 | "metadata": {},
261 | "source": [
262 | "## 例外の送出"
263 | ]
264 | },
265 | {
266 | "cell_type": "markdown",
267 | "metadata": {},
268 | "source": [
269 | "[raise](https://docs.python.org/ja/3/reference/simple_stmts.html#raise)文を用いると、自分で実装したコードの中から例外を送出できる。"
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": 10,
275 | "metadata": {},
276 | "outputs": [],
277 | "source": [
278 | "def timestamp(hour, minute, second):\n",
279 | " if hour < 0 or 24 <= hour:\n",
280 | " raise ValueError(\"引数hourは0 <= hour < 24を満たす必要があります\")\n",
281 | " if minute < 0 or 60 <= minute:\n",
282 | " raise ValueError(\"引数minuteは0 <= minute < 60を満たす必要があります\")\n",
283 | " if second < 0 or 60 <= second:\n",
284 | " raise ValueError(\"引数secondは0 <= second < 60を満たす必要があります\")\n",
285 | " return hour * 3600 + minute * 60 + second"
286 | ]
287 | },
288 | {
289 | "cell_type": "code",
290 | "execution_count": 11,
291 | "metadata": {
292 | "tags": [
293 | "raises-exception"
294 | ]
295 | },
296 | "outputs": [
297 | {
298 | "ename": "ValueError",
299 | "evalue": "引数secondは0 <= second < 60を満たす必要があります",
300 | "output_type": "error",
301 | "traceback": [
302 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
303 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
304 | "\u001b[0;32m/tmp/ipykernel_205130/3015373880.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtimestamp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m43\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m70\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
305 | "\u001b[0;32m/tmp/ipykernel_205130/1757576539.py\u001b[0m in \u001b[0;36mtimestamp\u001b[0;34m(hour, minute, second)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"引数minuteは0 <= minute < 60を満たす必要があります\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0msecond\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;36m60\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0msecond\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"引数secondは0 <= second < 60を満たす必要があります\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mhour\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m3600\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mminute\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m60\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0msecond\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
306 | "\u001b[0;31mValueError\u001b[0m: 引数secondは0 <= second < 60を満たす必要があります"
307 | ]
308 | }
309 | ],
310 | "source": [
311 | "timestamp(2, 43, 70)"
312 | ]
313 | },
314 | {
315 | "cell_type": "markdown",
316 | "metadata": {},
317 | "source": [
318 | "関数の呼び出し側にtry文を埋め込み、例外を捕捉することも可能である。"
319 | ]
320 | },
321 | {
322 | "cell_type": "code",
323 | "execution_count": 12,
324 | "metadata": {},
325 | "outputs": [
326 | {
327 | "name": "stdout",
328 | "output_type": "stream",
329 | "text": [
330 | "例外: 引数hourは0 <= hour < 24を満たす必要があります\n"
331 | ]
332 | }
333 | ],
334 | "source": [
335 | "try:\n",
336 | " timestamp(48, 0, 0)\n",
337 | "except Exception as e:\n",
338 | " print('例外:', type(e), e)"
339 | ]
340 | },
341 | {
342 | "cell_type": "markdown",
343 | "metadata": {},
344 | "source": [
345 | "例外クラスを自分で定義することもできる。ユーザ定義の例外クラスは[Exception](https://docs.python.org/ja/3/library/exceptions.html#Exception)を継承する必要がある。"
346 | ]
347 | },
348 | {
349 | "cell_type": "code",
350 | "execution_count": 13,
351 | "metadata": {},
352 | "outputs": [],
353 | "source": [
354 | "class TimestampError(Exception):\n",
355 | " pass\n",
356 | "\n",
357 | "def timestamp(hour, minute, second):\n",
358 | " if hour < 0 or 24 <= hour:\n",
359 | " raise TimestampError(\"引数hourは0 <= hour < 24を満たす必要があります\")\n",
360 | " if minute < 0 or 60 <= minute:\n",
361 | " raise TimestampError(\"引数minuteは0 <= minute < 60を満たす必要があります\")\n",
362 | " if second < 0 or 60 <= second:\n",
363 | " raise TimestampError(\"引数secondは0 <= second < 60を満たす必要があります\")\n",
364 | " return hour * 3600 + minute * 60 + second"
365 | ]
366 | },
367 | {
368 | "cell_type": "code",
369 | "execution_count": 14,
370 | "metadata": {
371 | "tags": [
372 | "raises-exception"
373 | ]
374 | },
375 | "outputs": [
376 | {
377 | "ename": "TimestampError",
378 | "evalue": "引数minuteは0 <= minute < 60を満たす必要があります",
379 | "output_type": "error",
380 | "traceback": [
381 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
382 | "\u001b[0;31mTimestampError\u001b[0m Traceback (most recent call last)",
383 | "\u001b[0;32m/tmp/ipykernel_205130/3588777746.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtimestamp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m95\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m22\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
384 | "\u001b[0;32m/tmp/ipykernel_205130/1955752630.py\u001b[0m in \u001b[0;36mtimestamp\u001b[0;34m(hour, minute, second)\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mTimestampError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"引数hourは0 <= hour < 24を満たす必要があります\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mminute\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;36m60\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0mminute\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTimestampError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"引数minuteは0 <= minute < 60を満たす必要があります\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0msecond\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;36m60\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0msecond\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mTimestampError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"引数secondは0 <= second < 60を満たす必要があります\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
385 | "\u001b[0;31mTimestampError\u001b[0m: 引数minuteは0 <= minute < 60を満たす必要があります"
386 | ]
387 | }
388 | ],
389 | "source": [
390 | "timestamp(1, 95, 22)"
391 | ]
392 | },
393 | {
394 | "cell_type": "markdown",
395 | "metadata": {},
396 | "source": [
397 | "今回の引数チェックの場合、`hour`, `minute`, `second`のそれぞれに対し、別の例外クラスを定義するのも一案である。"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": 15,
403 | "metadata": {},
404 | "outputs": [],
405 | "source": [
406 | "class TimestampError(Exception):\n",
407 | " pass\n",
408 | "\n",
409 | "class TimestampHourError(TimestampError):\n",
410 | " pass\n",
411 | "\n",
412 | "class TimestampMinuteError(TimestampError):\n",
413 | " pass\n",
414 | "\n",
415 | "class TimestampSecondError(TimestampError):\n",
416 | " pass\n",
417 | "\n",
418 | "def timestamp(hour, minute, second):\n",
419 | " if hour < 0 or 24 <= hour:\n",
420 | " raise TimestampHourError(\"引数hourは0 <= hour < 24を満たす必要があります\")\n",
421 | " if minute < 0 or 60 <= minute:\n",
422 | " raise TimestampMinuteError(\"引数minuteは0 <= minute < 60を満たす必要があります\")\n",
423 | " if second < 0 or 60 <= second:\n",
424 | " raise TimestampSecondError(\"引数secondは0 <= second < 60を満たす必要があります\")\n",
425 | " return hour * 3600 + minute * 60 + second"
426 | ]
427 | },
428 | {
429 | "cell_type": "code",
430 | "execution_count": 16,
431 | "metadata": {},
432 | "outputs": [
433 | {
434 | "name": "stdout",
435 | "output_type": "stream",
436 | "text": [
437 | "例外: 引数minuteは0 <= minute < 60を満たす必要があります\n"
438 | ]
439 | }
440 | ],
441 | "source": [
442 | "try:\n",
443 | " timestamp(2, 68, 0)\n",
444 | "except Exception as e:\n",
445 | " print('例外:', type(e), e)"
446 | ]
447 | },
448 | {
449 | "cell_type": "markdown",
450 | "metadata": {},
451 | "source": [
452 | "なお、デバッグ目的であれば[assert](https://docs.python.org/ja/3/reference/simple_stmts.html#the-assert-statement)文を使い、引数の値をチェック(テスト)して、違反していたら[AssertionError](https://docs.python.org/ja/3/library/exceptions.html#AssertionError)を送出することもできる。"
453 | ]
454 | },
455 | {
456 | "cell_type": "code",
457 | "execution_count": 17,
458 | "metadata": {},
459 | "outputs": [],
460 | "source": [
461 | "def timestamp(hour, minute, second):\n",
462 | " assert 0 <= hour < 24, \"引数hourは0 <= hour < 24を満たす必要があります\"\n",
463 | " assert 0 <= minute < 60, \"引数minuteは0 <= minute < 60を満たす必要があります\"\n",
464 | " assert 0 <= second < 60, \"引数secondは0 <= second < 60を満たす必要があります\"\n",
465 | " return hour * 3600 + minute * 60 + second"
466 | ]
467 | },
468 | {
469 | "cell_type": "code",
470 | "execution_count": 18,
471 | "metadata": {
472 | "tags": [
473 | "raises-exception"
474 | ]
475 | },
476 | "outputs": [
477 | {
478 | "ename": "AssertionError",
479 | "evalue": "引数secondは0 <= second < 60を満たす必要があります",
480 | "output_type": "error",
481 | "traceback": [
482 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
483 | "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)",
484 | "\u001b[0;32m/tmp/ipykernel_205130/3015373880.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtimestamp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m43\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m70\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
485 | "\u001b[0;32m/tmp/ipykernel_205130/811021604.py\u001b[0m in \u001b[0;36mtimestamp\u001b[0;34m(hour, minute, second)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32massert\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0mhour\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m24\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"引数hourは0 <= hour < 24を満たす必要があります\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32massert\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0mminute\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m60\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"引数minuteは0 <= minute < 60を満たす必要があります\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32massert\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0msecond\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m60\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"引数secondは0 <= second < 60を満たす必要があります\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mhour\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m3600\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mminute\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m60\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0msecond\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
486 | "\u001b[0;31mAssertionError\u001b[0m: 引数secondは0 <= second < 60を満たす必要があります"
487 | ]
488 | }
489 | ],
490 | "source": [
491 | "timestamp(2, 43, 70)"
492 | ]
493 | },
494 | {
495 | "cell_type": "markdown",
496 | "metadata": {},
497 | "source": [
498 | "## よく見かける例外"
499 | ]
500 | },
501 | {
502 | "cell_type": "markdown",
503 | "metadata": {},
504 | "source": [
505 | "文法エラー"
506 | ]
507 | },
508 | {
509 | "cell_type": "code",
510 | "execution_count": 19,
511 | "metadata": {
512 | "tags": [
513 | "raises-exception"
514 | ]
515 | },
516 | "outputs": [
517 | {
518 | "ename": "SyntaxError",
519 | "evalue": "invalid syntax (3671002116.py, line 1)",
520 | "output_type": "error",
521 | "traceback": [
522 | "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_205130/3671002116.py\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m 2 / / 1\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
523 | ]
524 | }
525 | ],
526 | "source": [
527 | "2 / / 1"
528 | ]
529 | },
530 | {
531 | "cell_type": "markdown",
532 | "metadata": {},
533 | "source": [
534 | "インデントの間違い"
535 | ]
536 | },
537 | {
538 | "cell_type": "code",
539 | "execution_count": 20,
540 | "metadata": {
541 | "tags": [
542 | "raises-exception"
543 | ]
544 | },
545 | "outputs": [
546 | {
547 | "ename": "IndentationError",
548 | "evalue": "expected an indented block after 'if' statement on line 2 (2214768420.py, line 3)",
549 | "output_type": "error",
550 | "traceback": [
551 | "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_205130/2214768420.py\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m print('even')\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block after 'if' statement on line 2\n"
552 | ]
553 | }
554 | ],
555 | "source": [
556 | "for i in range(10):\n",
557 | " if i % 2 == 0:\n",
558 | " print('even')"
559 | ]
560 | },
561 | {
562 | "cell_type": "markdown",
563 | "metadata": {},
564 | "source": [
565 | "オーバーフロー"
566 | ]
567 | },
568 | {
569 | "cell_type": "code",
570 | "execution_count": 21,
571 | "metadata": {
572 | "tags": [
573 | "raises-exception"
574 | ]
575 | },
576 | "outputs": [
577 | {
578 | "ename": "OverflowError",
579 | "evalue": "(34, 'Numerical result out of range')",
580 | "output_type": "error",
581 | "traceback": [
582 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
583 | "\u001b[0;31mOverflowError\u001b[0m Traceback (most recent call last)",
584 | "\u001b[0;32m/tmp/ipykernel_205130/997473611.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;36m2.\u001b[0m \u001b[0;34m**\u001b[0m \u001b[0;36m1024\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
585 | "\u001b[0;31mOverflowError\u001b[0m: (34, 'Numerical result out of range')"
586 | ]
587 | }
588 | ],
589 | "source": [
590 | "2. ** 1024"
591 | ]
592 | },
593 | {
594 | "cell_type": "markdown",
595 | "metadata": {},
596 | "source": [
597 | "未定義の変数"
598 | ]
599 | },
600 | {
601 | "cell_type": "code",
602 | "execution_count": 22,
603 | "metadata": {
604 | "tags": [
605 | "raises-exception"
606 | ]
607 | },
608 | "outputs": [
609 | {
610 | "ename": "NameError",
611 | "evalue": "name 'a' is not defined",
612 | "output_type": "error",
613 | "traceback": [
614 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
615 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
616 | "\u001b[0;32m/tmp/ipykernel_205130/188921875.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
617 | "\u001b[0;31mNameError\u001b[0m: name 'a' is not defined"
618 | ]
619 | }
620 | ],
621 | "source": [
622 | "a * 2"
623 | ]
624 | },
625 | {
626 | "cell_type": "markdown",
627 | "metadata": {},
628 | "source": [
629 | "範囲外のインデックス"
630 | ]
631 | },
632 | {
633 | "cell_type": "code",
634 | "execution_count": 23,
635 | "metadata": {
636 | "tags": [
637 | "raises-exception"
638 | ]
639 | },
640 | "outputs": [
641 | {
642 | "ename": "IndexError",
643 | "evalue": "list index out of range",
644 | "output_type": "error",
645 | "traceback": [
646 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
647 | "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
648 | "\u001b[0;32m/tmp/ipykernel_205130/3042274859.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
649 | "\u001b[0;31mIndexError\u001b[0m: list index out of range"
650 | ]
651 | }
652 | ],
653 | "source": [
654 | "x = [1, 2, 3]\n",
655 | "x[4]"
656 | ]
657 | },
658 | {
659 | "cell_type": "markdown",
660 | "metadata": {},
661 | "source": [
662 | "キーが見つからない"
663 | ]
664 | },
665 | {
666 | "cell_type": "code",
667 | "execution_count": 24,
668 | "metadata": {
669 | "tags": [
670 | "raises-exception"
671 | ]
672 | },
673 | "outputs": [
674 | {
675 | "ename": "KeyError",
676 | "evalue": "'four'",
677 | "output_type": "error",
678 | "traceback": [
679 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
680 | "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
681 | "\u001b[0;32m/tmp/ipykernel_205130/1027427460.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m'one'\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'two'\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'three'\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0my\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'four'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
682 | "\u001b[0;31mKeyError\u001b[0m: 'four'"
683 | ]
684 | }
685 | ],
686 | "source": [
687 | "y = {'one': 1, 'two': 2, 'three': 3}\n",
688 | "y['four']"
689 | ]
690 | },
691 | {
692 | "cell_type": "markdown",
693 | "metadata": {},
694 | "source": [
695 | "型の不整合"
696 | ]
697 | },
698 | {
699 | "cell_type": "code",
700 | "execution_count": 25,
701 | "metadata": {
702 | "tags": [
703 | "raises-exception"
704 | ]
705 | },
706 | "outputs": [
707 | {
708 | "ename": "TypeError",
709 | "evalue": "can only concatenate list (not \"dict\") to list",
710 | "output_type": "error",
711 | "traceback": [
712 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
713 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
714 | "\u001b[0;32m/tmp/ipykernel_205130/978381659.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
715 | "\u001b[0;31mTypeError\u001b[0m: can only concatenate list (not \"dict\") to list"
716 | ]
717 | }
718 | ],
719 | "source": [
720 | "x + y"
721 | ]
722 | },
723 | {
724 | "cell_type": "markdown",
725 | "metadata": {},
726 | "source": [
727 | "ファイルが見つからない"
728 | ]
729 | },
730 | {
731 | "cell_type": "code",
732 | "execution_count": 26,
733 | "metadata": {
734 | "tags": [
735 | "raises-exception"
736 | ]
737 | },
738 | "outputs": [
739 | {
740 | "ename": "FileNotFoundError",
741 | "evalue": "[Errno 2] No such file or directory: 'hoge.txt'",
742 | "output_type": "error",
743 | "traceback": [
744 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
745 | "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
746 | "\u001b[0;32m/tmp/ipykernel_205130/1539795522.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'hoge.txt'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
747 | "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'hoge.txt'"
748 | ]
749 | }
750 | ],
751 | "source": [
752 | "open('hoge.txt')"
753 | ]
754 | },
755 | {
756 | "cell_type": "markdown",
757 | "metadata": {
758 | "tags": [
759 | "remove-cell"
760 | ]
761 | },
762 | "source": [
763 | "---\n",
764 | "\n",
765 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
766 | ]
767 | }
768 | ],
769 | "metadata": {
770 | "@context": {
771 | "CreativeWork": "http://schema.org/CreativeWork",
772 | "Organization": "http://schema.org/Organization",
773 | "Person": "http://schema.org/Person",
774 | "author": "http://schema.org/author",
775 | "copyrightHolder": "http://schema.org/copyrightHolder",
776 | "copyrightYear": "http://schema.org/copyrightYear",
777 | "license": "http://schema.org/license",
778 | "name": "http://schema.org/name",
779 | "title": "http://schema.org/name",
780 | "url": "http://schema.org/url"
781 | },
782 | "@type": "CreativeWork",
783 | "author": [
784 | {
785 | "@type": "Person",
786 | "name": "Naoaki Okazaki",
787 | "url": "https://www.chokkan.org/"
788 | }
789 | ],
790 | "copyrightHolder": [
791 | {
792 | "@type": "Person",
793 | "name": "Naoaki Okazaki",
794 | "url": "https://www.chokkan.org/"
795 | }
796 | ],
797 | "copyrightYear": 2024,
798 | "kernelspec": {
799 | "display_name": "Python 3 (ipykernel)",
800 | "language": "python",
801 | "name": "python3"
802 | },
803 | "language_info": {
804 | "codemirror_mode": {
805 | "name": "ipython",
806 | "version": 3
807 | },
808 | "file_extension": ".py",
809 | "mimetype": "text/x-python",
810 | "name": "python",
811 | "nbconvert_exporter": "python",
812 | "pygments_lexer": "ipython3",
813 | "version": "3.10.12"
814 | },
815 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
816 | "title": "Python早見帳"
817 | },
818 | "nbformat": 4,
819 | "nbformat_minor": 4
820 | }
821 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Attribution-NonCommercial-NoDerivatives 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
58 | International Public License
59 |
60 | By exercising the Licensed Rights (defined below), You accept and agree
61 | to be bound by the terms and conditions of this Creative Commons
62 | Attribution-NonCommercial-NoDerivatives 4.0 International Public
63 | License ("Public License"). To the extent this Public License may be
64 | interpreted as a contract, You are granted the Licensed Rights in
65 | consideration of Your acceptance of these terms and conditions, and the
66 | Licensor grants You such rights in consideration of benefits the
67 | Licensor receives from making the Licensed Material available under
68 | these terms and conditions.
69 |
70 |
71 | Section 1 -- Definitions.
72 |
73 | a. Adapted Material means material subject to Copyright and Similar
74 | Rights that is derived from or based upon the Licensed Material
75 | and in which the Licensed Material is translated, altered,
76 | arranged, transformed, or otherwise modified in a manner requiring
77 | permission under the Copyright and Similar Rights held by the
78 | Licensor. For purposes of this Public License, where the Licensed
79 | Material is a musical work, performance, or sound recording,
80 | Adapted Material is always produced where the Licensed Material is
81 | synched in timed relation with a moving image.
82 |
83 | b. Copyright and Similar Rights means copyright and/or similar rights
84 | closely related to copyright including, without limitation,
85 | performance, broadcast, sound recording, and Sui Generis Database
86 | Rights, without regard to how the rights are labeled or
87 | categorized. For purposes of this Public License, the rights
88 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
89 | Rights.
90 |
91 | c. Effective Technological Measures means those measures that, in the
92 | absence of proper authority, may not be circumvented under laws
93 | fulfilling obligations under Article 11 of the WIPO Copyright
94 | Treaty adopted on December 20, 1996, and/or similar international
95 | agreements.
96 |
97 | d. Exceptions and Limitations means fair use, fair dealing, and/or
98 | any other exception or limitation to Copyright and Similar Rights
99 | that applies to Your use of the Licensed Material.
100 |
101 | e. Licensed Material means the artistic or literary work, database,
102 | or other material to which the Licensor applied this Public
103 | License.
104 |
105 | f. Licensed Rights means the rights granted to You subject to the
106 | terms and conditions of this Public License, which are limited to
107 | all Copyright and Similar Rights that apply to Your use of the
108 | Licensed Material and that the Licensor has authority to license.
109 |
110 | g. Licensor means the individual(s) or entity(ies) granting rights
111 | under this Public License.
112 |
113 | h. NonCommercial means not primarily intended for or directed towards
114 | commercial advantage or monetary compensation. For purposes of
115 | this Public License, the exchange of the Licensed Material for
116 | other material subject to Copyright and Similar Rights by digital
117 | file-sharing or similar means is NonCommercial provided there is
118 | no payment of monetary compensation in connection with the
119 | exchange.
120 |
121 | i. Share means to provide material to the public by any means or
122 | process that requires permission under the Licensed Rights, such
123 | as reproduction, public display, public performance, distribution,
124 | dissemination, communication, or importation, and to make material
125 | available to the public including in ways that members of the
126 | public may access the material from a place and at a time
127 | individually chosen by them.
128 |
129 | j. Sui Generis Database Rights means rights other than copyright
130 | resulting from Directive 96/9/EC of the European Parliament and of
131 | the Council of 11 March 1996 on the legal protection of databases,
132 | as amended and/or succeeded, as well as other essentially
133 | equivalent rights anywhere in the world.
134 |
135 | k. You means the individual or entity exercising the Licensed Rights
136 | under this Public License. Your has a corresponding meaning.
137 |
138 |
139 | Section 2 -- Scope.
140 |
141 | a. License grant.
142 |
143 | 1. Subject to the terms and conditions of this Public License,
144 | the Licensor hereby grants You a worldwide, royalty-free,
145 | non-sublicensable, non-exclusive, irrevocable license to
146 | exercise the Licensed Rights in the Licensed Material to:
147 |
148 | a. reproduce and Share the Licensed Material, in whole or
149 | in part, for NonCommercial purposes only; and
150 |
151 | b. produce and reproduce, but not Share, Adapted Material
152 | for NonCommercial purposes only.
153 |
154 | 2. Exceptions and Limitations. For the avoidance of doubt, where
155 | Exceptions and Limitations apply to Your use, this Public
156 | License does not apply, and You do not need to comply with
157 | its terms and conditions.
158 |
159 | 3. Term. The term of this Public License is specified in Section
160 | 6(a).
161 |
162 | 4. Media and formats; technical modifications allowed. The
163 | Licensor authorizes You to exercise the Licensed Rights in
164 | all media and formats whether now known or hereafter created,
165 | and to make technical modifications necessary to do so. The
166 | Licensor waives and/or agrees not to assert any right or
167 | authority to forbid You from making technical modifications
168 | necessary to exercise the Licensed Rights, including
169 | technical modifications necessary to circumvent Effective
170 | Technological Measures. For purposes of this Public License,
171 | simply making modifications authorized by this Section 2(a)
172 | (4) never produces Adapted Material.
173 |
174 | 5. Downstream recipients.
175 |
176 | a. Offer from the Licensor -- Licensed Material. Every
177 | recipient of the Licensed Material automatically
178 | receives an offer from the Licensor to exercise the
179 | Licensed Rights under the terms and conditions of this
180 | Public License.
181 |
182 | b. No downstream restrictions. You may not offer or impose
183 | any additional or different terms or conditions on, or
184 | apply any Effective Technological Measures to, the
185 | Licensed Material if doing so restricts exercise of the
186 | Licensed Rights by any recipient of the Licensed
187 | Material.
188 |
189 | 6. No endorsement. Nothing in this Public License constitutes or
190 | may be construed as permission to assert or imply that You
191 | are, or that Your use of the Licensed Material is, connected
192 | with, or sponsored, endorsed, or granted official status by,
193 | the Licensor or others designated to receive attribution as
194 | provided in Section 3(a)(1)(A)(i).
195 |
196 | b. Other rights.
197 |
198 | 1. Moral rights, such as the right of integrity, are not
199 | licensed under this Public License, nor are publicity,
200 | privacy, and/or other similar personality rights; however, to
201 | the extent possible, the Licensor waives and/or agrees not to
202 | assert any such rights held by the Licensor to the limited
203 | extent necessary to allow You to exercise the Licensed
204 | Rights, but not otherwise.
205 |
206 | 2. Patent and trademark rights are not licensed under this
207 | Public License.
208 |
209 | 3. To the extent possible, the Licensor waives any right to
210 | collect royalties from You for the exercise of the Licensed
211 | Rights, whether directly or through a collecting society
212 | under any voluntary or waivable statutory or compulsory
213 | licensing scheme. In all other cases the Licensor expressly
214 | reserves any right to collect such royalties, including when
215 | the Licensed Material is used other than for NonCommercial
216 | purposes.
217 |
218 |
219 | Section 3 -- License Conditions.
220 |
221 | Your exercise of the Licensed Rights is expressly made subject to the
222 | following conditions.
223 |
224 | a. Attribution.
225 |
226 | 1. If You Share the Licensed Material, You must:
227 |
228 | a. retain the following if it is supplied by the Licensor
229 | with the Licensed Material:
230 |
231 | i. identification of the creator(s) of the Licensed
232 | Material and any others designated to receive
233 | attribution, in any reasonable manner requested by
234 | the Licensor (including by pseudonym if
235 | designated);
236 |
237 | ii. a copyright notice;
238 |
239 | iii. a notice that refers to this Public License;
240 |
241 | iv. a notice that refers to the disclaimer of
242 | warranties;
243 |
244 | v. a URI or hyperlink to the Licensed Material to the
245 | extent reasonably practicable;
246 |
247 | b. indicate if You modified the Licensed Material and
248 | retain an indication of any previous modifications; and
249 |
250 | c. indicate the Licensed Material is licensed under this
251 | Public License, and include the text of, or the URI or
252 | hyperlink to, this Public License.
253 |
254 | For the avoidance of doubt, You do not have permission under
255 | this Public License to Share Adapted Material.
256 |
257 | 2. You may satisfy the conditions in Section 3(a)(1) in any
258 | reasonable manner based on the medium, means, and context in
259 | which You Share the Licensed Material. For example, it may be
260 | reasonable to satisfy the conditions by providing a URI or
261 | hyperlink to a resource that includes the required
262 | information.
263 |
264 | 3. If requested by the Licensor, You must remove any of the
265 | information required by Section 3(a)(1)(A) to the extent
266 | reasonably practicable.
267 |
268 |
269 | Section 4 -- Sui Generis Database Rights.
270 |
271 | Where the Licensed Rights include Sui Generis Database Rights that
272 | apply to Your use of the Licensed Material:
273 |
274 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
275 | to extract, reuse, reproduce, and Share all or a substantial
276 | portion of the contents of the database for NonCommercial purposes
277 | only and provided You do not Share Adapted Material;
278 |
279 | b. if You include all or a substantial portion of the database
280 | contents in a database in which You have Sui Generis Database
281 | Rights, then the database in which You have Sui Generis Database
282 | Rights (but not its individual contents) is Adapted Material; and
283 |
284 | c. You must comply with the conditions in Section 3(a) if You Share
285 | all or a substantial portion of the contents of the database.
286 |
287 | For the avoidance of doubt, this Section 4 supplements and does not
288 | replace Your obligations under this Public License where the Licensed
289 | Rights include other Copyright and Similar Rights.
290 |
291 |
292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
293 |
294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
304 |
305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
314 |
315 | c. The disclaimer of warranties and limitation of liability provided
316 | above shall be interpreted in a manner that, to the extent
317 | possible, most closely approximates an absolute disclaimer and
318 | waiver of all liability.
319 |
320 |
321 | Section 6 -- Term and Termination.
322 |
323 | a. This Public License applies for the term of the Copyright and
324 | Similar Rights licensed here. However, if You fail to comply with
325 | this Public License, then Your rights under this Public License
326 | terminate automatically.
327 |
328 | b. Where Your right to use the Licensed Material has terminated under
329 | Section 6(a), it reinstates:
330 |
331 | 1. automatically as of the date the violation is cured, provided
332 | it is cured within 30 days of Your discovery of the
333 | violation; or
334 |
335 | 2. upon express reinstatement by the Licensor.
336 |
337 | For the avoidance of doubt, this Section 6(b) does not affect any
338 | right the Licensor may have to seek remedies for Your violations
339 | of this Public License.
340 |
341 | c. For the avoidance of doubt, the Licensor may also offer the
342 | Licensed Material under separate terms or conditions or stop
343 | distributing the Licensed Material at any time; however, doing so
344 | will not terminate this Public License.
345 |
346 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
347 | License.
348 |
349 |
350 | Section 7 -- Other Terms and Conditions.
351 |
352 | a. The Licensor shall not be bound by any additional or different
353 | terms or conditions communicated by You unless expressly agreed.
354 |
355 | b. Any arrangements, understandings, or agreements regarding the
356 | Licensed Material not stated herein are separate from and
357 | independent of the terms and conditions of this Public License.
358 |
359 |
360 | Section 8 -- Interpretation.
361 |
362 | a. For the avoidance of doubt, this Public License does not, and
363 | shall not be interpreted to, reduce, limit, restrict, or impose
364 | conditions on any use of the Licensed Material that could lawfully
365 | be made without permission under this Public License.
366 |
367 | b. To the extent possible, if any provision of this Public License is
368 | deemed unenforceable, it shall be automatically reformed to the
369 | minimum extent necessary to make it enforceable. If the provision
370 | cannot be reformed, it shall be severed from this Public License
371 | without affecting the enforceability of the remaining terms and
372 | conditions.
373 |
374 | c. No term or condition of this Public License will be waived and no
375 | failure to comply consented to unless expressly agreed to by the
376 | Licensor.
377 |
378 | d. Nothing in this Public License constitutes or may be interpreted
379 | as a limitation upon, or waiver of, any privileges and immunities
380 | that apply to the Licensor or You, including from the legal
381 | processes of any jurisdiction or authority.
382 |
383 | =======================================================================
384 |
385 | Creative Commons is not a party to its public
386 | licenses. Notwithstanding, Creative Commons may elect to apply one of
387 | its public licenses to material it publishes and in those instances
388 | will be considered the “Licensor.” The text of the Creative Commons
389 | public licenses is dedicated to the public domain under the CC0 Public
390 | Domain Dedication. Except for the limited purpose of indicating that
391 | material is shared under a Creative Commons public license or as
392 | otherwise permitted by the Creative Commons policies published at
393 | creativecommons.org/policies, Creative Commons does not authorize the
394 | use of the trademark "Creative Commons" or any other trademark or logo
395 | of Creative Commons without its prior written consent including,
396 | without limitation, in connection with any unauthorized modifications
397 | to any of its public licenses or any other arrangements,
398 | understandings, or agreements concerning use of licensed material. For
399 | the avoidance of doubt, this paragraph does not form part of the
400 | public licenses.
401 |
402 | Creative Commons may be contacted at creativecommons.org.
403 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python早見帳
2 |
3 | Python早見帳は、プログラミング言語Pythonを素早く概観(**早見**)するノート(**帳**)です。
4 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | #######################################################################################
2 | # A default configuration that will be loaded for all jupyter books
3 | # Users are expected to override these values in their own `_config.yml` file.
4 | # This is also the "master list" of all allowed keys and values.
5 |
6 | #######################################################################################
7 | # Book settings
8 | title: Python早見帳
9 | author: ""
10 | copyright: "2020-2024 by 岡崎 直観 (Naoaki Okazaki), クリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 (CC BY-NC-ND 4.0)"
11 | exclude_patterns: [_build, material, README.md, Thumbs.db, .DS_Store, "**.ipynb_checkpoints"]
12 | only_build_toc_files: true
13 |
14 | #######################################################################################
15 | # Execution settings
16 | execute:
17 | execute_notebooks : off # Whether to execute notebooks at build time. Must be one of ("auto", "force", "cache", "off")
18 | cache : "" # A path to the jupyter cache that will be used to store execution artifacts. Defaults to `_build/.jupyter_cache/`
19 | exclude_patterns : [] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time)
20 | timeout : 30 # The maximum time (in seconds) each notebook cell is allowed to run.
21 | run_in_temp : false # If `True`, then a temporary directory will be created and used as the command working directory (cwd),
22 | # otherwise the notebook's parent directory will be the cwd.
23 | allow_errors : false # If `False`, when a code cell raises an error the execution is stopped, otherwise all cells are always run.
24 | stderr_output : show # One of 'show', 'remove', 'remove-warn', 'warn', 'error', 'severe'
25 |
26 | #######################################################################################
27 | # Parse and render settings
28 | parse:
29 | myst_enable_extensions: # default extensions to enable in the myst parser. See https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html
30 | - amsmath
31 | - colon_fence
32 | # - deflist
33 | - dollarmath
34 | # - html_admonition
35 | # - html_image
36 | - linkify
37 | # - replacements
38 | # - smartquotes
39 | - substitution
40 | - tasklist
41 | myst_url_schemes: [mailto, http, https] # URI schemes that will be recognised as external URLs in Markdown links
42 | myst_dmath_double_inline: true # Allow display math ($$) within an inline context
43 |
44 | #######################################################################################
45 | # HTML-specific settings
46 | html:
47 | favicon : "favicon.ico" # A path to a favicon image
48 | use_edit_page_button : false # Whether to add an "edit this page" button to pages. If `true`, repository information in repository: must be filled in
49 | use_repository_button : true # Whether to add a link to your repository button
50 | use_issues_button : true # Whether to add an "open an issue" button
51 | use_multitoc_numbering : true # Continuous numbering across parts/chapters
52 | extra_footer: | # Will be displayed underneath the footer.
53 | © Copyright 2020-2024 by 岡崎 直観 (Naoaki Okazaki). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
54 | home_page_in_navbar : false # Whether to include your home page in the left Navigation Bar
55 | baseurl : "https://chokkan.github.io/python/" # The base URL where your book will be hosted. Used for creating image previews and social links. e.g.: https://mypage.com/mybook/
56 | analytics:
57 | plausible_analytics_domain: ""
58 | plausible_analytics_url: "https://plausible.io/js/script.js"
59 | google_analytics_id : "G-F7QDQE5R7W" # A GA id that can be used to track book views.
60 | comments:
61 | hypothesis : false
62 | utterances : false
63 | announcement : "" # A banner announcement at the top of the site.
64 |
65 | #######################################################################################
66 | # Launch button settings
67 | launch_buttons:
68 | notebook_interface : "jupyterlab" # The interface interactive links will activate ["classic", "jupyterlab"]
69 | binderhub_url : "https://mybinder.org" # The URL of the BinderHub (e.g., https://mybinder.org)
70 | jupyterhub_url : "" # The URL of the JupyterHub (e.g., https://datahub.berkeley.edu)
71 | thebe : true # Add a thebe button to pages (requires the repository to run on Binder)
72 | colab_url : "https://colab.research.google.com" # The URL of Google Colab (https://colab.research.google.com)
73 |
74 | repository:
75 | url: https://github.com/chokkan/python # Online location of your book
76 | path_to_book : "" # A path to your book's folder, relative to the repository root.
77 | branch: main # Which branch of the repository should be used when creating links (optional)
78 |
79 | sphinx:
80 | extra_extensions : # A list of extra extensions to load by Sphinx (added to those already used by JB).
81 | local_extensions : # A list of local extensions to load by sphinx specified by "name: path" items
82 | recursive_update : false # A boolean indicating whether to overwrite the Sphinx config (true) or recursively update (false)
83 | config:
84 | language: ja
85 | html_show_copyright: false
86 |
--------------------------------------------------------------------------------
/_toc.yml:
--------------------------------------------------------------------------------
1 | format: jb-book
2 | root: index
3 |
4 | parts:
5 | - caption: 基礎
6 | numbered: true
7 | chapters:
8 | - file: 01calc
9 | - file: 02variable
10 | - file: 03control
11 | - file: 04function
12 | - file: 05module
13 | - caption: データ構造
14 | numbered: true
15 | chapters:
16 | - file: 06list
17 | - file: 07tuple
18 | - file: 08str
19 | - file: 09dict
20 | - file: 10set
21 | - caption: 発展
22 | numbered: true
23 | chapters:
24 | - file: 11file
25 | - file: 12immutable
26 | - file: 13class
27 | - file: 14exception
28 | - file: 15iterator
29 | - caption: 科学技術計算とデータ分析
30 | numbered: true
31 | chapters:
32 | - file: 16numpy1
33 | - file: 17numpy2
34 | - file: 18plot
35 | - caption: 付録
36 | numbered: False
37 | chapters:
38 | - file: jupyter
39 | - file: references
40 |
--------------------------------------------------------------------------------
/assets/image/colab-clean.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-clean.png
--------------------------------------------------------------------------------
/assets/image/colab-code.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-code.png
--------------------------------------------------------------------------------
/assets/image/colab-insert-text.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-insert-text.png
--------------------------------------------------------------------------------
/assets/image/colab-new.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-new.png
--------------------------------------------------------------------------------
/assets/image/colab-rename.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-rename.png
--------------------------------------------------------------------------------
/assets/image/colab-save.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-save.png
--------------------------------------------------------------------------------
/assets/image/colab-text.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-text.png
--------------------------------------------------------------------------------
/assets/image/colab-upload.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/colab-upload.png
--------------------------------------------------------------------------------
/assets/image/jupyter-lab.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/jupyter-lab.png
--------------------------------------------------------------------------------
/assets/image/jupyter-notebook.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/jupyter-notebook.png
--------------------------------------------------------------------------------
/assets/image/jupyter-notebook2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/jupyter-notebook2.png
--------------------------------------------------------------------------------
/assets/image/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/logo.png
--------------------------------------------------------------------------------
/assets/image/scatter.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/assets/image/scatter.gif
--------------------------------------------------------------------------------
/decorator.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "e4725cfa",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "def npath(x, y):\n",
11 | " if x == 0 or y == 0:\n",
12 | " return 1\n",
13 | " else:\n",
14 | " return npath(x-1, y) + npath(x, y-1)"
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": 2,
20 | "id": "b2ffaeae",
21 | "metadata": {},
22 | "outputs": [
23 | {
24 | "name": "stdout",
25 | "output_type": "stream",
26 | "text": [
27 | "46.5 µs ± 1.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n"
28 | ]
29 | }
30 | ],
31 | "source": [
32 | "%timeit npath(8, 4)"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": 3,
38 | "id": "b9904a84",
39 | "metadata": {},
40 | "outputs": [],
41 | "source": [
42 | "def memo(func):\n",
43 | " M = {}\n",
44 | " def wrapper(x, y):\n",
45 | " n = M.get((x, y))\n",
46 | " if n is None:\n",
47 | " v = func(x, y)\n",
48 | " M[(x, y)] = v\n",
49 | " return v\n",
50 | " else:\n",
51 | " return n\n",
52 | " return wrapper\n",
53 | "\n",
54 | "npath_memo = memo(npath)"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": 4,
60 | "id": "1b5342af",
61 | "metadata": {},
62 | "outputs": [
63 | {
64 | "name": "stdout",
65 | "output_type": "stream",
66 | "text": [
67 | "70.9 ns ± 1.86 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n"
68 | ]
69 | }
70 | ],
71 | "source": [
72 | "%timeit npath_memo(8, 4)"
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": 5,
78 | "id": "fe3fb1d9",
79 | "metadata": {},
80 | "outputs": [],
81 | "source": [
82 | "@memo\n",
83 | "def npath(x, y):\n",
84 | " if x == 0 or y == 0:\n",
85 | " return 1\n",
86 | " else:\n",
87 | " return npath(x-1, y) + npath(x, y-1)"
88 | ]
89 | },
90 | {
91 | "cell_type": "code",
92 | "execution_count": 6,
93 | "id": "36c4f366",
94 | "metadata": {},
95 | "outputs": [
96 | {
97 | "name": "stdout",
98 | "output_type": "stream",
99 | "text": [
100 | "70.7 ns ± 0.582 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n"
101 | ]
102 | }
103 | ],
104 | "source": [
105 | "%timeit npath(8, 4)"
106 | ]
107 | },
108 | {
109 | "cell_type": "markdown",
110 | "id": "afd03434-6b4a-4662-89ad-20d90893ceda",
111 | "metadata": {
112 | "tags": [
113 | "remove-cell"
114 | ]
115 | },
116 | "source": [
117 | "---\n",
118 | "\n",
119 | "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品はクリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンスの下に提供されています。
"
120 | ]
121 | }
122 | ],
123 | "metadata": {
124 | "@context": {
125 | "CreativeWork": "http://schema.org/CreativeWork",
126 | "Organization": "http://schema.org/Organization",
127 | "Person": "http://schema.org/Person",
128 | "author": "http://schema.org/author",
129 | "copyrightHolder": "http://schema.org/copyrightHolder",
130 | "copyrightYear": "http://schema.org/copyrightYear",
131 | "license": "http://schema.org/license",
132 | "name": "http://schema.org/name",
133 | "title": "http://schema.org/name",
134 | "url": "http://schema.org/url"
135 | },
136 | "@type": "CreativeWork",
137 | "author": [
138 | {
139 | "@type": "Person",
140 | "name": "Naoaki Okazaki",
141 | "url": "https://www.chokkan.org/"
142 | }
143 | ],
144 | "copyrightHolder": [
145 | {
146 | "@type": "Person",
147 | "name": "Naoaki Okazaki",
148 | "url": "https://www.chokkan.org/"
149 | }
150 | ],
151 | "copyrightYear": 2024,
152 | "kernelspec": {
153 | "display_name": "Python 3 (ipykernel)",
154 | "language": "python",
155 | "name": "python3"
156 | },
157 | "language_info": {
158 | "codemirror_mode": {
159 | "name": "ipython",
160 | "version": 3
161 | },
162 | "file_extension": ".py",
163 | "mimetype": "text/x-python",
164 | "name": "python",
165 | "nbconvert_exporter": "python",
166 | "pygments_lexer": "ipython3",
167 | "version": "3.10.12"
168 | },
169 | "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja",
170 | "title": "Python早見帳"
171 | },
172 | "nbformat": 4,
173 | "nbformat_minor": 5
174 | }
175 |
--------------------------------------------------------------------------------
/index.md:
--------------------------------------------------------------------------------
1 | # はじめに
2 |
3 | ```{only} html
4 | [](https://colab.research.google.com/github/chokkan/python/blob/main/)
5 | [](https://studiolab.sagemaker.aws/import/github/chokkan/python/blob/master/01calc.ipynb)
6 | [](https://mybinder.org/v2/gh/chokkan/python/main)
7 | [](https://jupyterbook.org)
8 | [](https://www.python.org/)
9 | [](https://numpy.org/)
10 | [](https://matplotlib.org/)
11 | ```
12 |
13 | Python早見帳は、Pythonのプログラムと実行例をさっと確認(**早見**)できるJupyter Notebook(**帳**)です。
14 |
15 | ::::{grid} 2
16 | :gutter: 2
17 |
18 | :::{grid-item-card} Pythonの基礎事項を素早く学べる 📖
19 | Python早見帳は、プログラムと実行例をカタログ的に提示しながら、Pythonの言語仕様やライブラリを紹介しています。Pythonの基礎を素早く習得したり、ライブラリやオブジェクトの使い方を確認することができます。
20 | :::
21 |
22 | :::{grid-item-card} 👩💻 Jupyter Notebook 👨💻
23 | Python早見帳のJupyter Notebookを[Github上で公開](https://github.com/chokkan/python)していますので、解説を読みながら実際にプログラムを動かすことができます。各ページにある[Google Colaboratory](https://colab.research.google.com/)や[Binder](https://mybinder.org/)へのリンクをクリックすることで、Python早見帳の実行環境がすぐに立ち上がります。
24 | :::
25 |
26 | :::{grid-item-card} 📈 データ分析のトピックをカバー 📊
27 | Pythonでデータ分析や機械学習を行うときに基礎となるライブラリである[NumPy](https://numpy.org/)と[Matplotlib](https://matplotlib.org/)を紹介しています。
28 | :::
29 |
30 | :::{grid-item-card} オープンソース・プロジェクト 🎁
31 | Python早見帳は、[クリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 (CC BY-NC-ND 4.0)](https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja)のライセンスで公開されています。不具合報告はGitHubの[issues](https://github.com/chokkan/python/issues)までお願いします。
32 | :::
33 | ::::
34 |
35 | Python早見帳は、[Jupyter Lab](https://jupyter.org/#jupyterlab)で書かれたコンテンツを[Jupyter Book](https://jupyterbook.org/)で変換することで生成されています。
36 |
37 | ## 講義
38 |
39 | + 東京工業大学情報理工学院 [機械学習 (CSC.T254)](http://www.ocw.titech.ac.jp/index.php?module=General&action=T0300&JWC=202127792)
40 |
--------------------------------------------------------------------------------
/material/card-a4.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/material/card-a4.ai
--------------------------------------------------------------------------------
/material/python-note.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chokkan/python/8d4654a3339b1e9043ada42267b608c14c6d082b/material/python-note.png
--------------------------------------------------------------------------------
/optim.py:
--------------------------------------------------------------------------------
1 | def bisection(func, a, b, eps=1e-8):
2 | while True:
3 | x = (a + b) / 2
4 | fx = func(x)
5 | if -eps < fx < eps:
6 | return x
7 | fa = func(a)
8 | if fx * fa < 0:
9 | b = x
10 | else:
11 | a = x
12 |
13 | def newton_raphson(func_f, func_g, x=0, eps=1e-8):
14 | while True:
15 | fx, gx = func_f(x), func_g(x)
16 | if -eps < fx < eps:
17 | return x
18 | x -= fx / gx
19 |
--------------------------------------------------------------------------------
/optim2.py:
--------------------------------------------------------------------------------
1 | def bisection(func, a, b, eps=1e-8):
2 | while True:
3 | x = (a + b) / 2
4 | fx = func(x)
5 | if -eps < fx < eps:
6 | return x
7 | fa = func(a)
8 | if fx * fa < 0:
9 | b = x
10 | else:
11 | a = x
12 |
13 | def newton_raphson(func_f, func_g, x=0, eps=1e-8):
14 | while True:
15 | fx, gx = func_f(x), func_g(x)
16 | if -eps < fx < eps:
17 | return x
18 | x -= fx / gx
19 |
20 | def f(x):
21 | return x ** 2 + 2 * x - 3
22 |
23 | def g(x):
24 | return 2 * x + 2
25 |
26 | print(bisection(f, -2, 2))
27 | print(newton_raphson(f, g, 0))
28 |
--------------------------------------------------------------------------------
/references.md:
--------------------------------------------------------------------------------
1 | # リンク・謝辞
2 |
3 | ## リンク
4 |
5 | + [Pythonチュートリアル](https://docs.python.org/ja/3/tutorial/)
6 | + [Dive Into Python 3 日本語版](http://diveintopython3-ja.rdy.jp/)
7 | + [Pythonプログラミング入門](https://utokyo-ipp.github.io/index.html)(東京大学 数理・情報教育研究センター)
8 | + [プログラミング演習 Python 2019](https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/245698/1/Version2020_02_13_01.pdf)(京都大学 国際高等教育院)
9 | + [コンピュータ処理](https://amorphous.tf.chiba-u.jp/lecture.files/chem_computer/index.html)(千葉大学 共生応用化学科)
10 | + [Python入門](https://www.atmarkit.co.jp/ait/subtop/features/di/all.html#pythone585a5e99680)(@IT/Deep Insider)
11 | + [機械学習&ディープラーニング入門(作業環境準備編)](https://www.atmarkit.co.jp/ait/series/15223/)(@IT/Deep Insider)
12 |
13 | ## 謝辞
14 |
15 | + [The Python Logo](https://www.python.org/community/logos/): The Twitter card of this Web site includes the Python logo.
16 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | matplotlib
3 |
--------------------------------------------------------------------------------
/tools/build.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 | import glob
3 | import os
4 | import re
5 | import shutil
6 | import sys
7 |
8 | twitter_card = """
9 |
10 |
11 |
12 |
13 |
14 |
15 | """
16 |
17 | sagemaker_studio_lab = """
18 | Colab
19 |
20 |
21 |
22 |
23 |
27 |
28 |
29 |
30 |
31 | SageMaker
32 | """
33 |
34 | def build():
35 | os.system('jupyter-book build --all .')
36 |
37 | def modify_html():
38 | # Copy the Twitter card.
39 | shutil.copyfile('./material/python-note.png', './_build/html/_static/python-note.png')
40 |
41 | # Modify the generated HTML files.
42 | for src in glob.glob('_build/html/**/*.html', recursive=True):
43 | print(f'Updating: {src}')
44 |
45 | # Load the HTML content.
46 | with open(src) as fi:
47 | content = fi.read()
48 |
49 | # Find the path to .ipynb
50 | path = ''
51 | m = re.search(r'"https://colab\.research\.google\.com/github/chokkan/python/blob/main/([^"]+)"', content)
52 | if m is not None:
53 | path = m.group(1)
54 | print(f' path: {path}')
55 |
56 | # Add meta tags for Twitter card.
57 | content = content.replace('', twitter_card)
58 |
59 | # Add the button for SageMaker Studio Lab.
60 | if path:
61 | content = content.replace(
62 | 'Colab',
63 | sagemaker_studio_lab.format(path)
64 | )
65 |
66 | # Write out the HTML content.
67 | with open(src, 'w') as fo:
68 | fo.write(content)
69 |
70 | def update_license():
71 | for src in glob.glob('*.ipynb'):
72 | with open(src) as fi:
73 | content = fi.read()
74 | #content = content.replace('Copyright 2020-2022', 'Copyright 2020-2024')
75 | with open(src, 'w') as fo:
76 | fo.write(content)
77 |
78 | if __name__ == '__main__':
79 | #update_license()
80 | build()
81 | modify_html()
82 |
--------------------------------------------------------------------------------
/tools/update-license.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 |
3 | import glob
4 |
5 | if __name__ == '__main__':
6 | for src in glob.glob('*.ipynb'):
7 | with open(src) as fi:
8 | content = fi.read()
9 | content = content.replace('Copyright 2020-2022', 'Copyright 2020-2024')
10 | content = content.replace('"copyrightYear": 2022,', '"copyrightYear": 2024,')
11 | with open(src, 'w') as fo:
12 | fo.write(content)
13 |
--------------------------------------------------------------------------------
/tools/upload.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ghp-import -n -p -f _build/html
3 |
--------------------------------------------------------------------------------