PowerPoint
Python
Moon Yong Joon
1
Contents
Moon Yong Joon
2
1. Python 2. Python /3. Python 4.Python /
3
5. Python 6. Python 7. 8. Exception9. Python
4
1.Python
Moon Yong Joon
5
1.1
6
zen of python
7
zen of python
8
platform
9
platform module
platform
10
1.2
11
12
Python 2to3
http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html
13
__future__
14
3.X
Python 2to3
15
1.3 /
16
literal expression
17
literal expression
literal expression ,
18
19
20
21
Division :
22
, operator
2. int 3.
__future__ division import 3.
23
special method
/ __truediv__ // __floordiv__
24
25
Expression
26
Expression
generator
Generator expression
27
1.4
28
29
Expression vs. Statement
(eval) (exec)
30
=
if
for/while
try/except
with
def/class
#,
31
32
#
, : docstring ,
33
1.5
34
35
var, obj var obj class var, obj
36
( Reference Variable)
,
Variable
,
Variable = ()
( )
37
38
39
None
Variable
,
Variable = ()
40
i
41
1.6 (value & Type)
42
43
instance object class object
Class
object
Instance
object
Type
Value
new
Value/Type
44
45
(Variable) (object)
,
Variable
,
Variable = ()
46
Type
47
Type inference
l .
.
.
48
49
new
50
Int
Float int isdigit() True
51
float
int float
52
53
54
1.7 //
55
56
: , ,,,
57
( )
Private
(property, )
Private( )
, (special method)
58
59
namespace
namespace
operator
operator
60
Special
61
Special
__special__
62
1.8 Keywords
63
Keyword
64
Keyword
keyword keyword import (2.7)
65
Keyword : 2.x
2.7
Keywordandelififprintaselseimportraiseassertexceptinreturnbreakexecistryclassfinallylambdawhilecontinuefornotwithdeffromoryielddelglobalpass66
Keyword : print(2.x)
2.x 3. __future__ import print
67
Keyword : 3.x
3.x
Keywordandelifimportraiseaselseinreturnassertexceptistrybreakfinallylambdawhileclassfor nonlocalwithcontinuefromnotyielddefglobalordelifpass68
69
Print : 2.7
70
1.9
71
72
=
iii + 1 Unbinding (NameError: name 'iii' is not defined)
73
binding()
Scope
I + 1 I
I NameError: name 'i' is not defined
( )
.
74
75
namespace
, class, instance global
globals()
locals()
class
__dict__
instance
__dict__
76
class method :
class class namespace class.
Global
Count = 100
Class A
A.Count = 1
77
78
Reference Variable
() reference binding
dir() context
79
namespace: dict type
global . Globals context
80
namespace:
globals [], = global
81
binding
82
Variable
83
84
85
Variable
Context .
del , del()
86
1.10
87
Chained Assignments
88
.
89
Augmented Assignments
90
.
91
1.11 operator
92
Operator
93
94
95
96
97
: and, or, xor
OperatorDescription& Binary AND | Binary OR ^ Binary XOR98
: ~,
OperatorDescription~ Binary Ones Complement1 > Binary Right Shift .99
100
101
102
: and/or
and : true
and : false
or : true
or : false
103
104
174
annotation : tuple
annotation
175
annotation : int
annotation
176
1.17 ( )
177
178
2 namespace
()
()
179
class
class
180
181
exec
182
class :exec
class exec
183
exec : 2.
exec
184
exec : 3.
exec
185
1.18 Lambda
186
187
lambda
lambda
188
189
lambda
python
2.X print
190
global
191
Lambda : Global
global
192
1.19
193
194
195
196
197
. ()
198
199
( x,y closure )
200
201
apply
appy
def ( , *args, **kwargs) :
apply
202
operator
203
1. 20 Namespace/
204
205
( global) ( local)
Builtin
Local > Global > Built-in
()
()
206
1
p
207
2
local/global global
208
/
209
: global
global namespace(__dict__) key/value . global
Module namespace
vvv
210
: local
local local namespace(__dict__)
func namespace
var_init, var
x runtime
211
Global immutable
212
global
Global immutable
namespace(global)
namespace(local)
213
global :
Global Mutable
result = result +
result global
214
global
Global Mutable global
namespace(global)
namespace(local)
Int, float immutable global
215
Global mutable
216
global : mutable
Global Mutable global
217
1.21 namespace
218
nonlocal(2)
219
: 2
python 2 nonlocal
220
nonlocal(3)
221
Nonlocal
immutable namespace .
Namespace
Namespace
222
:
immutable
n + = x n
223
:
immutable nonlocal
224
1.22
225
Bytecode
226
dis : bytecode
bytecode
227
source
228
Inspect : source
229
1.23
230
Callable
231
callable
(special method __call__ )
__call__
232
__call__
hasattr __call__
function class __call__
Python 2Python 3callable(anything)hasattr(anything,'__call__')233
234
2
1
0
Built-in
Global
3
Local
scope
Non Local
235
236
237
238
Built-in function
bif
239
return
240
1.24
241
Call by sharing
242
Call by sharing
=>Immutable
=> mutable
243
/
244
/
binding mutable/immutable
local reference
245
Function Bound/unbound
binding local reference
246
1.25
247
?
248
namespace key/value
namespace
249
250
?
251
key/value
252
?
253
key() value
254
?
255
(*[tuple], **[dict]) agrs/kwargs key value
256
namespce ?
257
Runtime
local runtime locals() key .
Runtime local
258
unpack ?
259
unpack
(*), (**) unpack
260
1.26 Data type is Object
261
1 ?
262
1
1
263
Literal
264
?
Immutuable
()
Mutuable
()
.
.
265
Value
Immutuable() :
-
Mutuable() : ()
- ,
266
267
268
call by sharing
269
var, obj var obj class var, obj
270
Class pass __init__
271
Class pass __init__
exec()
272
1.27
273
/
274
Values and data types:
type()
reference
type
value
float
1.1
reference
type
value
int
17
()
275
Values and data types:
reference
type
element
reference
type
value
int
1
reference
type
element
list
reference
type
value
reference
type
value
list
276
277
copy
i j j i
278
279
is/is not :
280
281
== :
==
282
== : overriding
__eq__ overriding
283
1.28
284
285
dir()
/
286
instance.__dict__
287
Mutable & immutable
288
Mutable & immutable
mutabale
immutabale
289
Builtin type
=>
(immutable) : int, float, complex,
str/unicode/bytes, tuple, frozenset
(mutable) : list, dict, set, bytes-array
290
Mutable & immutable
Values .
variables,
291
Data(Object) Type
292
object
293
Data types
int data type type
int type
294
1.29 Python Class
295
Class (2)
296
object
2 object (3 )
297
298
__init__
__init__ Class
obj = Class()
class Class( Class) :
def __init__(self, ) :
self. =
299
Explicit is better than implicit
class __init__
__init__
300
301
Class object (, ) bind reference
302
303
Class object instance
304
305
Class public
Class runtime
306
Classmethod/statcimethod
Class object method . Staticmethod type
307
add 2 add
308
309
__init__ class
310
311
class object override
312
class object class
313
314
:
.
class object type object
(inheritance)(Delegation)Is a Has a315
class object
316
317
Method Bound/unbound
bounding , bound
318
Method Bound
self, cls
TransformationCalled from an ObjectCalled from a ClassInstance methodf(*args)f(obj,*args)Static methodf(*args)f(*args)Class methodf(*args)f(*args)319
320
class class
Instance.method = function method
321
322
1
Class .
323
2
Class
324
Class @staticmethod
325
1.30 Classnamespace
326
Class
327
class
class/instance namespace __dict__
class
__dict__
instance
__dict__
Base class
__dict__
328
class
class base class .
class
__dict__
instance
__dict__
Base class
__dict__
329
Class
330
class __dict__
class namespace __dict__
331
class
332
parent class/child class
class namespace __dict__
333
class
334
class
class namespace __dict__
335
class
class namespace __dict__
336
list class
list class namespace __dict__
337
dict class
dict class namespace __dict__
338
class
339
class : int
int class class instance __dict__
340
class : list
list class class instance __dict__ __getitem__
__dict__ value list
341
342
class
class
class
343
Runtime
344
class/instance
class/instace dict namespace
345
class/instance runtime
class/instace runtime
346
Global
347
class : global
class global
348
class : class ()
class class class
349
1.31 (binding)
350
/
351
context .
352
Binding method
353
Binding instance
context binding .
class Foo() :
def __init__(self,name=None) :
self.name = name
#context
Instance foo
foo = Foo(Dahl)
Foo.__init__(foo,Dahl)
{'name': 'Dahl'}
foo.__dict__
354
Binding function
355
Binding instance: function
context binding .
class Foo() :
def __init__(self,name=None) :
self.name = name
bar = external_bar
#context
Instance foo
foo = Foo(Dahl)
Foo.__init__(foo,Dahl)
{'lastname': 'Moon', 'name': 'Yong'}
foo.__dict__
def external_bar(self,lastname):
self.lastname = lastname
return self.name+ " " + self.lastname
foo.bar(Moon)
356
1.32 namespace
357
namespace
358
self.name self
359
globals local>global>builtin
360
361
local/global namespace
362
.
( )
363
1.33 instance property
364
property
365
property
class property property
366
Property
367
property
property
368
1.34 instance descriptor
369
Descriptor
370
descriptor
class desciptor
Instance instance
371
Descriptor
372
class name name Descriptor class
373
name namespace _name
374
1.35 Module
375
import/from import
376
import from imort
Import globals from import
377
from imort
from import
378
module global
379
module global
module global import global module global
add_1 add add_1 global
380
__builtin__
381
__builtin__ import
__builtins__ __builtin__ import
382
3. import
__builtins__ builtins import
383
1.36 File
384
File
385
File Object
Object File . iterable
Handle
Line
Line
Line
Line
Line
Line
method
386
File handle object
file handle
file
file
handle
387
File handle
388
File Object Method(1)
Methodfile.close()Close the filefile.flush() file.fileno()Return the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating systemfile.isatty()ReturnTrueif the file is connected to a tty(-like) device, elseFalse.file.next()A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. file.read([size])Read at mostsizebytes from the file (less if the read hits EOF before obtainingsizebytes).file.readline([size])Read one entire line from the file.file.readlines([sizehint]) ..389
File Object Method(2)
Methodfile.xreadlines() , .file.seek(offset[,whence]) .(whence offset , 1 offset, 2 offset ) - seek(n) : n - seek(n, 1) : n (n , ) - seek(n, 2) : n (n )file.tell() .file.truncate([size]) . ..file.write(str)Write a string to the file. There is no return value.file.writelines(sequence) .390
File :read
open read str
391
File :readlines
open readlines list
392
File :tell
open readline
393
File : seek
open readline seek
394
File : truncate
truncate .( write )
395
File handle
396
File Object Variable
Methodfile.closedbool indicating the current state of the file object.file.encodingThe encoding that this file uses.file.errorsThe Unicode error handler used along with the encoding.file.modeThe I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.file.nameIf the file object was created using open(), the name of the file. Otherwise, some string that indicates the source of the file object, of the form . file.newlinesIf Python was built with universal newlines enabled (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. file.softspaceoolean that indicates whether a space character needs to be printed before another value when using the print statement.397
1.37 File
398
File /
399
File
open close
: = open(, )
: .close()
file
400
File
r - r+ - a - ()a+ ( )w - w+ ( )t b- rb rb+ wb+ ( )ab+ ( )401
402
File
.write()
403
File
= open(, a) .write(), w
404
405
File -
.readline()
406
File -
.readlines(), .read()
407
408
File file
open line write
409
410
File
w+ mode write write
411
412
File
file_read.txt
413
File : for
iterable for
414
Console
415
raw_input file write
Console file
(3 input )
416
Jupyter notebook cell %load file load
417
1.38 File (with context)
418
With
419
File with
With file.close() with file close
420
2.Python /
Moon Yong Joon
421
2.1 Python class
422
class
423
object class class type class
object
class
/
class
type
class
424
__class__ __bases__
2
3
425
class
426
namespace
class class namespace
class
__dict__
namespace
427
namespace
class class class namespace
428
instance
429
instance namespace
class class instance __init__
class
__dict__
namespace
instance
__dict__
namespace
Scope()
430
namespace
class __init__
431
method
432
method namespace
class class instance __init__
class
__dict__
namespace
locals()
__dict__
namespace
Scope() (, )
433
namespace
method getPerson var_mt
434
2.2 object class
435
object class
436
object
Object object instance
Object
1 Object
437
object class:
438
object class :
(__new__), (__int__)
439
object :
object
440
441
object :
object
442
object :
object
443
object :
object ,
444
2.3 Type class
445
type class
446
type
type object (override )
447
type
Class type class , class type
448
Value and Type :
obj.__class__.__name__
obj.__class__
__name__
449
type class
450
Type: class
type
451
2.4 Iterable protocol
452
Iterator protocol
453
__iter__/next
iterator protocol __iter__/next
454
Iterable
455
Iterator : sentinel
iter sentinel callable setinel
456
Iterable class
457
Iterator
__iter__ next
458
Iterator
for next() exception
459
for next() exception
460
Iterable : list
461
list instance listiterator
list iter() listiterator next
462
for
for in iterable : iterable
463
2.5 data type
464
Namespace(__dict__)
465
: __dict__
__dict__
466
467
:
__dict__
468
: str
str class __dict__ self
469
2.6
470
__getattribute__
471
.
. . __getattribute__
472
: __getattribute__
.__getattribute__(__class__) class object
473
__getattribute__
Object class binding self self.__dict__
474
looping
475
return
476
__getattribute__
__getattribute__, getattr class recursive call
477
__getattribute__
__getattribute__ object.__getattribute__ recursive
478
2.7 number data type
479
Numeric Type
480
Numberic Types
int
float
long(2.x)
complex
1 context id
481
, operator
OperationResultNotesx+ysum ofxandyx-ydifference ofxandyx*yproduct ofxandyx/yquotient ofxandyx//y(floored) quotient ofxandyx%yremainder ofx/y-xxnegated+xxunchangedabs(x)absolute value or magnitude ofxint(x)xconverted to integerlong(x)xconverted to long integerfloat(x)xconverted to floating pointcomplex(re,im)a complex number with real partre, imaginary partim.imdefaults to zero.c.conjugate()conjugate of the complex numbercdivmod(x,y)the pair(x//y,x%y)pow(x,y)xto the poweryx**yxto the powery482
Numeric Type(int)
483
- int
int operator
484
int
int
real : int
bit_length() : bit
denominator :
numerator :
485
long
python3
NotesPython 2Python 3x=1000000000000Lx=1000000000000x=0xFFFFFFFFFFFFLx=0xFFFFFFFFFFFFlong(x)int(x)type(x)islongtype(x)isintisinstance(x,long)isinstance(x,int)486
Numeric Type(float)
487
- float
float operator
488
float
float
real : float
hex() : 16
fromhex() : hex() float
is_integer() : 0 true
as_integer_ratio() : denominator : , numerator :
489
Numeric Type(complex)
490
- complex
float operator
491
complex
complex
real : float
imag:
conjugate () :
492
493
fractions
fractions . Float float
494
fractions
fractions . Float float
495
2.8 sequence data type
496
Sequence Type
497
Sequence
Sequenec Types
String/unicode
Buffer/range
List/tuple
container
container
** string
Elements
498
Sequence
Sequence , operator
OperationResultNotesxins xnot ins s+t sequence s*n,n*s s[i] s[i:j] s[i:j:k] k len(s) min(s) max(s)499
sequence
500
Sequence class
sequence len() [ ]( )
__len__
__getitem__
Sequence
len()
Sequence index slice
501
Sequence class
__len__, __getitem__ overriding sequence class
502
Sequence class
__getitem__ list / return
503
Sequence sorting
504
Sequence-revesed
Sequence (reversed)
505
Sequence-sorted
Sequence (sorted, reversed)
506
Sequence : zip
507
zip seq
Sequence (zip)
Zip unpack 2
Python 2Python 3zip(a,b,c)list(zip(a,b,c))d.join(zip(a,b,c))no change508
zip : 3.x
Sequence (zip) zip
509
zip : 3.x : zip
Sequence (zip) zip
Python 2Python 3zip(a,b,c)list(zip(a,b,c))510
zip : 3.x list
Zip zip
511
zip : 3.x : join
Sequence (zip) join
Python 2Python 3d.join(zip(a,b,c))no change512
2.9 sequence(string) data type
513
Sequence : String Type
514
Sequence -str
str
515
String :
immutable +
516
String-operator
OperatorDescriptionExample+Concatenation - Adds values on either side of the operatora + b will give HelloPython*Repetition - Creates new strings, concatenating multiple copies of the same stringa*2 will give -HelloHello[]Slice - Gives the character from the given indexa[1] will give e[ : ]Range Slice - Gives the characters from the given rangea[1:4] will give ellinMembership - Returns true if a character exists in the given stringH in a will give 1 not inMembership - Returns true if a character does not exist in the given stringM not in a will give 1r/RRaw String print r'\n' prints \n and print R'\n'prints \n%Format - Performs String formattingSee at next section517
Operator+
Sequence , operator
+ : str, list, tuple str, tuple
min(), max() : , list list
518
String-escape
Backslash notationHexadecimal characterDescription\a0x07Bell or alert\b0x08Backspace\000\cxControl-x\C-xControl-x\e0x1bEscape\f0x0cFormfeed\M-\C-xMeta-Control-x\n0x0aNewline (Line Feed) \nnnOctal notation, where n is in the range 0.7\r0x0dCarriage return \s0x20Space\t0x09Tab\v0x0bVertical tab\xCharacter x\xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F\\ "\"\' (')\" (")519
Sequence : String method
520
Sequence-String (1)
String
Method Descriptioncapitalize()Capitalizes first letter of stringcenter(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.decode(encoding='UTF-8',errors='strict')Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.encode(encoding='UTF-8',errors='strict')Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.endswith(suffix, beg=0, end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.521
Sequence-String (2)
String
Method Descriptionfind(str, beg=0 end=len(string))Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not found.isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.isdigit()Returns true if string contains only digits and false otherwise.islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. partition ()Split the string at the first occurrence ofsep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.522
Sequence-String (3)
String
Method Descriptionisspace()Returns true if string contains only whitespace characters and false otherwise.istitle()Returns true if string is properly "titlecased" and false otherwise.isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.join(seq)Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.len(string)Returns the length of the stringljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.lower()Converts all uppercase letters in string to lowercase.lstrip()Removes all leading whitespace in string.maketrans()Returns a translation table to be used in translate function.523
Sequence-String (4)
String
Method Descriptionmax(str)Returns the max alphabetical character from the string str.min(str)Returns the min alphabetical character from the string str.replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.rfind(str, beg=0,end=len(string))Same as find(), but search backwards in string.rindex( str, beg=0, end=len(string))Same as index(), but search backwards in string.rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.rstrip()Removes all trailing whitespace of string.split(str="", num=string.count(str))Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.splitlines( num=string.count('\n'))Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.524
Sequence-String (5)
String
Method Descriptionstartswith(str, beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.strip([chars])Performs both lstrip() and rstrip() on stringswapcase()Inverts case for all letters in string.title()Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.translate(table, deletechars="")Translates string according to translation table str(256 chars), removing those in the del string.upper()Converts lowercase letters in string to uppercase.zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).isdecimal()Returns true if a unicode string contains only decimal characters and false otherwise.525
526
String : count
527
String : find
528
String : index
529
530
String : partition
3 tuple
531
String : join
list . dict
532
String : split
list
533
String : startswith
prefix
534
String : endswith
suffix
535
Translate:
536
String : translate
537
string.maketrans : help
538
string.maketrans ;
c k, s z table
abkdefghijklmnopqrztuvwxyz
abcdefghijklmnopqrstuvwxyz
539
String : translate : 1
540
String : translate : 2
string.maketran translate
541
Translate: 3
542
Translate : table
3 table dict
dict{ ord(key) : valeue}
/ ord(key)
543
Translate:
Translate dict key ord
544
Translate:
545
String : translate :
Translate
546
2.10 sequence(list) data type
547
Sequence : List Type
548
Sequence-List
list
list isinstance
549
Sequence - List
List
Python ExpressionResultsDescriptionl=[1,2,3] l.append(4)[1, 2, 3, 4] del l[3][1, 2, 3] len([1, 2, 3])3Length [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6] Concatenation['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition3 in [1, 2, 3]True Membershipfor x in [1, 2, 3]: print x,1 2 3 - Iteration550
Sequence-List : +/extend
list + list list.extend
551
Sequence-List
Function Descriptioncmp(list1, list2)Compares elements of both lists.len(list)Gives the total length of the list.max(list)Returns item from the list with max value.min(list)Returns item from the list with min value.list(seq)Converts a tuple into list.str(list)Produces a printable string representation of a listtype(list)Returns the type of the passed variable. If passed variable is list, then it would return a list type.552
Sequence-List : compare
2 0, 1, -1
553
Sequence : List method
554
Sequence-List
Method Descriptionlist.append(obj)Appends object obj to listlist.count(obj)Returns count of how many times obj occurs in listlist.extend(seq)Appends the contents of seq to listlist.index(obj)Returns the lowest index in list that obj appearslist.insert(index,obj)Inserts object obj into list at offset indexlist.pop(obj=list[-1])Removes and returns last object or obj from listlist.remove(obj)Removes object obj from listlist.reverse()Reverses objects of list in placelist.sort([func])Sorts objects of list, use compare func if given555
Sequence-List : append
list index
556
Sequence-List : count
list value
557
Sequence-List : pop
list index default last .
558
Sequence-List : remove
list value
559
Sequence-List : insert
list [index] index insert append
560
Sequence-List sort
list.sort(key=) ( )
561
Sequence-List stack
Stack LIFO(last in first out) List (append) (pop)
562
Sequence-List queue
queue FIFO(first in first out) List (append) (reverse,pop)
pop() 0
563
Sequence-List: reverse
list
564
565
Bisect
.
566
2.11 sequence(tuple) data type
567
Sequence : Tuple Type
568
Sequence - Tuple
tuple immutable
Slicing String
Python ExpressionResultsDescriptionT =(1,)(1,) (,) T = (1,2,3,4)(1, 2, 3, 4) len((1, 2, 3))3Length (1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6) Concatenation('Hi!) * 4'Hi!Hi!Hi!Hi!' string 3 in (1, 2, 3)True Membershipfor x in (1, 2, 3): print x,1 2 3 - Iteration569
Sequence- Tuple
tuple
Function Descriptioncmp(tuple1, tuple2)Compares elements of both tuples.len(tuple)Gives the total length of the tuple.max(tuple)Returns item from the tuple with max value.min(tuple)Returns item from the tuple with min value.tuple(seq)Converts a list into a tuple.str(tuple)Produces a printable string representation of a tupletype(tuple)Returns the type of the passed variable. If passed variable is tuple, then it would return a tuple type.570
Tuple
Tuple (count), (index)
571
572
Tuple :
Tuple tuple copy
list
573
Tuple
574
Tuple mutable
tuple immutable mutable . ,
575
2.12 Sequence type(Index/slice)
576
Sequence
577
Sequence
index
slice
578
Index/slice
579
Sequence
String index slice
580
Accessing Values : index
Sequence Type(String, List, Tuple) [index]
Sequence Instance [index]
581
Index slice
Index slice
582
Index/slice
583
Updating Values : list
Sequence Instance index .
584
Updating Values: string
immutable [index]
585
enumerater
586
index
Sequence (enumerate) index
587
Slice()
588
slice()
slice() slicing
589
slice()
slice() slicing
590
Slice ()
591
slicing //
Sequence , , , list
(python 2.x )
object.__getslice__(self,i,j)
object.__setslice__(self,i,j,sequence)
object.__delslice__(self,i,j)
/
592
Slice (2)
593
Container //
List,dict , , , list index
( )
object.__getitem__(self,key)
object.__setitem__(self,key,value)
object.__delitem__(self,key)
/
594
get/set/del item
dict/list/tuple dict/list
List index
Dict key
595
get/set/del slice
2 Sequence slicing (item )
596
2.13 String format
597
Format conversion type
598
Format :
format
Conversion Type Meaningd, iSigned integer decimaloUnsigned octaluUnsigned decimalxUnsigned hexadecimal (lowercase)XUnsigned hexadecimal (uppercase)eFloating-point exponential format (lowercase)EFloating-point exponential format (uppercase) f, FFloating-point decimal formatgSame as e if exponent is greater than 4 or less than precision; f otherwiseGSame as E if exponent is greater than 4 or less than precision; F otherwisecSingle character (accepts an integer or a single character string)rString (converts any Python object using repr)wString (converts any Python object using str)599
New
600
String-format :
{:} .format()
601
String-format :
{name:} .format()
602
String-format
s (String) d, i (Integer)f (floating-point)o8x16X16%% !r__repr__ !s__str__603
String Format -old
604
String-format
%s(string)%d (Integer)%f (floating-point)%o8%x16605
String-format(%) :
% ( )
% % ( )
606
String-format(%) : name
%() % (dict )
607
2.14 String format( )
608
New
609
String-format :
{:[.]} .format()
610
String-format :
{:[.]} .format()
611
String-format :
{ : width.precision } .format()
{:[.]} .format()
612
String-format
formatting
613
old
614
String-format :
%width.precision } %format()
615
old *
616
*
*
617
2.15 String format name
618
String Format new
619
String-format
% % % () { } .format()
620
name - new
621
String-format : index
{ } .format()
0
{} {]
622
String-format : name
{ } .format(=,)
{} {]
623
String-format :
{} { } .format(, =)
Key/Value
624
name - old
625
String-format :
% dict key
626
2.16 String format
627
new
628
String-format
< >^ =629
String-format
format
.
{:[][.]} .format()
630
Sign/0- new
631
Signs, Zero-Padding
padding
{:[][padding][.]} .format()
632
Sign/0- old
633
Signs, Zero-Padding
%()(.)?[s|d|f]
+ / -
634
2.17 setdata type
635
Set Type
636
Set
, (unordered)
(&), (|), (-)
Set: mutable set
Frozenset: immutable set
637
Set
mutable
Set
Set 1
638
Set
Set() 1 . mutable
639
Set
Set index/slice for
Index
640
dict.keys()
641
dict.keys() : 3
dict.keys() dict_keys set
642
FrozenSet Type
643
FrozenSet
FrozenSet type immutable
644
Set Type /
645
Set -
OperationEquivalentResultlen(s)cardinality of setsxinstestxfor membership insxnot instestxfor non-membership ins646
Set - 1
OperationEquivalentResults.issubset(t)s=ttest whether every element intis inss.union(t)s|tnew set with elements from bothsandts.intersection(t)s&tnew set with elements common tosandts.difference(t)s-tnew set with elements insbut not ints.symmetric_difference(t)s^tnew set with elements in eithersortbut not boths.copy()new set with a shallow copy ofs647
Set - 2
OperationEquivalentResults.update(t)s|=tupdate sets, adding elements fromts.intersection_update(t)s&=tupdate sets, keeping only elements found in bothsandts.difference_update(t)s-=tupdate sets, removing elements found ints.symmetric_difference_update(t)s^=tupdate sets, keeping only elements found in eithersortbut not in boths.add(x)add elementxto setss.remove(x)removexfrom sets; raises KeyError if not presents.discard(x)removesxfrom setsif presents.pop()remove and return an arbitrary element froms; raisesKeyErrorif emptys.clear()remove all elements from sets648
/
649
Set
object, type, int special method override
650
Set
Set type mutable
651
Set update
set set
652
Set :intersection_update
set set
653
Set :difference_update
set set
654
Set :symmetric_difference_update
set set
655
Set add
Set . set
656
Set remove
Set
657
Set discard
Set
658
Set pop
Set hash .
659
Set clear
Set
660
2.18 mappingdata type
661
mapping Type
662
Mapping -dictionary
Key/Value
container
Name 1
Name 2
container
:
:
Dictionary Type
663
Mapping - dict
dict
664
Mapping
dict type
665
Hash
666
key hash
mapping hash
tuple mutable hash
667
dict
668
Map -
dict . key/value
669
dict
670
Mapping - Accessing Elements
Key/Value Key index
671
Mapping - Updating Elements
key key
key :
key :
672
Mapping - Delete Elements
, , dict instance
Dict
673
dict
674
Mapping dict
Dictionary , , dictionary instance
Function Descriptioncmp(dict1, dict2)Compares elements of both dict.len(dict)Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.str(dict)Produces a printable string representation of a dictionarytype(dict)Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.dict(mapping)Converts a map into list.675
Mapping -dict class
dict
676
dict
677
Mapping -dictionary
Method Descriptiondict.clear()Removes all elements of dictionarydictdict.copy()Returns a shallow copy of dictionarydictdict.fromkeys()Create a new dictionary with keys from seq and valuessettovalue.dict.get(key, default=None)Forkeykey, returns value or default if key not in dictionarydict.has_key(key)Returnstrueif key in dictionarydict,falseotherwisedict.items()Returns a list ofdict's (key, value) tuple pairsdict.keys()Returns list of dictionary dict's keysdict.setdefault(key, default=None)Similar to get(), but will set dict[key]=default ifkeyis not already in dictdict.update(dict2)Adds dictionarydict2's key-values pairs todictdict.values()Returns list of dictionarydict's values dict.iteritems()Iterable items678
dict.get()
dict KeyError get()
Key default
679
dict.setdefault()
dict default
680
dict.get/setdefault()
dict [] get
681
dict.update()
dict dict
682
iteritems/iterkeys/itervalues
dict iterable
683
684
keys,items
NotesPython 2Python 3a_dictionary.keys()list(a_dictionary.keys())a_dictionary.items()list(a_dictionary.items())a_dictionary.iterkeys()iter(a_dictionary.keys())[iforiina_dictionary.iterkeys()][iforiina_dictionary.keys()]min(a_dictionary.keys())no change685
keys, values, items list dict
686
dict.key/values/items()
python list dict_keys, values,items list()
687
dict.key/values/items: for
python 3. for
688
dict.key: set
python 3. set
689
viewitems/keys/values
690
dict.viewitems()
dict view 3
691
viewitems/viewkeys()
dict viewitems/viewkeys set (3 keys()/items() )
692
2.19 Boolean data type
693
Boolean type
694
Boolean
true/false
or "python"""[1, 2, 3][](){}10NoneIf :
pass
Else :
pass
695
Bool
bool int
696
2.20 nonedata type
697
None type
698
None
(Not Exists)
(Not Assigned, Not Defined)
(No Value)
(Initialized Value)
699
None
700
2.21 Type
701
Type Conversion
702
Type conversion
703
Type
int()
float()
str()
list()
dict()
tuple()
set()
704
immutable
705
immutable
int()
float()
str()
tuple()
706
String integer
str isdigit
707
String
string str()
708
mutable
709
mutable
mutable
list()
dict()
set()
710
2.22 Data type copy
711
Copy
712
Mutable & immutable
copy copy
copy.deepcopy
tuple/list/dict list
713
Copy : immutable
714
str copy
str copy str copy
Immutable copy
715
tuple copy
tuple copy tuple copy
Immutable copy
716
Copy : mutable
717
list copy
list copy
718
set copy
set copy
719
dict copy
dict copy
720
deepcopy
721
deepcopy
mutable mutable deepcopy
Mutable ,
Mutable
722
2.23 Comprehension
723
comprehension
724
/
#
S ={1,2,4,8,...,2}
#
M={x|xinSandxeven}
725
Comprehension
for i in sequence if
For :
If
726
Comprehension
727
2.
2 comprehension namespace comprehension
x
728
3.
3 comprehension namespace comprehension
729
list comprehension
730
List Comprehension
A = [ for i in sequence if ]
731
List Comprehension :
for
A = [ for i in sequence for j in sequence if ]
732
List
733
734
735
set comprehension
736
Set Comprehension
Set Set
A = { for i in sequence if }
737
set Comprehension :
set for
A = { for i in sequence for j in sequence if }
738
dict comprehension
739
Dict Comprehension
A = { for (k,v) in sequence if }
740
Dict Comprehension :
dict comprehension
A = { for i in sequence if }
741
dict Comprehension :
dict for
A = { for i in sequence for j in sequence if }
742
2.24 Generator
743
generator
744
Generator
tuple(immutable) comprehension syntax generator
745
Generator
generator next . StopIteration
746
generator
747
Generator : send
send None
748
2.25 __bulitins__ class
749
__builtins__/ class
750
class :
__builtins__ class
751
class :
__builtins__ class
752
Ellipsis class
753
[] Ellipsis
754
doctest
#doctest Ellipsis
755
2.26 ()
756
enumerate class
757
enumerate index value
758
iterable enumerate index
dict key value
759
reserved class
760
reversed reverse iterator
761
iterable reversed
762
2.27 (buffer)
763
buffer class
764
buffer call interface (strings,arrays, buffers ) object .
765
buffer slice
766
list buffer
767
memoryview class
768
Buffer interface .
769
view
770
2.28 (array)
771
bytearray
772
: Bytearray
Bytearray index/slice
773
array
774
: Array
Array array index slicing
775
2.29 (queue)
776
Heap queue
777
heapq
heapq
778
heappush
Heap
779
heappush:
heapq list
780
heappop
Head
781
heappush/heappop: list
list heap
782
heappush/heappop:
heapq for/while push/pop
783
heappushpop
heap push pop
784
nlargest
heap
785
nsmallest
heap
786
dict heapq
heapq dict key
787
heapify
heapify .
788
collections.deque
789
queue class
Deque object
790
Deque iterable
deque
791
queue
queue
792
Deque list
deque : list
793
2.30 (dict)
794
Key: multi- value
795
collections.defualdict
defualtdict
796
Dictionary
797
collections.OrderedDict linked list
Ordereddict
798
collections.itemgetter
799
dict key key item getter class
itemgetter
800
fname key key itg dict
Itemgetter
801
itemgetter dict list sorted
Itemgetter sorted
802
collections.attrgetter
803
class
attrgetter
804
attrgetter class
attrgetter
805
attrgetter list sorted
attrgetter sorted
806
3.Python
Moon Yong Joon
807
3.1Python
808
Building Block
809
(\) :
: intention
: (\n)
(#) :
Doc : single ('), double (") and triple (''' or """) quotes .__doc__
(;) : ;
810
docstring
811
docstring
doc
812
3.2 PythonControl flow
813
Control flow
814
if Statement
StatementDescriptionif statements true if...else statements true if false else nested if statementsIf elif true false else815
Control
816
if only :
true
817
if else :
True/False
818
if elif else :
True/False elif
819
nested
820
if :
if if
821
(3)
822
if Statement :
if (:)
823
3.3 PythonLoop flow
824
Loop flow
825
Loop Statement
Loop TypeDescriptionwhile loop true for in loop sequence nested loops826
For :
For iterable _ for
827
Loop
828
Break Statement
loop flow
829
Continue Statement
control flow
830
Break
831
else Statement : for/while
For/while else ( break )
832
3.4 Pythonwith
833
with
834
With Statement
with context , close
835
Context special method
836
file : __enter__/__exit__
__enter__/__exit__
837
file : __enter__/__exit__
__exit__
838
File: close
close
839
3.5 Pythonpass
840
pass
841
Pass Statement
pass
Continue pass
842
4.Python /
Moon Yong Joon
843
4.1 import
844
845
sys.modules
846
__import__
847
__import__
import
848
__import__
math import __import__ . Math.cos (__module__)
849
__import__
850
851
import: __import__
__import__ import add globals
852
4.2 Python namespace
853
Namespace
854
Namespace
, , name .
, , name , , ,
855
Namespace
Import , pythonpath .
856
Namespace
dir() : , list
__dict__ :
>>>dir()
>>>dir()
>>>.__dict__
>>>
857
Namespace :
858
Namespace :
859
Namespace :
860
function Namespace
Namespace
Namespace .
Namespace .
locals()/globals()
Dict{}
Dict{}
Dict{}
Dict{}
Dict{}
Built-in
Dict{}
861
Namespace :
local global
862
Namespace :
function class
863
Namespace : object
864
Object Namespace
Base class
class
instance
instance
instance
Dict{}
Dict{}
Dict{}
Dict{}
Dict{}
Namespace
Namespace
865
Namespace :
Class instance
866
4.3 Python/
867
Module
868
, , , (.)
869
Module
AttributeDescription__doc__documentation string__file__filename (missing for built-in modules)870
Module
871
help() : module
help()
872
package
873
(Packages) ('.') ( )
import game.sound.echo # ..
from game.sound import echo
from game.sound.echo import echo_test # ..
import .echo # import
import ..echo # import
game/
__init__.py #
sound/ __init__.py echo.py wav.py
graphic/ __init__.py screen.py render.py
play/ __init__.py run.py test.py
874
(1)
1. Kakao pythonpath
2. account
3. account account.py
875
(2)
1. myproject pythonpath
2. add_test.py
3. account.account import
876
Python path
877
:pythonpath
pythonpath
set PYTHONPATH=c:\python20\lib;
878
: ide path
.
#path
>>> import sys
>>> sys.path
['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\
\Python34', 'c:\\Python34\\lib\\site-packages']
#
>>> sys.path.append("C:/Python/Mymodules")
>>> sys.path
['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\\Python34', 'c:\\Python34\\lib\\site-packages', 'C:/Python/Mymodules']
>>>
>>> import mod2
>>> print(mod2.sum(3,4)) # 7
879
4.4 Python /
880
Context
881
if __name__ == "__main__":
__main__
882
command line
__name__ __main__
import
if __name__ == "__main__": #
print(safe_sum('a', 1))
print(safe_sum(1, 4))
print(sum(10, 10.4))
else : # import
883
Import
884
namespace
.
Namespace : .__dict__
: .__dict__.get()
885
4.5 Command
886
Command
887
Command line
$ python h # command help
usage: python [-BdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]
OptionDescription-dprovide debug output-Ogenerate optimized bytecode (resulting in .pyo files)-Sdo not run import site to look for Python paths on startup-vverbose output (detailed trace on import statements)-Xdisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6-c cmdrun Python script sent in as cmd stringfilerun Python script from given file888
Command line -
$ python test.py arg1 arg2 arg3
#!/usr/bin/python import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
test.py
test.py
Sys argv
sys.argv[1]
#
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
889
PIP command
Command
Pip [options] []
890
PIP :
C:\Python27\Lib\site-packages
891
PIP :
flask
892
Jupyter notebook cell
893
Pip list
Pip list
894
Pip
!pip install -upgrade
895
Python
!python
896
5.Python
Moon Yong Joon
897
5.1
Moon Yong Joon
898
Function
899
()
Return
900
(def)
def add (x,y) :
(return/yield) []
901
( , , )
902
/
903
Function
904
comment __doc__
905
Function Scope
906
Scoping
.
Local > global > Built-in
Global/nonlocal
global
Built-in
Scope
Namespace
local
local
907
-scope
dictionary
/
locals()
#
908
local
local dict
909
global
global
910
Return
911
-None
Return
None
912
None
913
Return
914
-return
Tuple .
915
Return
Return
def f_ex
return add(5,5)
def f_tr
return add
def add(x,y) :
return x+y
916
-return
917
Yield
918
-yield
return yield Generator
yield , ', ' .
yield , next() iteration ,
919
5.2
Moon Yong Joon
920
Function
921
class
function function type class
922
function class code class
923
def add(x,y) :
return x+y
add
def add(x,y) :
return x+y
{x : None, y:None}
924
:
function type code type
function type
code type
func_code
.
func_code : code type
.
.
925
?
function class instance, code code class
926
Function
927
function class class
def add(x,y) :
return x+y
object
function
code
'co_argcount',
'co_cellvars',
'co_code',
'co_consts',
'co_filename',
'co_firstlineno',
'co_flags',
'co_freevars',
'co_lnotab',
'co_name',
'co_names',
'co_nlocals',
'co_stacksize',
'co_varnames'
'
'__class__',
'__delattr__',
'__doc__',
'__format__',
'__getattribute__',
'func_closure',
'func_code',
'func_defaults',
'func_dict',
'func_doc',
'func_globals',
'func_name'
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__'
'__hash__',
'__init__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__call__',
'__closure__',
'__code__',
'__defaults__',
'__dict__',
'__get__',
'__globals__',
'__module__',
'__name__',
928
Function
AttributeDescription__doc__ doc __name__ func_code byte code code func_defaults arguments defult func_doc __doc__ func_globals func_name __name__929
Function :
Function type
930
: default
Function __defaults__ default
931
:
Function special method
Python 2(func)Python 2(special)a_function.func_namea_function.__name__a_function.func_doca_function.__doc__a_function.func_defaultsa_function.__defaults__a_function.func_dicta_function.__dict__a_function.func_closurea_function.__closure__a_function.func_globalsa_function.__globals__a_function.func_codea_function.__code__932
: 1
, defaults, code
933
: 2
934
: 3
namespace , doc, global namespace
935
Function class: 3
936
: 3.x
3 function
Python 2Python 3a_function.func_name/__name__a_function.__name__a_function.func_doc/__doc__a_function.__doc__a_function.func_defaults/__defauts__a_function.__defaults__a_function.func_dict/__dict__a_function.__dict__a_function.func_closure/__closure__a_function.__closure__a_function.func_globals/__globals__a_function.__globals__a_function.func_code/__code__a_function.__code__937
: 3.x
3 function
938
defaults
default default .
939
Inspect
940
inspect :
Inspect
functionDescriptioninspect.getdoc(object) object doc inspect.getsourcefile(object) object (0 inspect.getmodule(object) object inspect.getsource(object) object inspect.getsourcelines(object) object inspect.getargspec(func) argument inspect.getcallargs(func[, *args][, **kwds]) argument941
inspect :
Inspect
942
inspect : argument
Inspect argument
943
inspect :signature
3 annotation signature( )
functionDescriptioninspect.signature()944
945
( ( ) )
()
def ( ) :
(return/yield)
object
function
code
946
__call__
def add(x,y) :
return x+y
>>> add(5,5)
>>> add.__call__(5,5)
>>> add
add
947
Stack
stack
1
2
3
4
Stack
load
948
.
949
5.3 InteranAltype
Moon Yong Joon
950
Code
951
Code
code
AttributeDescriptionco_argcount number of arguments (not including * or ** args)co_codestring of raw compiled bytecodeco_consts tuple of constants used in the bytecodco_filename name of file in which this code object was createdco_firstlineno number of first line in Python source codeco_flags bitmap: 1=optimized|2=newlocals|4=*arg|8=**argco_lnotab encoded mapping of line numbers to bytecode indicesco_namename with which this code object was definedco_namestuple of names of local variablesco_nlocalsnumber of local variablesco_stacksizevirtual machine stack space requiredco_varnamestuple of names of arguments and local variables952
:
, func_code(code )
953
Frame class
954
frame class
frame class
f_backnext outer frame object (this frames caller)f_builtinsbuiltins namespace seen by this framef_codecode object being executed in this framef_exc_tracebacktraceback if raised in this frame, orNonef_exc_typeexception type if raised in this frame, orNonef_exc_valueexception value if raised in this frame, orNonef_globalsglobal namespace seen by this framef_lastiindex of last attempted instruction in bytecodef_linenocurrent line number in Python source codef_localslocal namespace seen by this framef_restricted0 or 1 if frame is in restricted execution modef_tracetracing function for this frame, orNone955
frame
.
956
frame
Getframeinfo, getsource frame
957
frame
Frame .
958
5.4 1
Moon Yong Joon
959
1
960
First Class Object
First Class .
(variable)
(parameter)
(return value)
function
961
First Class Object :
1 (first class object)
(runtime)
(anonymous)
962
1
963
First Class Object :
()
964
First Class Object :
965
First Class Object : return
966
5.5 Function scope
Moon Yong Joon
967
Function variable scope
968
Scoping
.
Local > global > Built-in
Global/nonlocal
global
Built-in
Scope
Namespace
local
local
969
-scope
dictionary
/
locals()
#
970
locals()
971
locals()
locals()
dict
972
global
973
globals()
global module . Import global global 2
974
global
975
global : immutable
global
976
Global : mutable
mutable()
Mutable swap()
Return
977
5.6
Moon Yong Joon
978
Parameter/argment
979
4
/
/
(x,y,z)
/
/
/
980
(position)
981
(key/value)
key/value
982
-Namespace :
Namespace dict
983
(key/value)
984
key=value
985
986
987
Inspect getcallargs
getcallargs(,,)
988
:
989
Default
default __defaults__ (tuple)
def (k= 10)
__defaults__
(10,)
990
-
add
{x: 10, y:None}
#
add
{x: 1, y: 20}
#
add
{x: 10, y: 20}
991
default
992
Default
None
def f(a, l=[]) :
l.append(a)
return l
f(1)
f(2)
f(3)
{ a:1, l :[1]}
{ a:2, l :[1,2]}
{ a:2, l :[1,2,3]}
f(1)
f(2)
f(3)
List
.
def f(a, l=None) :
l = []
l.append(a)
return l
993
Default
defaults tuple tuple
994
Default mutable
default default .
995
5.7
Moon Yong Joon
996
(tuple)
997
*args namespace args(key), (value)
998
args key tuple value
999
(dict)
1000
-
**kargs keyword
1001
5.8
Moon Yong Joon
1002
1003
, , ,
1004
/
1005
: +
1006
: +
1007
/
1008
:
*args, **kargs *args **kargs
1009
: list
*args, **kargs (python 3. list(kargs.values()) )
1010
: dict
1011
, /
1012
1013
5.9 unpack
Moon Yong Joon
1014
unpack
1015
dict *args tuple, **kargs dict
1016
Unpack
1017
unpack
tuple/list * unpack
Python3 dict list
1018
unpack
dict ** unpack
1019
tuple
1020
tuple
tuple *args
call by sharing
1021
*args
.
1022
Dict
1023
dict
dict dict dict
call by sharing
1024
**kwargs
** dict
1025
5.10
Moon Yong Joon
1026
Apply
1027
Apply
apply *args, **kwargs
apply (, )
*args, **kargs
1028
Add add apply
1029
1030
Global :
(global )
{add: function }
{x:None, y:None}
{x:5, y:5}
global
local()
local()
1031
(global)
{add: function , add_args: function}
{func:None, x:None, y:None}
{func: add, x:5, y:5}
global
local()
local()
1032
1033
Lambda
1034
1035
()
(iteration, generation)
1036
stack
1037
Iteration :
sequence iter() iterator
1038
Iteration :
sequence iter() iterator
1039
Generation : comprehension
Generator comprehension
exception
1040
Generation :function
exception
1041
5.11 generator
Moon Yong Joon
1042
Generator
1043
Generator
generator next next
1044
Generator :
Yield
1045
Generator :
Return Yield
(next())
exception
1046
Coroutine
1047
Coroutine : send
yield send
Yield send
1048
Generator :
Generator send
( )
1049
5.12 Lambda()
Moon Yong Joon
1050
1051
Lambda
Lambda (return )
Lambda :
()
1052
Lambda
Python 2Python 3lambda(x,):x+f(x)lambdax1:x1[0]+f(x1[0])lambda(x,y):x+f(y)lambdax_y:x_y[0]+f(x_y[1])lambda(x,(y,z)):x+y+zlambdax_y_z:x_y_z[0]+x_y_z[1][0]+x_y_z[1][1]lambdax,y,z:x+y+zunchanged1053
Lambda
Lambda (return )
Lambda :
lambda __name__ lambda
1054
Lambda vs.
1055
lambda (return)
def () :
retun
lambda :
Lambda
1056
lambda lambda
Lambda
1057
Lambda namespace
1058
Namespace scope
lambda namespace
Local > global> builtin
1059
Parameter
1060
/
Lambda
1061
-
Lambda *args
1062
/
Lambda **kargs dict
**d **kargs = **d
/ kargs
1063
If
1064
Lambda if
Lambda if True if
lambda :(if True) if else (False )
1065
1066
Lambda
Lambda and/or
and :
or :
1067
Lambda :
1068
1069
Lambda
Lambda
= Lambda :
()
(Lambda : )()
1070
Lambda :
Lambda ,
1071
Lambda
lambda return tuple
1072
Lambda :
Lambda return
1073
5.13 Lambda()
Moon Yong Joon
1074
List Comprehensions
1075
Comprehensions
Lambda
1076
: conprehension
Lambda comprehensions lambda
1077
lambda
1078
Lambda for
Lambda for map/reduce/filter
map
reduce
filter
filter
1079
Map : 2
Lambda sequence
1080
Map : 3
3 class list list
1081
reduce : 2
Lambda sequence
11
22
33
44
33
66
110
1082
reduce : 3
functools reduce
1083
filter : 2
Sequence lambda
1084
filter : 3
3 class list list
1085
Nested lambda
1086
lambda
Lambda
1087
:lambda
1088
Lambda lambda
1089
5.14 Builtin (__builtins__)
Moon Yong Joon
1090
__builtins__ function
1091
: 2.x
2.x class
1092
: 2.7
__builtins__ function
1093
: 3.x