Changeset 391 for python/trunk/Doc/tutorial/controlflow.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/tutorial/controlflow.rst
r2 r391 60 60 61 61 >>> # Measure some strings: 62 ... a= ['cat', 'window', 'defenestrate']63 >>> for x in a:64 ... print x, len(x)62 ... words = ['cat', 'window', 'defenestrate'] 63 >>> for w in words: 64 ... print w, len(w) 65 65 ... 66 66 cat 3 … … 68 68 defenestrate 12 69 69 70 I t is not safe to modify the sequence being iterated over in the loop (this can71 only happen for mutable sequence types, such as lists). If you need to modify 72 the list you are iterating over (for example, to duplicate selected items) you 73 must iterate over a copy. The slice notation makes this particularly 74 convenient:: 75 76 >>> for x in a[:]: # make a slice copy of the entire list77 ... if len(x) > 6: a.insert(0, x)78 ... 79 >>> a70 If you need to modify the sequence you are iterating over while inside the loop 71 (for example to duplicate selected items), it is recommended that you first 72 make a copy. Iterating over a sequence does not implicitly make a copy. The 73 slice notation makes this especially convenient:: 74 75 >>> for w in words[:]: # Loop over a slice copy of the entire list. 76 ... if len(w) > 6: 77 ... words.insert(0, w) 78 ... 79 >>> words 80 80 ['defenestrate', 'cat', 'window', 'defenestrate'] 81 81 … … 129 129 The :keyword:`break` statement, like in C, breaks out of the smallest enclosing 130 130 :keyword:`for` or :keyword:`while` loop. 131 132 The :keyword:`continue` statement, also borrowed from C, continues with the next133 iteration of the loop.134 131 135 132 Loop statements may have an ``else`` clause; it is executed when the loop … … 156 153 8 equals 2 * 4 157 154 9 equals 3 * 3 155 156 (Yes, this is the correct code. Look closely: the ``else`` clause belongs to 157 the :keyword:`for` loop, **not** the :keyword:`if` statement.) 158 159 When used with a loop, the ``else`` clause has more in common with the 160 ``else`` clause of a :keyword:`try` statement than it does that of 161 :keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs 162 when no exception occurs, and a loop's ``else`` clause runs when no ``break`` 163 occurs. For more on the :keyword:`try` statement and exceptions, see 164 :ref:`tut-handling`. 165 166 The :keyword:`continue` statement, also borrowed from C, continues with the next 167 iteration of the loop:: 168 169 >>> for num in range(2, 10): 170 ... if num % 2 == 0: 171 ... print "Found an even number", num 172 ... continue 173 ... print "Found a number", num 174 Found an even number 2 175 Found a number 3 176 Found an even number 4 177 Found a number 5 178 Found an even number 6 179 Found a number 7 180 Found an even number 8 181 Found a number 9 158 182 159 183 … … 381 405 ----------------- 382 406 383 Functions can also be called using keyword arguments of the form ``keyword =384 value``. For instance, the following function::407 Functions can also be called using :term:`keyword arguments <keyword argument>` 408 of the form ``kwarg=value``. For instance, the following function:: 385 409 386 410 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): … … 390 414 print "-- It's", state, "!" 391 415 392 could be called in any of the following ways:: 393 394 parrot(1000) 395 parrot(action = 'VOOOOOM', voltage = 1000000) 396 parrot('a thousand', state = 'pushing up the daisies') 397 parrot('a million', 'bereft of life', 'jump') 398 399 but the following calls would all be invalid:: 416 accepts one required argument (``voltage``) and three optional arguments 417 (``state``, ``action``, and ``type``). This function can be called in any 418 of the following ways:: 419 420 parrot(1000) # 1 positional argument 421 parrot(voltage=1000) # 1 keyword argument 422 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments 423 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments 424 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments 425 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword 426 427 but all the following calls would be invalid:: 400 428 401 429 parrot() # required argument missing 402 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword 403 parrot(110, voltage=220) # duplicate value for argument 404 parrot(actor='John Cleese') # unknown keyword 405 406 In general, an argument list must have any positional arguments followed by any 407 keyword arguments, where the keywords must be chosen from the formal parameter 408 names. It's not important whether a formal parameter has a default value or 409 not. No argument may receive a value more than once --- formal parameter names 410 corresponding to positional arguments cannot be used as keywords in the same 411 calls. Here's an example that fails due to this restriction:: 430 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument 431 parrot(110, voltage=220) # duplicate value for the same argument 432 parrot(actor='John Cleese') # unknown keyword argument 433 434 In a function call, keyword arguments must follow positional arguments. 435 All the keyword arguments passed must match one of the arguments 436 accepted by the function (e.g. ``actor`` is not a valid argument for the 437 ``parrot`` function), and their order is not important. This also includes 438 non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). 439 No argument may receive a value more than once. 440 Here's an example that fails due to this restriction:: 412 441 413 442 >>> def function(a): … … 430 459 print "-- Do you have any", kind, "?" 431 460 print "-- I'm sorry, we're all out of", kind 432 for arg in arguments: print arg 461 for arg in arguments: 462 print arg 433 463 print "-" * 40 434 keys = keywords.keys()435 keys.sort()436 for kw in keys:print kw, ":", keywords[kw]464 keys = sorted(keywords.keys()) 465 for kw in keys: 466 print kw, ":", keywords[kw] 437 467 438 468 It could be called like this:: … … 455 485 sketch : Cheese Shop Sketch 456 486 457 Note that the :meth:`sort` method of the list of keyword argument names is 458 called before printing the contents of the ``keywords`` dictionary; if this is 459 not done, the order in which the arguments are printed is undefined. 460 487 Note that the list of keyword argument names is created by sorting the result 488 of the keywords dictionary's ``keys()`` method before printing its contents; 489 if this is not done, the order in which the arguments are printed is undefined. 461 490 462 491 .. _tut-arbitraryargs: … … 513 542 .. _tut-lambda: 514 543 515 Lambda Forms 516 ------------ 517 518 By popular demand, a few features commonly found in functional programming 519 languages like Lisp have been added to Python. With the :keyword:`lambda` 520 keyword, small anonymous functions can be created. Here's a function that 521 returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be 522 used wherever function objects are required. They are syntactically restricted 523 to a single expression. Semantically, they are just syntactic sugar for a 524 normal function definition. Like nested function definitions, lambda forms can 525 reference variables from the containing scope:: 544 Lambda Expressions 545 ------------------ 546 547 Small anonymous functions can be created with the :keyword:`lambda` keyword. 548 This function returns the sum of its two arguments: ``lambda a, b: a+b``. 549 Lambda functions can be used wherever function objects are required. They are 550 syntactically restricted to a single expression. Semantically, they are just 551 syntactic sugar for a normal function definition. Like nested function 552 definitions, lambda functions can reference variables from the containing 553 scope:: 526 554 527 555 >>> def make_incrementor(n): … … 533 561 >>> f(1) 534 562 43 563 564 The above example uses a lambda expression to return a function. Another use 565 is to pass a small function as an argument:: 566 567 >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] 568 >>> pairs.sort(key=lambda pair: pair[1]) 569 >>> pairs 570 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] 535 571 536 572
Note:
See TracChangeset
for help on using the changeset viewer.