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  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1.2 Python 进阶"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.1 列表推导式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "循环可以用来生成列表:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [x for x in range(4)]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在循环的过程中使用 `if`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [x for x in range(3,10) if x % 2 == 0]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2 个`for` 循环:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [(x,y) for x in range(1,3) for y in range(1,3)]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3 个 `for` 循环:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [(x,y,z) for x in range(1,3) for y in range(1,3) for z in range(1,3)]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以使用推导式生成集合和字典:  \n",
    "**字典推导式**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [10, 21, 4, 7, 12]\n",
    "square_dict = {x: x**2 for x in values if x <= 10}\n",
    "print(square_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**集合推导式**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [10, 21, 4, 7, 12]\n",
    "square_set = {x**2 for x in values if x <= 10}\n",
    "print(square_set)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.2 函数\n",
    "\n",
    "### 定义函数\n",
    "\n",
    "函数`function`,通常接收输入参数,并有返回值。\n",
    "\n",
    "它负责完成某项特定任务,而且相较于其他代码,具备相对的独立性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(x, y):\n",
    "    \"\"\"Add two numbers\"\"\"\n",
    "    a = x + y\n",
    "    return a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函数通常有一下几个特征:\n",
    "- 使用 `def` 关键词来定义一个函数。\n",
    "-  `def` 后面是函数的名称,括号中是函数的参数,不同的参数用 `,` 隔开, `def foo():` 的形式是必须要有的,参数可以为空;\n",
    "- 使用缩进来划分函数的内容;\n",
    "-  `docstring` 用 `\"\"\"` 包含的字符串,用来解释函数的用途,可省略;\n",
    "-  `return` 返回特定的值,如果省略,返回 `None` 。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用函数\n",
    "\n",
    "使用函数时,只需要将参数换成特定的值传给函数。\n",
    "\n",
    "**Python** 并没有限定参数的类型,因此可以使用不同的参数类型:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(2, 3))\n",
    "print(add('foo', 'bar'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这个例子中,如果传入的两个参数不可以相加,那么 **Python** 会将报错:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(2, \"foo\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果传入的参数数目与实际不符合,也会报错:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(1, 2, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "传入参数时,**Python** 提供了两种选项,第一种是上面使用的按照位置传入参数,另一种则是使用关键词模式,显式地指定参数的值:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(x=2, y=3))\n",
    "print(add(y=\"foo\", x=\"bar\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以混合这两种模式:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(2, y=3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 设定参数默认值\n",
    "\n",
    "可以在函数定义的时候给参数设定默认值,例如:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def quad(x, a=1, b=0, c=0):\n",
    "    return a*x**2 + b*x + c"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以省略有默认值的参数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(quad(2.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以修改参数的默认值:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(quad(2.0, b=3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(quad(2.0, 2, c=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里混合了位置和指定两种参数传入方式,第二个 2 是传给 `a` 的。\n",
    "\n",
    "注意,在使用混合语法时,要注意不能给同一个值赋值多次,否则会报错,例如:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(quad(2.0, 2, a=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 接收不定长参数\n",
    "\n",
    "使用如下方法,可以使函数接受不定数目的参数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(x, *args):\n",
    "    total = x\n",
    "    for arg in args:\n",
    "        total += arg\n",
    "    return total"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里,`*args` 表示参数数目不定,可以看成一个元组,把第一个参数后面的参数当作元组中的元素。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(1, 2, 3, 4))\n",
    "print(add(1, 2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这样定义的函数不能使用关键词传入参数,要使用关键词,可以这样:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(x, **kwargs):\n",
    "    total = x\n",
    "    for arg, value in kwargs.items():\n",
    "        print(\"adding %s=%s\"%(arg,value))\n",
    "        total += value\n",
    "    return total\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里, `**kwargs` 表示参数数目不定,相当于一个字典,键和值对应于键值对。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(add(10, y=11, z=12, w=13))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再看这个例子,可以接收任意数目的位置参数和键值对参数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def foo(*args, **kwargs):\n",
    "    print(args, kwargs)\n",
    "\n",
    "foo(2, 3, x='bar', z=10)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "不过要按顺序传入参数,先传入位置参数 `args` ,再传入关键词参数 `kwargs` 。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 返回多个值\n",
    "\n",
    "函数可以返回多个值:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divid(a, b):\n",
    "    \"\"\"\n",
    "    除法\n",
    "    :param a: number 被除数\n",
    "    :param b: number 除数\n",
    "    :return: 商和余数\n",
    "    \"\"\"\n",
    "    quotient = a // b\n",
    "    remainder = a % b\n",
    "    return quotient, remainder\n",
    "\n",
    "quotient, remainder = divid(7,4)\n",
    "print(quotient, remainder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上,**Python** 将返回的两个值变成了元组:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(divid(7,4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为这个元组中有两个值,所以可以使用\n",
    "\n",
    "    quotient, remainder = divid(7,4)\n",
    "\n",
    "给两个值赋值。\n",
    "\n",
    "列表也有相似的功能:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b, c = [1, 2, 3]\n",
    "print(a, b, c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上,不仅仅返回值可以用元组表示,也可以将参数用元组以这种方式传入:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divid(a, b):\n",
    "    \"\"\"\n",
    "    除法\n",
    "    :param a: number 被除数\n",
    "    :param b: number 除数\n",
    "    :return: 商和余数\n",
    "    \"\"\"\n",
    "    quotient = a // b\n",
    "    remainder = a % b\n",
    "    return quotient, remainder\n",
    "\n",
    "z = (7,4)\n",
    "print(divid(*z))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里的`*`必不可少。\n",
    "\n",
    "事实上,还可以通过字典传入参数来执行函数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divid(a, b):\n",
    "    \"\"\"\n",
    "    除法\n",
    "    :param a: number 被除数\n",
    "    :param b: number 除数\n",
    "    :return: 商和余数\n",
    "    \"\"\"\n",
    "    quotient = a // b\n",
    "    remainder = a % b\n",
    "    return quotient, remainder\n",
    "\n",
    "z = {'a':7,'b':4}\n",
    "print(divid(**z))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  `map` 方法生成序列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其用法为:\n",
    "    \n",
    "    map(aFun, aSeq)\n",
    "\n",
    "将函数 `aFun` 应用到序列 `aSeq` 上的每一个元素上,返回一个列表,不管这个序列原来是什么类型。\n",
    "\n",
    "事实上,根据函数参数的多少,`map` 可以接受多组序列,将其对应的元素作为参数传入函数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divid(a, b):\n",
    "    \"\"\"\n",
    "    除法\n",
    "    :param a: number 被除数\n",
    "    :param b: number 除数\n",
    "    :return: 商和余数\n",
    "    \"\"\"\n",
    "    quotient = a // b\n",
    "    remainder = a % b\n",
    "    return quotient, remainder\n",
    "\n",
    "a = (10, 6, 7)\n",
    "b = [2, 5, 3]\n",
    "print(list(map(divid,a,b)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.3 模块和包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 模块\n",
    "\n",
    "**Python** 会将所有 `.py` 结尾的文件认定为 **Python** 代码文件,考虑下面的脚本 `ex1.py` :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile ex1.py\n",
    "\n",
    "PI = 3.1416\n",
    "\n",
    "def sum(lst):\n",
    "    \"\"\"\n",
    "    计算 lst 序列所有元素的和\n",
    "    :param lst: 序列 e.g. [1,2,3]\n",
    "    :return: lst 序列所有元素的总和\n",
    "    \"\"\"\n",
    "    \n",
    "    # 获取 lst序列第一个元素\n",
    "    tot = lst[0]\n",
    "    \n",
    "    # 循环遍历 lst 序列剩余元素\n",
    "    for value in lst[1:]:\n",
    "        tot = tot + value\n",
    "    return tot\n",
    "\n",
    "w = [0, 1, 2, 3]\n",
    "print(sum(w), PI)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以执行它:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run ex1.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个脚本可以当作一个模块,可以使用`import`关键词加载并执行它(这里要求`ex1.py`在当前工作目录):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ex1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在导入时,**Python** 会执行一遍模块中的所有内容。\n",
    "\n",
    "`ex1.py` 中所有的变量都被载入了当前环境中,不过要使用\n",
    "\n",
    "    ex1.变量名\n",
    "\n",
    "的方法来查看或者修改这些变量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(ex1.PI)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ex1.PI = 3.141592653\n",
    "print(ex1.PI)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还可以用\n",
    "\n",
    "    ex1.函数名\n",
    "\n",
    "调用模块里面的函数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(ex1.sum([2, 3, 4]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了提高效率,**Python** 只会载入模块一次,已经载入的模块再次载入时,**Python** 并不会真正执行载入操作,哪怕模块的内容已经改变。\n",
    "\n",
    "例如,这里重新导入 `ex1` 时,并不会执行 `ex1.py` 中的 `print` 语句:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "需要重新导入模块时,可以使用 `reload` 强制重新载入它,例如:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from imp import reload\n",
    "reload(ex1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除之前生成的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('ex1.py')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `__name__` 属性\n",
    "\n",
    "有时候我们想将一个 `.py` 文件既当作脚本,又能当作模块用,这个时候可以使用 `__name__` 这个属性。\n",
    "\n",
    "只有当文件被当作脚本执行的时候, `__name__`的值才会是 `'__main__'`,所以我们可以:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile ex2.py\n",
    "\n",
    "PI = 3.1416\n",
    "\n",
    "def sum(lst):\n",
    "    \"\"\" Sum the values in a list\n",
    "    \"\"\"\n",
    "    tot = 0\n",
    "    for value in lst:\n",
    "        tot = tot + value\n",
    "    return tot\n",
    "\n",
    "def add(x, y):\n",
    "    \" Add two values.\"\n",
    "    a = x + y\n",
    "    return a\n",
    "\n",
    "def test():\n",
    "    w = [0,1,2,3]\n",
    "    assert(sum(w) == 6)\n",
    "    print('test passed.')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    test()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run ex2.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当作模块导入, `test()` 不会执行:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是可以使用其中的变量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ex2.PI\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "引入模块时可以为它设置一个别名让使用更方便:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex2 as e2\n",
    "e2.PI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 其它导入方法\n",
    "\n",
    "可以从模块中导入变量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ex2 import add, PI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `from` 后,可以直接使用 `add` , `PI`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "add(2, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "或者使用 `*` 导入所有变量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ex2 import *\n",
    "add(3, 4.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这种导入方法不是很提倡,因为如果你不确定导入的都有哪些,可能覆盖一些已有的函数。\n",
    "\n",
    "删除文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('ex2.py')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 包\n",
    "\n",
    "假设我们有这样的一个文件夹:\n",
    "\n",
    "foo/\n",
    "- `__init__.py` \n",
    "- `bar.py` (defines func)\n",
    "- `baz.py` (defines zap)\n",
    "\n",
    "这意味着 `foo` 是一个包,我们可以这样导入其中的内容:\n",
    "\n",
    "```python  \n",
    "\n",
    "from foo.bar import func\n",
    "from foo.baz import zap\n",
    "\n",
    "```\n",
    "\n",
    "`bar` 和 `baz` 都是 `foo` 文件夹下的 `.py` 文件。\n",
    "\n",
    "导入包要求:\n",
    "- 文件夹 `foo` 在 **Python** 的搜索路径中\n",
    "- `__init__.py` 表示 `foo` 是一个包,它可以是个空文件。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.4 异常\n",
    "\n",
    "写代码的时候,出现错误不可避免,即使代码语法没有问题,也可能遇到其它问题。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "看下面这段代码:\n",
    "\n",
    "```python \n",
    "\n",
    "import math\n",
    "\n",
    "while True:\n",
    "    text = input('> ')\n",
    "    if text[0] == 'q':\n",
    "        break\n",
    "    x = float(text)\n",
    "    y = math.log10(x)\n",
    "    print(\"log10({0}) = {1}\".format(x, y))\n",
    "```\n",
    "\n",
    "这段代码接收命令行的输入,当输入为数字时,计算它的对数并输出,直到输入值为 `q` 为止。\n",
    "\n",
    "乍看没什么问题,然而当我们输入 0 或者负数时:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    text = input('> ')\n",
    "    if text[0] == 'q':\n",
    "        break\n",
    "    x = float(text)\n",
    "    y = math.log10(x)\n",
    "    print(\"log10({0}) = {1}\".format(x, y))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`log10` 函数会报错,因为不能接受非正值。\n",
    "\n",
    "一旦报错,程序就会停止执行。如果不希望程序停止执行,并且想要捕捉异常,那么我们可以按照 `try/except` 语句。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "\n",
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = math.log10(x)\n",
    "        print(\"log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一旦 `try` 块中的内容出现了异常,那么 `try` 块后面的内容会被忽略,**Python** 会寻找 `except` 里面有没有对应的内容,如果找到,就执行对应的块,没有则抛出这个异常。\n",
    "\n",
    "在上面的例子中,`try` 抛出的是 `ValueError`,`except` 中有对应的内容,所以这个异常被 `except` 捕捉到,程序可以继续执行:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = math.log10(x)\n",
    "        print(\"log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 捕捉不同的错误类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "``` python\n",
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n",
    "```\n",
    "\n",
    "假设我们将这里的 `y` 更改为 `1 / math.log10(x)`,此时输入 `1`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为我们的 `except` 里面并没有 `ZeroDivisionError`,所以会抛出这个异常,我们可以通过两种方式解决这个问题。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 捕捉所有异常\n",
    "\n",
    "将`except` 的值改成 `Exception` 类,来捕获所有的异常。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"1 / log10({0}) = {1}\".format(x, y))\n",
    "    except Exception:\n",
    "        print(\"invalid value\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 指定特定异常\n",
    "\n",
    "这里,我们把 `ZeroDivisionError` 加入 `except` 。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"1 / log10({0}) = {1}\".format(x, y))\n",
    "    except (ValueError, ZeroDivisionError):\n",
    "        print(\"invalid value\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "或者另加处理:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"1 / log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n",
    "    except ZeroDivisionError:\n",
    "        print(\"the value must not be 1\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上,我们还可以将这两种方式结合起来,用 `Exception` 来捕捉其他的错误:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"1 / log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError:\n",
    "        print(\"the value must be greater than 0\")\n",
    "    except ZeroDivisionError:\n",
    "        print(\"the value must not be 1\")\n",
    "    except Exception:\n",
    "        print(\"unexpected error\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 得到异常的具体信息\n",
    "\n",
    "在上面的例子中,当我们输入不能转换为浮点数的字符串时,它输出的是 `the value must be greater than 0`,这并没有反映出实际情况。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了得到异常的具体信息,我们将这个 `ValueError` 具体化:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        text = input('> ')\n",
    "        if text[0] == 'q':\n",
    "            break\n",
    "        x = float(text)\n",
    "        y = 1 / math.log10(x)\n",
    "        print(\"1 / log10({0}) = {1}\".format(x, y))\n",
    "    except ValueError as exc:\n",
    "        if exc.message == \"math domain error\":\n",
    "            print(\"the value must be greater than 0\")\n",
    "        else:\n",
    "            print(\"could not convert '%s' to float\" % text)\n",
    "    except ZeroDivisionError:\n",
    "        print(\"the value must not be 1\")\n",
    "    except Exception as exc:\n",
    "        print(\"unexpected error:\", exc.message)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同时,我们也将捕获的其他异常的信息显示出来。\n",
    "\n",
    "这里,`exc.message` 显示的内容是异常对应的说明,例如\n",
    "\n",
    "    ValueError: could not convert string to float: a\n",
    "\n",
    "对应的 `message` 是 \n",
    "\n",
    "    could not convert string to float: a\n",
    "\n",
    "当我们使用 `except Exception` 时,会捕获所有的 `Exception` 和它派生出来的子类,但不是所有的异常都是从 `Exception` 类派生出来的,可能会出现一些不能捕获的情况,因此,更加一般的做法是使用这样的形式:\n",
    "\n",
    "```python\n",
    "try:\n",
    "    pass\n",
    "except:\n",
    "    pass\n",
    "```\n",
    "\n",
    "这样不指定异常的类型会捕获所有的异常,但是这样的形式并不推荐。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### else\n",
    "\n",
    "`try/except` 块有一个可选的关键词 `else`。\n",
    "\n",
    "如果使用这个子句,那么必须放在所有的 except 子句之后。else 子句将在 try 子句没有发生任何异常的时候执行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1)\n",
    "except:\n",
    "    pass\n",
    "else:\n",
    "    print('else was called.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "出现异常,else 不会执行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1/0)\n",
    "except ZeroDivisionError:\n",
    "    print('divide by 0.')\n",
    "else:\n",
    "    print('else was called.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### finally\n",
    "\n",
    "`try/except` 块还有一个可选的关键词 `finally`。\n",
    "\n",
    "不管 `try` 块有没有异常, `finally` 块的内容总是会被执行,而且会在抛出异常前执行,因此可以用来作为安全保证,比如确保打开的文件被关闭。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1)\n",
    "finally:\n",
    "    print('finally was called.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在抛出异常前执行:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1 / 0)\n",
    "finally:\n",
    "    print('finally was called.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果异常被捕获了,在最后执行:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1 / 0)\n",
    "except ZeroDivisionError:\n",
    "    print('divide by 0.')\n",
    "finally:\n",
    "    print('finally was called.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "异常的处理流程可参考下图:\n",
    "\n",
    "<img src=\"https://www.runoob.com/wp-content/uploads/2019/07/try_except_else_finally.png\" width=600px/>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.5 警告\n",
    "\n",
    "出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:\n",
    "\n",
    "首先导入警告模块:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在需要的地方,我们使用 `warnings` 中的 `warn` 函数:\n",
    "\n",
    "    warn(msg, WarningType = UserWarning)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def month_warning(m):\n",
    "    if not 1<= m <= 12:\n",
    "        msg = \"month (%d) is not between 1 and 12\" % m\n",
    "        warnings.warn(msg, RuntimeWarning)\n",
    "\n",
    "month_warning(13)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有时候我们想要忽略特定类型的警告,可以使用 `warnings` 的 `filterwarnings` 函数:\n",
    "\n",
    "    filterwarnings(action, category)\n",
    "\n",
    "将 `action` 设置为 `'ignore'` 便可以忽略特定类型的警告:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)\n",
    "\n",
    "month_warning(13)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.6 文件读写\n",
    "\n",
    "写入测试文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile test.txt\n",
    "this is a test file.\n",
    "hello world!\n",
    "python is good!\n",
    "today is a good day.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 读文件\n",
    "\n",
    "使用 `open` 函数来读文件,使用文件名的字符串作为输入参数:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认以读的方式打开文件,如果文件不存在会报错:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test1.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用 `read` 方法来读入文件中的所有内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = f.read()\n",
    "print(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以按照行读入内容,`readlines` 方法返回一个列表,每个元素代表文件中每一行的内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test.txt')\n",
    "lines = f.readlines()\n",
    "print(lines)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用完文件之后,需要将文件关闭。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上,我们可以将 `f` 放在一个循环中,得到它每一行的内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test.txt')\n",
    "for line in f:\n",
    "    print(line)\n",
    "f.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除刚才创建的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('test.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 写文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们使用 `open` 函数的写入模式来写文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('myfile.txt', 'w')\n",
    "f.write('hello world!')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `w` 模式时,如果文件不存在会被创建,我们可以查看是否真的写入成功:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(open('myfile.txt').read())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果文件已经存在, `w` 模式会覆盖之前写的所有内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('myfile.txt', 'w')\n",
    "f.write('another hello world!')\n",
    "f.close()\n",
    "print(open('myfile.txt').read())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "除了写入模式,还有追加模式 `a` ,追加模式不会覆盖之前已经写入的内容,而是在之后继续写入:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('myfile.txt', 'a')\n",
    "f.write('... and more')\n",
    "f.close()\n",
    "print(open('myfile.txt').read())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "写入结束之后一定要将文件关闭,否则可能出现内容没有完全写入文件中的情况。\n",
    "\n",
    "还可以使用读写模式 `w+`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('myfile.txt', 'w+')\n",
    "f.write('hello world!')\n",
    "f.seek(6)\n",
    "print(f.read())\n",
    "f.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里 `f.seek(6)` 移动到文件的第6个字符处,然后 `f.read()` 读出剩下的内容。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除刚才创建的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('myfile.txt')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 关闭文件\n",
    "\n",
    "在 **Python** 中,如果一个打开的文件不再被其他变量引用时,它会自动关闭这个文件。\n",
    "\n",
    "所以正常情况下,如果一个文件正常被关闭了,忘记调用文件的 `close` 方法不会有什么问题。\n",
    "\n",
    "关闭文件可以保证内容已经被写入文件,而不关闭可能会出现意想不到的结果:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('newfile.txt','w')\n",
    "f.write('hello world')\n",
    "g = open('newfile.txt', 'r')\n",
    "print(repr(g.read()))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "虽然这里写了内容,但是在关闭之前,这个内容并没有被写入磁盘。\n",
    "\n",
    "使用循环写入的内容也并不完整:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('newfile.txt','w')\n",
    "for i in range(30):\n",
    "    f.write('hello world: ' + str(i) + '\\n')\n",
    "\n",
    "g = open('newfile.txt', 'r')\n",
    "print(g.read())\n",
    "f.close()\n",
    "g.close()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('newfile.txt')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "出现异常时候的读写:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('newfile.txt','w')\n",
    "for i in range(30):\n",
    "    x = 1.0 / (i - 10)\n",
    "    f.write('hello world: ' + str(i) + '\\n')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "查看已有内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = open('newfile.txt', 'r')\n",
    "print(g.read())\n",
    "f.close()\n",
    "g.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到,出现异常的时候,磁盘的写入并没有完成,为此我们可以使用 `try/except/finally` 块来关闭文件,这里 `finally` 确保关闭文件,所有的写入已经完成。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('newfile.txt','w')\n",
    "try:\n",
    "    for i in range(30):\n",
    "        x = 1.0 / (i - 10)\n",
    "        f.write('hello world: ' + str(i) + '\\n')\n",
    "except Exception:\n",
    "    print(\"something bad happened\")\n",
    "finally:\n",
    "    f.close()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = open('newfile.txt', 'r')\n",
    "print(g.read())\n",
    "g.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### with 方法\n",
    "\n",
    "事实上,**Python** 提供了更安全的方法,当 `with` 块的内容结束后,**Python** 会自动调用它的`close` 方法,确保读写的安全:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('newfile.txt','w') as f:\n",
    "    for i in range(30):\n",
    "        x = 1.0 / (i - 10)\n",
    "        f.write('hello world: ' + str(i) + '\\n')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "与 `try/exception/finally` 效果相同,但更简单。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = open('newfile.txt', 'r')\n",
    "print(g.read())\n",
    "g.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所以,写文件时候要确保文件被正确关闭。\n",
    "\n",
    "删除刚才创建的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('newfile.txt')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2.7 CSV 文件和 csv 模块\n",
    "\n",
    "标准库中有自带的 `csv` 模块处理 `csv` 格式的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 读 csv 文件\n",
    "\n",
    "假设我们有这样的一个文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%file data.csv\n",
    "\"alpha 1\",  100, -1.443\n",
    "\"beat  3\",   12, -0.0934\n",
    "\"gamma 3a\", 192, -0.6621\n",
    "\"delta 2a\",  15, -4.515\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "打开这个文件,并产生一个文件 reader:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打开 data.csv 文件\n",
    "fp = open(\"data.csv\")\n",
    "\n",
    "# 读取文件“”\n",
    "r = csv.reader(fp)\n",
    "\n",
    "# 可以按行迭代数据\n",
    "for row in r:\n",
    "    print(row)\n",
    "\n",
    "# 关闭文件\n",
    "fp.close()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认数据内容都被当作字符串处理,不过可以自己进行处理:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = []\n",
    "\n",
    "with open('data.csv') as fp:\n",
    "    r = csv.reader(fp)\n",
    "    for row in r:\n",
    "        data.append([row[0], int(row[1]), float(row[2])])\n",
    "\n",
    "data\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "清除刚刚创建的文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('data.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 写 csv 文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用 `csv.writer` 写入文件,不过相应地,传入的应该是以写方式打开的文件,不过一般要用 `'wb'` 即二进制写入方式,防止出现换行不正确的问题:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = [('one', 1, 1.5), ('two', 2, 8.0)]\n",
    "with open('out.csv', 'w') as fp:\n",
    "    w = csv.writer(fp)\n",
    "    w.writerows(data)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "显示结果:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! cat 'out.csv'"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}