-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbyte_of_python笔记.html
1383 lines (1308 loc) · 80.7 KB
/
byte_of_python笔记.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
<!DOCTYPE html>
<html lang="zh-Hant"
>
<head>
<title>A byte of Python 笔记 - mx's blog</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#6b5594">
<meta name="msapplication-navbutton-color" content="#6b5594">
<meta name="apple-mobile-web-app-status-bar-style" content="#6b5594">
<link rel="manifest" href="/manifest.json">
<link rel="canonical" href="https://x-wei.github.io/byte_of_python笔记.html">
<meta name="author" content="mx" />
<meta name="keywords" content="python" />
<meta name="description" content="据说这本书是最好的入门读物, 况且只有100来页 (减掉前面后面那些扯淡的 不到100页...) 那就用这本书过一下py的基本知识点吧! 看完以后收获不少, 把py涉及的很大一部分都讲到了. 这本书已经是够压缩的了, 不过我还是边看边自己再压缩了一遍(写在zim笔记里). 我看的是1.20版本, 2004年的, 因为这个版本针对的是py2.x, 作者主页上现在的版本针对的是py3. 另外感觉没必要看中文翻译版, 因为这里用的英语比较简单, 而且有的时候中文翻译反而不如原文表达的恰当. preface+ch1+ch2 扯淡... ch3. First Steps There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file. Anything to the ..." />
<meta property="og:site_name" content="mx's blog" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="A byte of Python 笔记"/>
<meta property="og:url" content="https://x-wei.github.io/byte_of_python笔记.html"/>
<meta property="og:description" content="据说这本书是最好的入门读物, 况且只有100来页 (减掉前面后面那些扯淡的 不到100页...) 那就用这本书过一下py的基本知识点吧! 看完以后收获不少, 把py涉及的很大一部分都讲到了. 这本书已经是够压缩的了, 不过我还是边看边自己再压缩了一遍(写在zim笔记里). 我看的是1.20版本, 2004年的, 因为这个版本针对的是py2.x, 作者主页上现在的版本针对的是py3. 另外感觉没必要看中文翻译版, 因为这里用的英语比较简单, 而且有的时候中文翻译反而不如原文表达的恰当. preface+ch1+ch2 扯淡... ch3. First Steps There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file. Anything to the ..."/>
<meta property="article:published_time" content="2014-04-10" />
<meta property="article:section" content="tech" />
<meta property="article:tag" content="python" />
<meta property="article:author" content="mx" />
<meta property="og:image"
content="https://x-wei.github.io/byte_of_python笔记.png"/>
<!-- Bootstrap -->
<link href="https://x-wei.github.io/theme/css/bootstrap.min.css" rel="stylesheet">
<link href="https://x-wei.github.io/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="https://x-wei.github.io/theme/css/pygments/manni.css" rel="stylesheet">
<link href="https://x-wei.github.io/theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<link rel="stylesheet" href="https://x-wei.github.io/theme/css/style.css" type="text/css"/>
<link href="https://x-wei.github.io/feeds/atom.xml" type="application/atom+xml" rel="alternate"
title="mx's blog ATOM Feed"/>
<link href="https://x-wei.github.io/theme/css/material.min.css" rel="stylesheet">
<link href="https://x-wei.github.io/theme/css/ripples.css" rel="stylesheet">
</head>
<body>
<div style="display:none" id="title">A byte of Python 笔记 - mx's blog</div>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">切换导航</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://x-wei.github.io/" class="navbar-brand">
mx's blog </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="dropdown hidden-md hidden-lg hidden-xl">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="fa fa-user"></i><span class="caret"></span>
</a>
<ul class="dropdown-menu">
</ul>
</li>
<ul class="nav navbar-nav hidden-xs hidden-sm">
</ul>
</ul>
<ul class="nav navbar-nav hidden-md hidden-lg hidden-xl">
<li class="dropdown hidden-md hidden-lg hidden-xl">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="fa fa-folder-o"></i><span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li >
<a href="https://x-wei.github.io/category/misc.html"><i class="fa fa-folder-o"></i> Misc</a>
</li>
<li >
<a href="https://x-wei.github.io/category/music.html"><i class="fa fa-folder-o"></i> Music</a>
</li>
<li >
<a href="https://x-wei.github.io/category/notes.html"><i class="fa fa-folder-o"></i> Notes</a>
</li>
<li >
<a href="https://x-wei.github.io/category/soft.html"><i class="fa fa-folder-o"></i> Soft</a>
</li>
<li class="active">
<a href="https://x-wei.github.io/category/tech.html"><i class="fa fa-folder-o"></i> Tech</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav hidden-xs hidden-sm">
<li >
<a href="https://x-wei.github.io/category/misc.html"><i class="fa fa-folder-o"></i> Misc</a>
</li>
<li >
<a href="https://x-wei.github.io/category/music.html"><i class="fa fa-folder-o"></i> Music</a>
</li>
<li >
<a href="https://x-wei.github.io/category/notes.html"><i class="fa fa-folder-o"></i> Notes</a>
</li>
<li >
<a href="https://x-wei.github.io/category/soft.html"><i class="fa fa-folder-o"></i> Soft</a>
</li>
<li class="active">
<a href="https://x-wei.github.io/category/tech.html"><i class="fa fa-folder-o"></i> Tech</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right hidden-sm hidden-md hidden-lg hidden-xl">
<li class="dropdown hidden-md hidden-lg hidden-xl">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="fa fa-search"></i><span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><span>
<form class="navbar-search" action="/search.html">
<input type="text" class="search-query form-control col-lg-16" placeholder="Search" name="q" id="tipue_search_input" required>
</form></span>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-right navbar-form hidden-xs">
<li><span>
<form class="navbar-search" action="/search.html">
<input type="text" class="search-query form-control col-lg-16" placeholder="查找" name="q" id="tipue_search_input" required>
</form></span>
</li>
</ul>
<ul class="nav navbar-nav navbar-right hidden-xs">
<li><a href="https://x-wei.github.io/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archive</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container" style="min-height: 100%;height: auto !important;height: 100%;">
<div class="row" style="padding-bottom:80px;padding-top:80px;">
<div class="col-xl-21 col-lg-20 col-md-18">
<div id="loading-block">
<ol class="breadcrumb">
<li><a href="https://x-wei.github.io/" title="mx's blog"><i class="fa fa-home fa-lg"></i></a></li>
<li><a href="https://x-wei.github.io/category/tech.html" title="tech">tech</a></li>
<li class="active">A byte of Python 笔记</li>
</ol>
<section id="content" class="article-content">
<article>
<header class="page-header jumbotron jumbotron-primary panel-primary" id="article-header">
<div class="panel-heading">
<h1>
A byte of Python 笔记
<a href="https://x-wei.github.io/byte_of_python笔记.html"
rel="bookmark"
class="btn btn-primary btn-lg"
title="到 A byte of Python 笔记 的永久链接">
<i class="mdi-action-launch"></i>
</a>
</h1>
</div>
<div class="panel-body">
<div class="post-info">
<span class="published">
<time datetime="2014-04-10T00:00:00+02:00"><i class="fa fa-calendar"></i> Thu, 10 Apr 2014</time>
</span>
<span class="btn-group">
<a href="https://x-wei.github.io/tag/python.html" class="btn btn-primary btn-xs"><i class="fa fa-tag"></i> python</a>
</span>
</div><!-- /.post-info --> </div>
</header>
<div class="entry-content jumbotron" id="article-content">
<div class="panel panel-default">
<div class="panel-heading">
目录
</div>
<div class="panel-boy">
<div id="toc"><ul><li><a class="toc-href" href="#prefacech1ch2" title="preface+ch1+ch2">preface+ch1+ch2</a></li><li><a class="toc-href" href="#ch3-first-steps" title="ch3. First Steps">ch3. First Steps</a></li><li><a class="toc-href" href="#ch4-the-basics" title="ch4. The Basics">ch4. The Basics</a><ul><li><a class="toc-href" href="#literal-constants" title="Literal Constants">Literal Constants</a></li><li><a class="toc-href" href="#variables" title="Variables">Variables</a></li><li><a class="toc-href" href="#indentation" title="Indentation">Indentation</a></li></ul></li><li><a class="toc-href" href="#ch5-operators-and-expressions_1" title="ch5. Operators and Expressions">ch5. Operators and Expressions</a></li><li><a class="toc-href" href="#ch6-control-flow" title="ch6. Control Flow">ch6. Control Flow</a></li><li><a class="toc-href" href="#ch7-functions" title="ch7. Functions">ch7. Functions</a><ul><li><a class="toc-href" href="#scope" title="scope">scope</a></li><li><a class="toc-href" href="#default-argument-values" title="Default Argument Values">Default Argument Values</a></li><li><a class="toc-href" href="#docstrings" title="DocStrings">DocStrings</a></li></ul></li><li><a class="toc-href" href="#ch8-modules_1" title="ch8. Modules">ch8. Modules</a><ul><li><a class="toc-href" href="#ex-sys-module" title="ex. sys module">ex. sys module</a></li><li><a class="toc-href" href="#dir-function" title="dir() function">dir() function</a></li></ul></li><li><a class="toc-href" href="#ch9-data-structures_1" title="ch9. Data Structures">ch9. Data Structures</a><ul><li><a class="toc-href" href="#list-abc" title="List [a,b,c]">List [a,b,c]</a></li><li><a class="toc-href" href="#tuple-abc" title="Tuple (a,b,c)">Tuple (a,b,c)</a></li><li><a class="toc-href" href="#dictionary" title="Dictionary">Dictionary</a></li><li><a class="toc-href" href="#sequences" title="Sequences">Sequences</a></li><li><a class="toc-href" href="#references" title="References">References</a></li><li><a class="toc-href" href="#string" title="String">String</a></li></ul></li><li><a class="toc-href" href="#ch10-problem-solving-writing-a-python-script_1" title="ch10. Problem Solving - Writing a Python Script">ch10. Problem Solving - Writing a Python Script</a><ul><li><a class="toc-href" href="#1st-version" title="1st version">1st version</a></li><li><a class="toc-href" href="#2nd-version" title="2nd version">2nd version</a></li><li><a class="toc-href" href="#3rd-version" title="3rd version">3rd version</a></li><li><a class="toc-href" href="#more-refinements" title="More Refinements">More Refinements</a></li></ul></li><li><a class="toc-href" href="#ch11-object-oriented-programming_1" title="ch11. Object-Oriented Programming">ch11. Object-Oriented Programming</a><ul><li><a class="toc-href" href="#fields-methods" title="fields, methods">fields, methods</a></li><li><a class="toc-href" href="#self" title="self">self</a></li><li><a class="toc-href" href="#the-init-method" title="The init method">The init method</a></li><li><a class="toc-href" href="#inheritance" title="Inheritance">Inheritance</a></li></ul></li><li><a class="toc-href" href="#ch12-inputoutput_1" title="ch12. Input/Output">ch12. Input/Output</a><ul><li><a class="toc-href" href="#files" title="Files">Files</a></li><li><a class="toc-href" href="#pickle" title="Pickle">Pickle</a></li></ul></li><li><a class="toc-href" href="#ch13-exceptions_1" title="ch13. Exceptions">ch13. Exceptions</a><ul><li><a class="toc-href" href="#tryexcept" title="Try..Except">Try..Except</a></li><li><a class="toc-href" href="#raising-exceptions" title="Raising Exceptions">Raising Exceptions</a></li><li><a class="toc-href" href="#tryfinally" title="Try..Finally">Try..Finally</a></li></ul></li><li><a class="toc-href" href="#ch14-the-python-standard-library_1" title="ch14. The Python Standard Library">ch14. The Python Standard Library</a><ul><li><a class="toc-href" href="#sys-module" title="sys module">sys module</a></li><li><a class="toc-href" href="#os-module" title="os module">os module</a></li></ul></li><li><a class="toc-href" href="#ch15-more-python_1" title="ch15. More Python">ch15. More Python</a><ul><li><a class="toc-href" href="#special-methods" title="Special Methods">Special Methods</a></li><li><a class="toc-href" href="#list-comprehension" title="List Comprehension">List Comprehension</a></li><li><a class="toc-href" href="#receiving-tuples-and-lists-in-functions" title="Receiving Tuples and Lists in Functions">Receiving Tuples and Lists in Functions</a></li><li><a class="toc-href" href="#lambda-forms" title="Lambda Forms">Lambda Forms</a></li><li><a class="toc-href" href="#the-exec-and-eval-statements" title="The exec and eval statements">The exec and eval statements</a></li><li><a class="toc-href" href="#the-assert-statement" title="The assert statement">The assert statement</a></li><li><a class="toc-href" href="#the-repr-function-or-backticks" title="The repr function or Backticks(`)">The repr function or Backticks(`)</a></li></ul></li></ul></div>
</div>
</div>
<p>据说这本书是最好的入门读物, 况且只有100来页 (减掉前面后面那些扯淡的 不到100页...)</p>
<p>那就用这本书过一下py的基本知识点吧! 看完以后收获不少, 把py涉及的很大一部分都讲到了. 这本书已经是够压缩的了, 不过我还是边看边自己再压缩了一遍(写在zim笔记里). </p>
<p>我看的是1.20版本, 2004年的, 因为这个版本针对的是py2.x, 作者主页上现在的版本针对的是py3. 另外感觉没必要看中文翻译版, 因为这里用的英语比较简单, 而且有的时候中文翻译反而不如原文表达的恰当.</p>
<h1 id="prefacech1ch2">preface+ch1+ch2</h1>
<p>扯淡...</p>
<h1 id="ch3-first-steps">ch3. First Steps</h1>
<ul>
<li>
<p>There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file.</p>
</li>
<li>
<p>Anything to the right of the # symbol is a comment.</p>
</li>
<li>
<p><strong>the shebang line</strong> - whenever the first two characters of the source file are <code>#!</code> followed by the location of a program, this tells your Linux/Unix system that this program should be run with this interpreter when you execute the program.</p>
</li>
</ul>
<p>(Note that you can always run the program on any platform by specifying the interpreter directly on the command line such as the command python helloworld.py .)</p>
<ul>
<li>use the built-in help functionality.</li>
</ul>
<p>or example, run <code>help(str)</code> - this displays the help for the str class which is used to store all text (strings) that you use in your program.</p>
<h1 id="ch4-the-basics">ch4. The Basics</h1>
<h2 id="literal-constants">Literal Constants</h2>
<p>It is called a literal because it is literal - you use its value literally. ex. number 2, or string "hello".</p>
<p><strong>number</strong></p>
<ul>
<li>Numbers in Python are of four types - integers, long integers, floating point and complex numbers.</li>
</ul>
<p>-Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4. The E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10-4.
-Examples of complex numbers are (-5+4j) and (2.3 - 4.6j)</p>
<p><strong>string</strong></p>
<ul>
<li>
<p>string可以用Single/Double/Triple Quotes括起来</p>
</li>
<li>
<p><em>escape sequence</em>: \', \n, \t, 以及在行末作为续行符号</p>
</li>
<li>
<p><strong>raw string</strong>: to specify some strings where no special processing such as escape sequences are handled, then what you need is to specify a raw string by prefixing r or R to the string. </p>
</li>
</ul>
<p>ex. <code>r"Newlines are indicated by \n"</code></p>
<ul>
<li>unicode text: prefix u or U. For example, <code>u"This is a Unicode string."</code></li>
</ul>
<p>Remember to use Unicode strings when you are dealing with text files, especially when you know that the file will contain text written in languages other than English.</p>
<ul>
<li>
<p>Strings are immutable: once you have created a string, you cannot change it.</p>
</li>
<li>
<p>String literal concatenation: If you place two string literals side by side, they are automatically concatenated by Python. For example, '<code>What\'s' 'your name?</code>' is automatically converted in to <code>"What's your name?".</code></p>
</li>
<li>
<p>Note for Regular Expression Users: Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. </p>
</li>
</ul>
<h2 id="variables">Variables</h2>
<p>顾名思义就是可以可以变的量...
Unlike literal constants, you need some method of accessing these variables <em>and hence you give them names</em>.</p>
<ul>
<li>Identifier(标示符)</li>
</ul>
<p><strong>Identifiers</strong> are names given to identify something.
The first character of the identifier must be a letter of the alphabet (upper or lowercase) <em>or an underscore ('_')</em>.</p>
<ul>
<li>Objects</li>
</ul>
<p>Python refers to anything used in a program as an object.
Python is <strong>strongly object-oriented</strong> in the sense that everything is an object <em>including numbers, strings and even functions</em>.</p>
<ul>
<li>
<p>Variables are used by just assigning them a value. No declaration or data type definition is needed/used.</p>
</li>
<li>
<p>Logical and Physical Lines: Implicitly, Python encourages the use of a single statement per line which makes code more readable. If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;)</p>
</li>
<li>
<p>explicit line joining: ex. 续行符\;</p>
</li>
</ul>
<p>implicit line joining: ex. 括号...</p>
<h2 id="indentation">Indentation</h2>
<ul>
<li>
<p>Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.</p>
</li>
<li>
<p>This means that statements which go together must have the same indentation. Each such set of state- ments is called a <em>block</em>. </p>
</li>
<li>
<p>Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. </p>
</li>
</ul>
<h1 id="ch5-operators-and-expressions_1">ch5. Operators and Expressions</h1>
<ul>
<li><strong>expressions</strong></li>
</ul>
<p>An expression can be broken down into <em>operators</em> and <em>operands</em>. </p>
<ul>
<li>一些oprators: </li>
</ul>
<p><code>**, //, <<, >>, &, |, ^, ~, not, and, or</code></p>
<ul>
<li>
<p>Operator Precedence: 优先级的一个表...</p>
</li>
<li>
<p>Associativity: </p>
</li>
</ul>
<p>Operators are usually associated from left to right i.e. operators with same precedence are evaluated in a left to right manner. For example, <code>2 + 3 + 4</code> is evaluated as <code>(2 + 3) + 4</code>. Some operators like assignment operators have right to left associativity i.e. <code>a = b = c</code> is treated as <code>a = (b = c)</code>.</p>
<h1 id="ch6-control-flow">ch6. Control Flow</h1>
<ul>
<li>if</li>
</ul>
<p><code>if-elif-else</code> statement: This makes the program easier and reduces the amount of indentation required. </p>
<ul>
<li>
<p>There is <em>no switch statement in Python:</em> You can use an if..elif..else statement to do the same thing (and in some cases, use a dictionary to do it quickly)</p>
</li>
<li>
<p>while</p>
</li>
</ul>
<p>Remember that you can have <em>an <strong><em>else</em></strong> clause for the while loop</em>.</p>
<ul>
<li>for</li>
</ul>
<p>-The <code>for..in</code> statement is another looping statement which <em>iterates</em> over a sequence of objects i.e. go
through each item in a sequence, a <em>sequence</em> is just an ordered collection of items.
-optional <strong>else</strong> part also.</p>
<ul>
<li>
<p>break</p>
</li>
<li>
<p>to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has been completely iterated over.
-An important note is that if you break out of a for or while loop, <em>any corresponding loop else block is <strong><em>not</em></strong> executed.</em></p>
</li>
<li>
<p>continue</p>
</li>
</ul>
<p>used to tell Python to skip the rest of the statements in the current loop block and to continue to the <em>next iteration</em> of the loop.</p>
<h1 id="ch7-functions">ch7. Functions</h1>
<p>Functions are reusable pieces of programs. </p>
<ul>
<li>
<p>def func_name()</p>
</li>
<li>
<p>parameters:</p>
</li>
</ul>
<p>Note the terminology used - the names given in the function definition are called <em>parameters(行参)</em> whereas the values you supply in the function call are called <em>arguments(实参)</em>.</p>
<h2 id="scope">scope</h2>
<ul>
<li>local variables:</li>
</ul>
<p>All variables have the <strong>scope</strong> of the block they are declared in starting from the point of definition of the name.</p>
<ul>
<li><strong>global variables</strong>:</li>
</ul>
<p>If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the <code>global</code> statement. </p>
<h2 id="default-argument-values">Default Argument Values</h2>
<p>Default Argument Values默认参数</p>
<ul>
<li>
<p>You can specify default argument values for parameters by following the parameter name in the function definition with the assignment operator (=) followed by the default value.</p>
</li>
<li>
<p>Note that the default argument value should be <em>immutable.</em></p>
</li>
<li>
<p>you cannot have a parameter with a default argument value <em>before</em> a parameter without a default argument value in the order of parameters declared in the function parameter list.</p>
</li>
</ul>
<p>This is because the values are <em>assigned to the parameters by position</em>. For example, <code>def func(a, b=5)</code> is valid, but <code>def func(a=5, b)</code> is not valid.</p>
<ul>
<li>Keyword Arguments</li>
</ul>
<p>If you have some functions with many parameters and you want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments - we <em>use the name (keyword) instead of the position</em> to specify the arguments to the function.</p>
<ul>
<li>return</li>
</ul>
<p>used to <em>return</em> from a function i.e. break out of the function. We can optionally return a value from the function as well.</p>
<ul>
<li>return None</li>
</ul>
<p>-a return statement without a value is equivalent to <code>return None</code>. None is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of None.
-Every function implicitly contains a return None statement at the end unless you have written your own return statement.</p>
<ul>
<li>pass</li>
</ul>
<p>the <code>pass</code> statement is used in Python to indicate an empty block of statements.</p>
<h2 id="docstrings">DocStrings</h2>
<ul>
<li><em>A string on the first logical line of a function</em> is the <strong>docstring</strong> for that function (also apply to modules and classes). </li>
</ul>
<p><code>func.__doc__</code></p>
<ul>
<li>The convention: a multi-line string where the first line starts with a capital letter and ends with a dot. Then the second line is blank followed by any detailed explanation starting from the third line. </li>
</ul>
<h1 id="ch8-modules_1">ch8. Modules</h1>
<ul>
<li>A module is basically <strong>a file</strong><em> containing all your functions and variables that you have defined</em>. </li>
<li>To reuse the module in other programs, the filename of the module must have a .py extension.</li>
</ul>
<h2 id="ex-sys-module">ex. sys module</h2>
<ul>
<li>
<p>When Python executes the <code>import sys</code> statement, it looks for the sys.py module in one of the directores listed in its <code>sys.path</code> variable. If the file is found, then the statements in the main block of that module is run and then the module is made available for you to use.</p>
</li>
<li>
<p>The <code>sys.argv</code> variable is a list of strings, contains the list of command line arguments i.e. the arguments passed to your program using the command line. 即程序执行时传给的参数列表.</p>
</li>
<li>
<p>The <code>sys.path</code> contains <em>the list of directory names where modules are imported</em> from. </p>
</li>
</ul>
<p>Observe that the first string in sys.path is empty - this empty string indicates that <em>the current directory</em> is also part of the sys.path which is same as the <code>PYTHONPATH</code> environment variable. This means that you can directly import modules located in the current directory. Otherwise, you will have to place your module in one of the directories listed in sys.path .</p>
<ul>
<li>Byte-compiled .pyc files</li>
</ul>
<p>Importing a module is a relatively costly affair.
This .pyc file is useful when you import the module the next time from a different program - it will be much faster since part of the processing required in importing a module is already done. Also, these byte-compiled files are platform-independent. </p>
<ul>
<li>from..import </li>
</ul>
<p>If you want to directly import the <code>argv</code> variable into your program (to avoid typing the <code>sys.</code> everytime for it), then you can use the <code>from sys import argv</code> statement.
not recommended...</p>
<ul>
<li><code>__name__</code></li>
</ul>
<p>Every Python module has it's <code>__name__</code> defined and if this is '<code>__main__</code>', it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.</p>
<ul>
<li>Every Python program is also a module. You just have to make sure it has a .py extension. </li>
</ul>
<h2 id="dir-function">dir() function</h2>
<ul>
<li>
<p>You can use the built-in dir function to <em>list the identifiers</em> that a module defines. The identifiers are the <strong>functions, classes, variables and imported modules</strong> defined in that module.</p>
</li>
<li>
<p>When you supply a module name to the dir() function, it returns the list of the names defined in that module. </p>
</li>
<li>When no argument is applied to it, it returns the list of names defined in the current module.</li>
</ul>
<h1 id="ch9-data-structures_1">ch9. Data Structures</h1>
<ul>
<li>Data structures are structures which can hold some data together. In other words, they are used to store a collection of related data.</li>
<li>3 built-in data structures in Python - <strong>list, tuple and dictionary</strong>.</li>
</ul>
<h2 id="list-abc">List [a,b,c]</h2>
<ul>
<li>a data structure that holds an ordered collection of items. </li>
<li>a <em>mutable</em> data type</li>
<li>you can add any kind of object to a list including numbers and even other lists.</li>
</ul>
<p>methods:</p>
<ul>
<li><em>indexing </em>operator: <code>a_list[1]</code></li>
<li><code>len(a_list)</code></li>
<li><code>a_list.append()</code></li>
<li><code>for..in</code> loop to iterate through the items of the list</li>
<li><code>a_list.sort()</code>: this method affects the list itself and does not return a modified list</li>
<li><code>del a_list[0]</code></li>
</ul>
<h2 id="tuple-abc">Tuple (a,b,c)</h2>
<ul>
<li>Tuples are just like lists except that they are <strong>immutable</strong></li>
<li>Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values (i.e. the tuple of values) used will not change.</li>
<li>can contain another tuple, another list......</li>
<li>singleton: <code>t=(2,)</code>(comma is necessary!)</li>
<li>empth: t=()</li>
</ul>
<p>methods:</p>
<ul>
<li>indexing: a_touple[0]</li>
<li>len(a_tuple)</li>
<li>used for output format:</li>
</ul>
<p><code>print '%s is %d years old' % (name, age)</code></p>
<h2 id="dictionary" k1:v1_="k1:v1," k2:v2="k2:v2">Dictionary</h2>
<ul>
<li>key-value mapping</li>
<li>you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. (This basically translates to say that you should use only simple objects for keys.)</li>
<li>一个dict中的keys不必同样type, values也是! </li>
<li>key/value pairs in a dictionary are <em>not ordered</em> in any manner.</li>
<li>instances/objects of the dict class.</li>
</ul>
<p>methods:</p>
<ul>
<li>adding key-value pair by indexing: <code>dic[key]=val</code><em>(overwrite if key already exists!)</em></li>
<li>deleting: <code>del dic[key]</code><em>(KeyError if key doesn't exist!)</em></li>
<li>
<p><code>dic.items()</code><em>返回一个list of tuples</em>:</p>
<p>dic.items()
[(k1,v1), (k2,v2)]
for k,v in dic.items:
print k, v</p>
</li>
<li>
<p><code>dic.keys()</code><em>返回keys的list</em></p>
</li>
<li>test: </li>
</ul>
<p>the <code>in</code> operator: <code>if akey in dic</code>
or even the <code>has_key</code> method of the dict class: <code>if dic.has_key(k)</code></p>
<h2 id="sequences">Sequences</h2>
<ul>
<li>Lists, tuples and strings are examples of sequences</li>
<li>Two of the main features of a sequence is the <strong>indexing</strong> operation which allows us to fetch a particular item in the sequence directly and the <strong>slicing</strong> operation which allows us to retrieve a slice of the sequence i.e. a part of the sequence.</li>
<li>
<p>The great thing about sequences is that you can access tuples, lists and strings all in the same way!</p>
</li>
<li>
<p>indexing(seq can be List or Tuple or String):</p>
</li>
</ul>
<p>seq<code>[2], seq[-1]</code></p>
<ul>
<li>slicing</li>
</ul>
<p>seq<code>[1:3]</code> <em>(from 1 to 2!)</em>
<code>seq[:]</code> <em>(a whole copy of the list)</em></p>
<h2 id="references">References</h2>
<ul>
<li>What you need to remember is that if you want to make a copy of a list or such kinds of sequences or complex objects (not simple objects such as integers), then you have to use the slicing operation(<code>list[:]</code>) to make a copy.</li>
<li>If you just assign the variable name to another name, both of them will refer to the same object and this could lead to all sorts of trouble if you are not careful.</li>
</ul>
<h2 id="string">String</h2>
<p>methods:</p>
<ul>
<li><code>str.startswith('a')</code> <em>return boolean</em></li>
<li><code>str.find(substr)</code> <em>return index of subster or -1 if not found</em></li>
<li><code>substr in str</code> <em>return boolean</em></li>
<li><code>str.join(strseq)</code> <em>use str as delimiter to joint the items in strseq</em></li>
</ul>
<h1 id="ch10-problem-solving-writing-a-python-script_1">ch10. Problem Solving - Writing a Python Script</h1>
<p>"a program which creates a backup of all my important files"</p>
<h2 id="1st-version">1st version</h2>
<ul>
<li>Run the command using the <code>os.system</code> function which runs the command as if it was run from the system i.e. in the shell - it returns 0 if the command was successfully, else it returns an error number.<div class="highlight"><pre><span class="code-line"><span></span><span class="err">source = ['/home/swaroop/byte', '/home/swaroop/bin']</span></span>
<span class="code-line"><span class="err">target_dir = '/mnt/e/backup/'</span></span>
<span class="code-line"><span class="err">target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'</span></span>
<span class="code-line"><span class="err">zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))</span></span>
<span class="code-line"><span class="err">if os.system(zip_command) == 0:</span></span>
<span class="code-line"><span class="err"> print 'Successful backup to', target</span></span>
<span class="code-line"><span class="c">else:</span></span>
<span class="code-line"><span class="c"> print 'Backup FAILED'</span></span>
</pre></div>
</li>
</ul>
<h2 id="2nd-version">2nd version</h2>
<ul>
<li>
<p>using the time as the name of the file within a directory with the current date as a directory within the main backup directory.</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="err">if not os.path.exists(today):</span></span>
<span class="code-line"><span class="err"> os.mkdir(today) # make directory</span></span>
<span class="code-line"><span class="err">...</span></span>
<span class="code-line"><span class="err">target = today + os.sep + now + '.zip'</span></span>
</pre></div>
</li>
<li>
<p><code>os.sep</code> variable - this gives the directory separator according to your operating system i.e. it will be '/' in Linux, Unix, it will be '\' in Windows and ':' in Mac OS.</p>
</li>
</ul>
<h2 id="3rd-version">3rd version</h2>
<ul>
<li>attaching a user-supplied comment to the name of the zip archive.<div class="highlight"><pre><span class="code-line"><span></span><span class="err">comment = raw_input('Enter a comment --> ')</span></span>
<span class="code-line"><span class="err">if len(comment) == 0: # check if a comment was entered</span></span>
<span class="code-line"><span class="err"> target = today + os.sep + now + '.zip'</span></span>
<span class="code-line"><span class="c">else:</span></span>
<span class="code-line"><span class="c"> target = today + os.sep + now + '_' + \</span></span>
<span class="code-line"><span class="c"> comment.replace(' ', '_') + '.zip'</span></span>
</pre></div>
</li>
</ul>
<h2 id="more-refinements">More Refinements</h2>
<ul>
<li>allow extra files and directories to be passed to the script at the command line. We will get these from the sys.argv list and we can add them to our source list using the extend method provided by the list class.</li>
<li>use of the tar command instead of the zip command. </li>
</ul>
<p>One advantage is that when you use the tar command along with gzip, the backup is much faster and the backup created is also much smaller. If I need to use this archive in Windows, then WinZip handles such .tar.gz files easily as well.</p>
<p><code>tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))</code></p>
<ul>
<li>The most preferred way of creating such kind of archives would be using the zipfile or tarfile module respectively.</li>
<li>"Software is grown, not built"</li>
</ul>
<h1 id="ch11-object-oriented-programming_1">ch11. Object-Oriented Programming</h1>
<h2 id="fields-methods">fields, methods</h2>
<ul>
<li>class: <strong>fields</strong>, <strong>methods</strong></li>
<li>Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called <strong>instance variables</strong> and <strong>class variables</strong> respectively.</li>
<li>ou must refer to the variables and methods of the same object using the <code>self</code> variable only. This is called an <em>attribute reference</em>.</li>
<li>we refer to the class variable as <code>ClassName.var</code> and not as <code>self.var</code>.</li>
</ul>
<h2 id="self">self</h2>
<ul>
<li>Class methods have only one specific difference from ordinary functions - <em>they must have an extra first name that has to be added to the beginning of the parameter list</em>, but you do do not give a value for this parameter when you call the method, Python will provide it. </li>
<li>create an object/instance of this class using the name of the class followed by a pair of parentheses.</li>
</ul>
<h2 id="the-init-method">The <strong>init</strong> method</h2>
<ul>
<li>The <code>__init__()</code> method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. </li>
<li>analogous to a constructor in C++, C# or Java.</li>
<li>the same, __<code>del__()</code> method: run when the object is no longer in use and there is no guarantee when that method will be run. If you want to explicitly do this, you just have to use the del statement.</li>
<li><em>All class members (including the data members) are <strong><em>public</em></strong> and all the methods are <strong><em>virtual</em></strong> in Python.</em></li>
<li>One exception: If you use data members with names using the double underscore prefix such as <code>__privatevar</code>, Python uses name-mangling to effectively make it a private variable.</li>
</ul>
<h2 id="inheritance">Inheritance</h2>
<ul>
<li>
<p>ex:</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="err">class Teacher(SchoolMember)://</span></span>
<span class="code-line"><span class="err"> '''Represents a teacher.'''</span></span>
<span class="code-line"><span class="err"> def __init__(self, name, age, salary):</span></span>
<span class="code-line"><span class="err"> SchoolMember.__init__(self, name, age)</span></span>
<span class="code-line"><span class="err"> self.salary = salary</span></span>
<span class="code-line"><span class="err"> print '(Initialized Teacher: %s)' % self.name</span></span>
</pre></div>
</li>
<li>
<p>To use inheritance, we specify the base class names in a <strong>tuple</strong> following the class name in the class definition. --<em>multiple inheritance.</em></p>
</li>
<li>the <code>__init__</code> method of the base class is explicitly called using the <code>self</code> variable so that we can initialize the base class part of the object. This is very important to remember - <em>Python does not automatically call the constructor of the base class, you have to explicitly call it yourself.</em></li>
</ul>
<h1 id="ch12-inputoutput_1">ch12. Input/Output</h1>
<h2 id="files">Files</h2>
<ul>
<li>open and use files for reading or writing by creating an object of the <code>file</code> class and using its <code>read</code>, <code>readline</code> or <code>write</code> methods appropriately to read from or write to the file. Then finally, when you are finished with the file, you call the <code>close</code> method to tell Python that we are done using the file.<div class="highlight"><pre><span class="code-line"><span></span><span class="err">f = file('poem.txt', 'w') # open for 'w'riting</span></span>
<span class="code-line"><span class="err">f.write(poem) # write text to file</span></span>
<span class="code-line"><span class="err">f.close() # close the file</span></span>
<span class="code-line"><span class="err">f = file('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default</span></span>
<span class="code-line"><span class="err">while True:</span></span>
<span class="code-line"><span class="err"> line = f.readline()# This method returns a complete line including the newline character at the end of the line.</span></span>
<span class="code-line"><span class="err"> if len(line) == 0: # Zero length indicates EOF</span></span>
<span class="code-line"><span class="err"> break</span></span>
<span class="code-line"><span class="err"> print line, # Notice comma to avoid automatic newline added by Python</span></span>
<span class="code-line"><span class="err">f.close() # close the file</span></span>
</pre></div>
</li>
</ul>
<h2 id="pickle">Pickle</h2>
<ul>
<li><em>Python provides a standard module called </em><code>pickle</code><em> using which you can store any Python object in a file and then get it back later intact. This is called storing the object persistently.</em></li>
<li>There is another module called <code>cPickle</code> which functions exactly same as the <code>pickle</code> module except that it is written in the C language and is (upto 1000 times) faster. </li>
<li>
<p>pickling & unpickling:</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="kn">import</span> <span class="nn">cPickle</span> <span class="kn">as</span> <span class="nn">p</span></span>
<span class="code-line"><span class="n">f</span> <span class="o">=</span> <span class="nb">file</span><span class="p">(</span><span class="n">shoplistfile</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span></span>
<span class="code-line"><span class="n">p</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">shoplist</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span></span>
<span class="code-line"><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></span>
<span class="code-line"><span class="n">f</span> <span class="o">=</span> <span class="nb">file</span><span class="p">(</span><span class="n">shoplistfile</span><span class="p">)</span></span>
<span class="code-line"><span class="n">storedlist</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span></span>
<span class="code-line"><span class="k">print</span> <span class="n">storedlist</span></span>
</pre></div>
</li>
<li>
<p>To store an object in a file, first we open a file object in write mode and store the object into the open file by calling the <code>dump</code> function of the pickle module. This process is called <em>pickling</em>.</p>
</li>
<li>Next, we retrieve the object using the <code>load</code> function of the pickle module which returns the object. This process is called <em>unpickling</em>.</li>
</ul>
<h1 id="ch13-exceptions_1">ch13. Exceptions</h1>
<h2 id="tryexcept">Try..Except</h2>
<ul>
<li>
<p>We can handle exceptions using the <code>try..except</code> statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.</p>
</li>
<li>
<p>ex</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="kn">import</span> <span class="nn">sys</span></span>
<span class="code-line"><span class="k">try</span><span class="p">:</span></span>
<span class="code-line"> <span class="n">s</span> <span class="o">=</span> <span class="nb">raw_input</span><span class="p">(</span><span class="s1">'Enter something --> '</span><span class="p">)</span></span>
<span class="code-line"><span class="k">except</span> <span class="ne">EOFError</span><span class="p">:</span></span>
<span class="code-line"> <span class="k">print</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">Why did you do an EOF on me?'</span></span>
<span class="code-line"> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">()</span> <span class="c1"># exit the program</span></span>
<span class="code-line"><span class="k">except</span><span class="p">:</span></span>
<span class="code-line"> <span class="k">print</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">Some error/exception occurred.'</span></span>
<span class="code-line"> <span class="c1"># here, we are not exiting the program</span></span>
<span class="code-line"><span class="k">print</span> <span class="s1">'Done'</span></span>
</pre></div>
</li>
<li>
<p>The <code>except</code> clause can handle a single specified error or exception, or a parenthesized list of errors/exceptions. If no names of errors or exceptions are supplied, it will handle all errors and exceptions.</p>
</li>
<li>If any error or exception is not handled, then the default Python handler is called which just stops the execution of the program and prints a message.</li>
<li>You can also have an <code>else</code> clause associated with a <code>try..catch</code> block. The <code>else</code> clause is executed if no exception occurs.</li>
</ul>
<h2 id="raising-exceptions">Raising Exceptions</h2>
<ul>
<li>using the <code>raise</code> statement. </li>
<li>You also have to specify the name of the error/exception and the exception object that is to be thrown along with the exception. </li>
<li>The error or exception that you can arise should be class which directly or indirectly is a derived class of the <code>Error</code> or <code>Exception</code> class respectively.</li>
<li>ex.<div class="highlight"><pre><span class="code-line"><span></span><span class="k">class</span> <span class="n">ShortInputException</span>(<span class="nb">Exception</span>):</span>
<span class="code-line"> <span class="s">'''A user-defined exception class.'''</span></span>
<span class="code-line"> <span class="n">def</span> <span class="n">__init__</span>(<span class="k">self</span>, <span class="n">length</span>, <span class="n">atleast</span>):</span>
<span class="code-line"> <span class="nb">Exception</span>.<span class="n">__init__</span>(<span class="k">self</span>)</span>
<span class="code-line"> <span class="k">self</span>.<span class="n">length</span> = <span class="n">length</span></span>
<span class="code-line"> <span class="k">self</span>.<span class="n">atleast</span> = <span class="n">atleast</span></span>
<span class="code-line"></span>
<span class="code-line"><span class="n">try:</span></span>
<span class="code-line"> <span class="o">s</span> = <span class="n">raw_input</span>(<span class="s">'Enter something --> '</span>)</span>
<span class="code-line"> <span class="k">if</span> <span class="n">len</span>(<span class="o">s</span>) < <span class="mi">3</span>:</span>
<span class="code-line"> <span class="n">raise</span> <span class="n">ShortInputException</span>(<span class="n">len</span>(<span class="o">s</span>), <span class="mi">3</span>)<span class="c1"># specify the name of the error/exception and the exception object that is to be thrown</span></span>
<span class="code-line"></span>
<span class="code-line"><span class="n">except</span> <span class="n">EOFError:</span></span>
<span class="code-line"> <span class="nb">print</span> <span class="s">'\nWhy did you do an EOF on me?'</span></span>
<span class="code-line"><span class="n">except</span> <span class="n">ShortInputException</span>, <span class="o">x</span>:</span>
<span class="code-line"> <span class="nb">print</span> <span class="s">'ShortInputException: The input was of length %d, \</span></span>
<span class="code-line"><span class="s"> was expecting at least %d'</span> % (<span class="o">x</span>.<span class="n">length</span>, <span class="o">x</span>.<span class="n">atleast</span>)</span>
<span class="code-line"><span class="n">else:</span></span>
<span class="code-line"> <span class="nb">print</span> <span class="s">'No exception was raised.'</span></span>
</pre></div>
</li>
</ul>
<h2 id="tryfinally">Try..Finally</h2>
<ul>
<li>What if you were reading a file and you wanted to close the file <em>whether or not an exception was raised</em>?</li>
<li>before the program exits, the finally clause is executed and the file is closed.</li>
</ul>
<h1 id="ch14-the-python-standard-library_1">ch14. The Python Standard Library</h1>
<h2 id="sys-module">sys module</h2>
<ul>
<li><code>sys.argv</code></li>
</ul>
<p>there is always at least one item in the <code>sys.argv</code> list which is the name of the current program being run and is available as <code>sys.argv[0]</code> . Other command line arguments follow this item.</p>
<ul>
<li><code>sys.exit</code> : to exit the running program.</li>
</ul>
<h2 id="os-module">os module</h2>
<ul>
<li><code>os.getcwd()</code></li>
</ul>
<p>gets the current working directory i.e. the path of the directory from which the curent Python script is working.</p>
<ul>
<li><code>os.listdir()</code></li>
<li><code>os.remove()</code></li>
<li><code>os.system()</code>: run a shell command.</li>
<li><code>os.linesep</code>: string gives the line terminator used in the current platform. </li>
<li><code>os.path.split()</code>: returns the directory name and file name of the path.</li>
<li><code>os.path.isfile()</code> and <code>os.path.isdir()</code></li>
</ul>
<h1 id="ch15-more-python_1">ch15. More Python</h1>
<h2 id="special-methods">Special Methods</h2>
<ul>
<li>Generally, special methods are used to mimic certain behavior. </li>
<li>For example, if you want to use the <code>x[key]</code> indexing operation for your class (just like you use for lists and tuples) then just implement the <code>__getitem__()</code> method and your job is done.</li>
<li><code>__init__(self, ...)</code> </li>
<li><code>__del__(self)</code> </li>
<li><code>__str__(self)</code> </li>
</ul>
<p>Called when we use the <code>print</code> statement with the object or when <code>str()</code> is used.</p>
<ul>
<li><code>__lt__(self, other)</code> </li>
</ul>
<p>Called when the <em>less than</em> operator ( < ) is used. Similarly, there are special methods for all the operators (+, >, etc.)</p>
<ul>
<li><code>__getitem__(self, key)</code> </li>
</ul>
<p>Called when x[key] indexing operation is used.</p>
<ul>
<li><code>__len__(self)</code> </li>
</ul>
<p>Called when the built-in <code>len()</code> function is used for the sequence object.</p>
<h2 id="list-comprehension">List Comprehension</h2>
<ul>
<li>used to derive a new list from an existing list.</li>
<li>
<p>ex</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="err">listone = [2, 3, 4]</span></span>
<span class="code-line"><span class="err">listtwo = [2*i for i in listone if i > 2]</span></span>
</pre></div>
</li>
<li>
<p>Here, we derive a new list by specifying the manipulation to be done (2*i) when some condition is satisfied (if i > 2).</p>
</li>
</ul>
<h2 id="receiving-tuples-and-lists-in-functions">Receiving Tuples and Lists in Functions</h2>
<ul>
<li>receiving parameters to a function as a <em>tuple</em> or a <em>dictionary</em> using the <code>*</code> or <code>**</code> prefix respectively. </li>
<li>This is useful when taking variable number of arguments in the function.</li>
</ul>
<p><code>def powersum(power, *args):...</code></p>
<ul>
<li>Due to the * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.</li>
</ul>
<h2 id="lambda-forms">Lambda Forms</h2>
<ul>
<li>A <code>lambda</code> statement is used to create new function objects and then return them <em>at runtime</em>.</li>
<li>ex. <div class="highlight"><pre><span class="code-line"><span></span><span class="err">def make_repeater(n):</span></span>
<span class="code-line"><span class="err"> return lambda s: s * n</span></span>
<span class="code-line"><span class="err">twice = make_repeater(2)</span></span>
<span class="code-line"><span class="err">print twice('word')</span></span>
<span class="code-line"><span class="err">print twice(5)</span></span>
</pre></div>
</li>
</ul>
<p>output:</p>
<div class="highlight"><pre><span class="code-line"><span></span><span class="err"> $ python lambda.py</span></span>
<span class="code-line"><span class="err"> wordword</span></span>
<span class="code-line"><span class="err"> 10</span></span>
</pre></div>
<ul>
<li>A <code>lambda</code> statement is used to create <em>the function object</em>.</li>
<li>Essentially, <em>the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function.</em> </li>
<li>Note that even a print statement cannot be used inside a lambda form, only <em>expressions</em>.</li>
</ul>
<h2 id="the-exec-and-eval-statements">The exec and eval statements</h2>
<ul>
<li>The <code>exec</code> statement is used to execute Python statements which are stored in a string or file.</li>
<li>The <code>eval</code> statement is used to evaluate valid Python expressions which are stored in a string. </li>
</ul>
<h2 id="the-assert-statement">The assert statement</h2>
<ul>
<li>to assert that something is true. </li>
<li>For example, if you are very sure that you will have at least one element in a list you are using and want to check this, and raise an error if it is not true, then assert statement is ideal in this situation. </li>
<li>When the assert statement fails, an AssertionError is raised.</li>
</ul>
<h2 id="the-repr-function-or-backticks">The repr function or Backticks(`)</h2>
<ul>
<li>to obtain a canonical string representation of the object.</li>
<li>you will have <code>eval(repr(object)) == object</code> most of the time.</li>
<li>Basically, the repr function or the backticks are used to obtain a printable representation of the object.</li>
<li>can control what your objects return for the repr function by defining the __<code>repr__</code> method in your class.</li>
</ul>
</div>
<div class="entry-content jumbotron" id="source-content" style="display: none">
<!-- <pre><code id="source-code">
</code></pre> -->
<div id="source-code"></div>
</div>
<!-- /.entry-content -->
<div class="row" id="prevnext">
<div class="col-xs-12">
<a href="https://x-wei.github.io/linux下安装并使用java开发opencv的配置.html" class="btn btn-default btn-lg" style="float:left;clear:both;background-color:#fff;">
<h4><i class="fa fa-arrow-left"></i>
linux下安装并使用java开发opencv的配置
</h4>
</a>
</div>
<div class="col-xs-12">
<a href="https://x-wei.github.io/fr-input.html" class="btn btn-default btn-lg" style="float:right;clear:both;background-color:#fff;">
<h4>
A French Input Method<i class="fa fa-arrow-right"></i>
</h4>
</a>
</div>
</div>
<section class="comments" id="comments">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-primary">
<div class="panel-heading" role="tab" id="disqus-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#disqus-comments" aria-expanded="true" aria-controls="disqus-comments">
<i class="fa fa-comments-o"></i> Disqus 留言
</a>
</h4>
</div>
<div id="disqus-comments" class="panel-collapse collapse.show" role="tabpanel" aria-labelledby="disqus-heading">
<div class="panel-body">
<div class="tab-pane fade active in" id="disqus-comments">
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'xweisblog'; // required: replace example with your forum shortname
var disqus_identifier = 'byte_of_python笔记';
var disqus_url = 'https://x-wei.github.io/byte_of_python笔记.html';
var disqus_config = function () {
this.language = "zh";
};
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by
Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
</div>
</div>
</div>
</section> </article>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<a data-dismiss="modal" href="javascript:void(0);">
<img id="mimg" src="" style="width:100%;height:auto">
</a>
</div>
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>
<div class="col-xl-3 col-lg-4 col-md-6" id="sidebar">
<aside>
<section>
<div class="sidebar-container">
<div class="sidebar-item ">
<div class="panel panel-default">
<div class="panel-heading">
<h4>
<i class="fa fa-user fa-lg"></i>
<a href="https://x-wei.github.io/about.html">
关于 mx
</a>
</h4>
</div>
<div class="panel-body" id="aboutme">
<a href="https://x-wei.github.io/about.html"><img width="100%" src="https://x-wei.github.io/../images/mx.jpg"/></a>
<h3 style="text-align:center">
<a href="https://github.com/x-wei" target="_blank">
<i class="fa fa-github" style="text-align:center"></i></a>
<a href="https://weibo.com/u/1817154611" target="_blank">
<i class="fa fa-weibo" style="text-align:center"></i></a>
<a href="mailto:[email protected]" target="_blank">
<i class="mdi-communication-email" style="text-align:center"></i></a>
</h3>
<h4 class="widget-title">推荐文章</h4>
<div class="textwidget">
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/TeXmacs_intro.html">学术文章写作利器: TeXmacs介绍</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/hashcode2014-solved-by-LP.html">运筹的力量: 用线性规划解决Google 2014 HashCode问题</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%85%A5%E9%97%A8%E7%AE%80%E4%BB%8B.html">正则表达式入门简介</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/%E6%88%91%E7%9A%84ubuntu10.04%E9%85%8D%E7%BD%AE%E6%80%BB%E7%BB%93.html">我的ubuntu10.04配置总结</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/PT-summery.html">2011巴黎高科(ParisTech)申请总结</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/GT-summery.html">用尽量少的时间考一个够用的分数--一点Tofel/GRE备考经验</a><br></li>
<li class="widget-container widget_text">
<a href="https://x-wei.github.io/pelican_github_blog.html">用pelican在github上创建自己的博客!</a><br></li>
</div>
<br><a href="https://www.polytechnique.edu/" target="_blank">
<img src="https://x-wei.github.io/images/x-logo.png" alt="X" width="180" border="0" />
</a><br/>
<br><a href="https://www.sjtu.edu.cn/">
<img src="https://x-wei.github.io/images/ssss.jpg" width="180" border="0" alt="上海西南某高校">
</a><br/>
<br>
<h4 class="widget-title">Visitors</h4>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/1.js?i=59olkba9w7e&s=220&m=3&v=true&r=false&b=000000&n=false&c=ff0000" async="async"></script>
<!-- hitwebcounter Code START -->
<a href="https://www.hitwebcounter.com/how-to/how-to-what-is-free-blog-counter.php" target="_blank">
<img src="https://hitwebcounter.com/counter/counter.php?page=5954927&style=0036&nbdigits=5&type=ip&initCount=0" title="web counter" Alt="web counter" border="0" ></a>
<br/>
</div>
</div>
</div>
<div class="sidebar-item ">
<div class="panel panel-default">
<div class="panel-heading">
<h4>
<a href="https://x-wei.github.io/tags.html"><i class="fa fa-tags fa-lg"></i><span class="icon-label">标签云</span></a>