Changeset 391 for python/trunk/Doc/tutorial
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 15 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/classes.rst
r2 r391 5 5 ******* 6 6 7 Python's class mechanism adds classes to the language with a minimum of new 8 syntax and semantics. It is a mixture of the class mechanisms found in C++ and 9 Modula-3. As is true for modules, classes in Python do not put an absolute 10 barrier between definition and user, but rather rely on the politeness of the 11 user not to "break into the definition." The most important features of classes 12 are retained with full power, however: the class inheritance mechanism allows 7 Compared with other programming languages, Python's class mechanism adds classes 8 with a minimum of new syntax and semantics. It is a mixture of the class 9 mechanisms found in C++ and Modula-3. Python classes provide all the standard 10 features of Object Oriented Programming: the class inheritance mechanism allows 13 11 multiple base classes, a derived class can override any methods of its base 14 12 class or classes, and a method can call the method of a base class with the same 15 name. Objects can contain an arbitrary amount of data. 16 17 In C++ terminology, all class members (including the data members) are *public*, 18 and all member functions are *virtual*. As in Modula-3, there are no shorthands 19 for referencing the object's members from its methods: the method function is 20 declared with an explicit first argument representing the object, which is 21 provided implicitly by the call. As in Smalltalk, classes themselves are 22 objects. This provides semantics for importing and renaming. Unlike C++ and 23 Modula-3, built-in types can be used as base classes for extension by the user. 24 Also, like in C++, most built-in operators with special syntax (arithmetic 25 operators, subscripting etc.) can be redefined for class instances. 13 name. Objects can contain arbitrary amounts and kinds of data. As is true for 14 modules, classes partake of the dynamic nature of Python: they are created at 15 runtime, and can be modified further after creation. 16 17 In C++ terminology, normally class members (including the data members) are 18 *public* (except see below :ref:`tut-private`), and all member functions are 19 *virtual*. As in Modula-3, there are no shorthands for referencing the object's 20 members from its methods: the method function is declared with an explicit first 21 argument representing the object, which is provided implicitly by the call. As 22 in Smalltalk, classes themselves are objects. This provides semantics for 23 importing and renaming. Unlike C++ and Modula-3, built-in types can be used as 24 base classes for extension by the user. Also, like in C++, most built-in 25 operators with special syntax (arithmetic operators, subscripting etc.) can be 26 redefined for class instances. 26 27 27 28 (Lacking universally accepted terminology to talk about classes, I will make … … 65 66 implemented as Python dictionaries, but that's normally not noticeable in any 66 67 way (except for performance), and it may change in the future. Examples of 67 namespaces are: the set of built-in names ( functions such as :func:`abs`, and68 namespaces are: the set of built-in names (containing functions such as :func:`abs`, and 68 69 built-in exception names); the global names in a module; and the local names in 69 70 a function invocation. In a sense the set of attributes of an object also form … … 409 410 410 411 Methods may reference global names in the same way as ordinary functions. The 411 global scope associated with a method is the module containing the class412 definition. ( The class itselfis never used as a global scope.) While one412 global scope associated with a method is the module containing its 413 definition. (A class is never used as a global scope.) While one 413 414 rarely encounters a good reason for using global data in a method, there are 414 415 many legitimate uses of the global scope: for one thing, functions and modules … … 518 519 519 520 With new-style classes, dynamic ordering is necessary because all cases of 520 multiple inheritance exhibit one or more diamond relationships (where oneat521 multiple inheritance exhibit one or more diamond relationships (where at 521 522 least one of the parent classes can be accessed through multiple paths from the 522 523 bottommost class). For example, all new-style classes inherit from … … 534 535 .. _tut-private: 535 536 536 Private Variables 537 ================= 537 Private Variables and Class-local References 538 ============================================ 538 539 539 540 "Private" instance variables that cannot be accessed except from inside an 540 object ,don't exist in Python. However, there is a convention that is followed541 object don't exist in Python. However, there is a convention that is followed 541 542 by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should 542 543 be treated as a non-public part of the API (whether it is a function, a method … … 553 554 occurs within the definition of a class. 554 555 556 Name mangling is helpful for letting subclasses override methods without 557 breaking intraclass method calls. For example:: 558 559 class Mapping: 560 def __init__(self, iterable): 561 self.items_list = [] 562 self.__update(iterable) 563 564 def update(self, iterable): 565 for item in iterable: 566 self.items_list.append(item) 567 568 __update = update # private copy of original update() method 569 570 class MappingSubclass(Mapping): 571 572 def update(self, keys, values): 573 # provides new signature for update() 574 # but does not break __init__() 575 for item in zip(keys, values): 576 self.items_list.append(item) 577 555 578 Note that the mangling rules are designed mostly to avoid accidents; it still is 556 579 possible to access or modify a variable that is considered private. This can … … 587 610 passed a class that emulates the methods of that data type instead. For 588 611 instance, if you have a function that formats some data from a file object, you 589 can define a class with methods :meth:`read` and :meth:` readline` that get the612 can define a class with methods :meth:`read` and :meth:`!readline` that get the 590 613 data from a string buffer instead, and pass it as an argument. 591 614 … … 666 689 print char 667 690 for line in open("myfile.txt"): 668 print line 691 print line, 669 692 670 693 This style of access is clear, concise, and convenient. The use of iterators 671 694 pervades and unifies Python. Behind the scenes, the :keyword:`for` statement 672 695 calls :func:`iter` on the container object. The function returns an iterator 673 object that defines the method :meth:`next` which accesses elements in the 674 container one at a time. When there are no more elements, :meth:`next` raises a 675 :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate. 696 object that defines the method :meth:`~iterator.next` which accesses elements 697 in the container one at a time. When there are no more elements, 698 :meth:`~iterator.next` raises a :exc:`StopIteration` exception which tells the 699 :keyword:`for` loop to terminate. 676 700 This example shows how it all works:: 677 701 … … 687 711 'c' 688 712 >>> it.next() 689 690 713 Traceback (most recent call last): 691 714 File "<stdin>", line 1, in ? … … 694 717 695 718 Having seen the mechanics behind the iterator protocol, it is easy to add 696 iterator behavior to your classes. Define a :meth:`__iter__` method which719 iterator behavior to your classes. Define an :meth:`__iter__` method which 697 720 returns an object with a :meth:`next` method. If the class defines 698 721 :meth:`next`, then :meth:`__iter__` can just return ``self``:: 699 722 700 723 class Reverse: 701 " Iterator for looping over a sequence backwards"724 """Iterator for looping over a sequence backwards.""" 702 725 def __init__(self, data): 703 726 self.data = data … … 711 734 return self.data[self.index] 712 735 713 >>> for char in Reverse('spam'): 736 :: 737 738 >>> rev = Reverse('spam') 739 >>> iter(rev) 740 <__main__.Reverse object at 0x00A1DB50> 741 >>> for char in rev: 714 742 ... print char 715 743 ... … … 735 763 for index in range(len(data)-1, -1, -1): 736 764 yield data[index] 765 766 :: 737 767 738 768 >>> for char in reverse('golf'): -
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 -
python/trunk/Doc/tutorial/datastructures.rst
r2 r391 171 171 the sequence for which ``function(item)`` is true. If *sequence* is a 172 172 :class:`string` or :class:`tuple`, the result will be of the same type; 173 otherwise, it is always a :class:`list`. For example, to compute some primes:: 173 otherwise, it is always a :class:`list`. For example, to compute a sequence of 174 numbers not divisible by 2 or 3:: 174 175 175 176 >>> def f(x): return x % 2 != 0 and x % 3 != 0 … … 229 230 and works exactly like this. 230 231 231 .. versionadded:: 2.3 232 232 .. _tut-listcomps: 233 233 234 234 List Comprehensions 235 235 ------------------- 236 236 237 List comprehensions provide a concise way to create lists without resorting to 238 use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list 239 definition tends often to be clearer than lists built using those constructs. 240 Each list comprehension consists of an expression followed by a :keyword:`for` 241 clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result 242 will be a list resulting from evaluating the expression in the context of the 243 :keyword:`for` and :keyword:`if` clauses which follow it. If the expression 244 would evaluate to a tuple, it must be parenthesized. :: 245 237 List comprehensions provide a concise way to create lists. 238 Common applications are to make new lists where each element is the result of 239 some operations applied to each member of another sequence or iterable, or to 240 create a subsequence of those elements that satisfy a certain condition. 241 242 For example, assume we want to create a list of squares, like:: 243 244 >>> squares = [] 245 >>> for x in range(10): 246 ... squares.append(x**2) 247 ... 248 >>> squares 249 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 250 251 We can obtain the same result with:: 252 253 squares = [x**2 for x in range(10)] 254 255 This is also equivalent to ``squares = map(lambda x: x**2, range(10))``, 256 but it's more concise and readable. 257 258 A list comprehension consists of brackets containing an expression followed 259 by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if` 260 clauses. The result will be a new list resulting from evaluating the expression 261 in the context of the :keyword:`for` and :keyword:`if` clauses which follow it. 262 For example, this listcomp combines the elements of two lists if they are not 263 equal:: 264 265 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] 266 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 267 268 and it's equivalent to: 269 270 >>> combs = [] 271 >>> for x in [1,2,3]: 272 ... for y in [3,1,4]: 273 ... if x != y: 274 ... combs.append((x, y)) 275 ... 276 >>> combs 277 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 278 279 Note how the order of the :keyword:`for` and :keyword:`if` statements is the 280 same in both these snippets. 281 282 If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), 283 it must be parenthesized. :: 284 285 >>> vec = [-4, -2, 0, 2, 4] 286 >>> # create a new list with the values doubled 287 >>> [x*2 for x in vec] 288 [-8, -4, 0, 4, 8] 289 >>> # filter the list to exclude negative numbers 290 >>> [x for x in vec if x >= 0] 291 [0, 2, 4] 292 >>> # apply a function to all the elements 293 >>> [abs(x) for x in vec] 294 [4, 2, 0, 2, 4] 295 >>> # call a method on each element 246 296 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] 247 297 >>> [weapon.strip() for weapon in freshfruit] 248 298 ['banana', 'loganberry', 'passion fruit'] 249 >>> vec = [2, 4, 6] 250 >>> [3*x for x in vec] 251 [6, 12, 18] 252 >>> [3*x for x in vec if x > 3] 253 [12, 18] 254 >>> [3*x for x in vec if x < 2] 255 [] 256 >>> [[x,x**2] for x in vec] 257 [[2, 4], [4, 16], [6, 36]] 258 >>> [x, x**2 for x in vec] # error - parens required for tuples 259 File "<stdin>", line 1, in ? 260 [x, x**2 for x in vec] 299 >>> # create a list of 2-tuples like (number, square) 300 >>> [(x, x**2) for x in range(6)] 301 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] 302 >>> # the tuple must be parenthesized, otherwise an error is raised 303 >>> [x, x**2 for x in range(6)] 304 File "<stdin>", line 1 305 [x, x**2 for x in range(6)] 261 306 ^ 262 307 SyntaxError: invalid syntax 263 >>> [(x, x**2) for x in vec] 264 [(2, 4), (4, 16), (6, 36)] 265 >>> vec1 = [2, 4, 6] 266 >>> vec2 = [4, 3, -9] 267 >>> [x*y for x in vec1 for y in vec2] 268 [8, 6, -18, 16, 12, -36, 24, 18, -54] 269 >>> [x+y for x in vec1 for y in vec2] 270 [6, 5, -7, 8, 7, -5, 10, 9, -3] 271 >>> [vec1[i]*vec2[i] for i in range(len(vec1))] 272 [8, 12, -54] 273 274 List comprehensions are much more flexible than :func:`map` and can be applied 275 to complex expressions and nested functions:: 276 277 >>> [str(round(355/113.0, i)) for i in range(1,6)] 308 >>> # flatten a list using a listcomp with two 'for' 309 >>> vec = [[1,2,3], [4,5,6], [7,8,9]] 310 >>> [num for elem in vec for num in elem] 311 [1, 2, 3, 4, 5, 6, 7, 8, 9] 312 313 List comprehensions can contain complex expressions and nested functions:: 314 315 >>> from math import pi 316 >>> [str(round(pi, i)) for i in range(1, 6)] 278 317 ['3.1', '3.14', '3.142', '3.1416', '3.14159'] 279 318 280 319 281 320 Nested List Comprehensions 282 -------------------------- 283 284 If you've got the stomach for it, list comprehensions can be nested. They are a 285 powerful tool but -- like all powerful tools -- they need to be used carefully, 286 if at all. 287 288 Consider the following example of a 3x3 matrix held as a list containing three 289 lists, one list per row:: 290 291 >>> mat = [ 292 ... [1, 2, 3], 293 ... [4, 5, 6], 294 ... [7, 8, 9], 295 ... ] 296 297 Now, if you wanted to swap rows and columns, you could use a list 298 comprehension:: 299 300 >>> print [[row[i] for row in mat] for i in [0, 1, 2]] 301 [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 302 303 Special care has to be taken for the *nested* list comprehension: 304 305 To avoid apprehension when nesting list comprehensions, read from right to 306 left. 307 308 A more verbose version of this snippet shows the flow explicitly:: 309 310 for i in [0, 1, 2]: 311 for row in mat: 312 print row[i], 313 print 314 315 In real world, you should prefer built-in functions to complex flow statements. 321 '''''''''''''''''''''''''' 322 323 The initial expression in a list comprehension can be any arbitrary expression, 324 including another list comprehension. 325 326 Consider the following example of a 3x4 matrix implemented as a list of 327 3 lists of length 4:: 328 329 >>> matrix = [ 330 ... [1, 2, 3, 4], 331 ... [5, 6, 7, 8], 332 ... [9, 10, 11, 12], 333 ... ] 334 335 The following list comprehension will transpose rows and columns:: 336 337 >>> [[row[i] for row in matrix] for i in range(4)] 338 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] 339 340 As we saw in the previous section, the nested listcomp is evaluated in 341 the context of the :keyword:`for` that follows it, so this example is 342 equivalent to:: 343 344 >>> transposed = [] 345 >>> for i in range(4): 346 ... transposed.append([row[i] for row in matrix]) 347 ... 348 >>> transposed 349 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] 350 351 which, in turn, is the same as:: 352 353 >>> transposed = [] 354 >>> for i in range(4): 355 ... # the following 3 lines implement the nested listcomp 356 ... transposed_row = [] 357 ... for row in matrix: 358 ... transposed_row.append(row[i]) 359 ... transposed.append(transposed_row) 360 ... 361 >>> transposed 362 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] 363 364 365 In the real world, you should prefer built-in functions to complex flow statements. 316 366 The :func:`zip` function would do a great job for this use case:: 317 367 318 >>> zip(*mat)319 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]368 >>> zip(*matrix) 369 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] 320 370 321 371 See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. … … 373 423 >>> u 374 424 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) 425 >>> # Tuples are immutable: 426 ... t[0] = 88888 427 Traceback (most recent call last): 428 File "<stdin>", line 1, in <module> 429 TypeError: 'tuple' object does not support item assignment 430 >>> # but they can contain mutable objects: 431 ... v = ([1, 2, 3], [3, 2, 1]) 432 >>> v 433 ([1, 2, 3], [3, 2, 1]) 434 375 435 376 436 As you see, on output tuples are always enclosed in parentheses, so that nested 377 437 tuples are interpreted correctly; they may be input with or without surrounding 378 438 parentheses, although often parentheses are necessary anyway (if the tuple is 379 part of a larger expression). 380 381 Tuples have many uses. For example: (x, y) coordinate pairs, employee records 382 from a database, etc. Tuples, like strings, are immutable: it is not possible 383 to assign to the individual items of a tuple (you can simulate much of the same 384 effect with slicing and concatenation, though). It is also possible to create 385 tuples which contain mutable objects, such as lists. 439 part of a larger expression). It is not possible to assign to the individual 440 items of a tuple, however it is possible to create tuples which contain mutable 441 objects, such as lists. 442 443 Though tuples may seem similar to lists, they are often used in different 444 situations and for different purposes. 445 Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of 446 elements that are accessed via unpacking (see later in this section) or indexing 447 (or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`). 448 Lists are :term:`mutable`, and their elements are usually homogeneous and are 449 accessed by iterating over the list. 386 450 387 451 A special problem is the construction of tuples containing 0 or 1 items: the … … 412 476 packing and sequence unpacking. 413 477 414 .. XXX Add a bit on the difference between tuples and lists.415 416 478 417 479 .. _tut-sets: … … 424 486 eliminating duplicate entries. Set objects also support mathematical operations 425 487 like union, intersection, difference, and symmetric difference. 488 489 Curly braces or the :func:`set` function can be used to create sets. Note: to 490 create an empty set you have to use ``set()``, not ``{}``; the latter creates an 491 empty dictionary, a data structure that we discuss in the next section. 426 492 427 493 Here is a brief demonstration:: … … 451 517 set(['r', 'd', 'b', 'm', 'z', 'l']) 452 518 519 Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions 520 are also supported:: 521 522 >>> a = {x for x in 'abracadabra' if x not in 'abc'} 523 >>> a 524 set(['r', 'd']) 525 453 526 454 527 .. _tut-dictionaries: … … 482 555 The :meth:`keys` method of a dictionary object returns a list of all the keys 483 556 used in the dictionary, in arbitrary order (if you want it sorted, just apply 484 the : meth:`sort` method to the list of keys). To check whether a single key is485 in thedictionary, use the :keyword:`in` keyword.557 the :func:`sorted` function to it). To check whether a single key is in the 558 dictionary, use the :keyword:`in` keyword. 486 559 487 560 Here is a small example using a dictionary:: … … 502 575 True 503 576 504 The :func:`dict` constructor builds dictionaries directly from lists of 505 key-value pairs stored as tuples. When the pairs form a pattern, list 506 comprehensions can compactly specify the key-value list. :: 577 The :func:`dict` constructor builds dictionaries directly from sequences of 578 key-value pairs:: 507 579 508 580 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) 509 581 {'sape': 4139, 'jack': 4098, 'guido': 4127} 510 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension 582 583 In addition, dict comprehensions can be used to create dictionaries from 584 arbitrary key and value expressions:: 585 586 >>> {x: x**2 for x in (2, 4, 6)} 511 587 {2: 4, 4: 16, 6: 36} 512 513 Later in the tutorial, we will learn about Generator Expressions which are even514 better suited for the task of supplying key-values pairs to the :func:`dict`515 constructor.516 588 517 589 When the keys are simple strings, it is sometimes easier to specify pairs using … … 526 598 Looping Techniques 527 599 ================== 528 529 When looping through dictionaries, the key and corresponding value can be530 retrieved at the same time using the :meth:`iteritems` method. ::531 532 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}533 >>> for k, v in knights.iteritems():534 ... print k, v535 ...536 gallahad the pure537 robin the brave538 600 539 601 When looping through a sequence, the position index and corresponding value can … … 582 644 orange 583 645 pear 646 647 When looping through dictionaries, the key and corresponding value can be 648 retrieved at the same time using the :meth:`iteritems` method. :: 649 650 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} 651 >>> for k, v in knights.iteritems(): 652 ... print k, v 653 ... 654 gallahad the pure 655 robin the brave 656 657 To change a sequence you are iterating over while inside the loop (for 658 example to duplicate certain items), it is recommended that you first make 659 a copy. Looping over a sequence does not implicitly make a copy. The slice 660 notation makes this especially convenient:: 661 662 >>> words = ['cat', 'window', 'defenestrate'] 663 >>> for w in words[:]: # Loop over a slice copy of the entire list. 664 ... if len(w) > 6: 665 ... words.insert(0, w) 666 ... 667 >>> words 668 ['defenestrate', 'cat', 'window', 'defenestrate'] 584 669 585 670 -
python/trunk/Doc/tutorial/errors.rst
r2 r391 121 121 ... pass 122 122 123 Note that the parentheses around this tuple are required, because 124 ``except ValueError, e:`` was the syntax used for what is normally 125 written as ``except ValueError as e:`` in modern Python (described 126 below). The old syntax is still supported for backwards compatibility. 127 This means ``except RuntimeError, TypeError`` is not equivalent to 128 ``except (RuntimeError, TypeError):`` but to ``except RuntimeError as 129 TypeError:`` which is not what you want. 130 123 131 The last except clause may omit the exception name(s), to serve as a wildcard. 124 132 Use this with extreme caution, since it is easy to mask a real programming error … … 132 140 s = f.readline() 133 141 i = int(s.strip()) 134 except IOError as (errno, strerror):135 print "I/O error({0}): {1}".format(e rrno,strerror)142 except IOError as e: 143 print "I/O error({0}): {1}".format(e.errno, e.strerror) 136 144 except ValueError: 137 145 print "Could not convert data to an integer." … … 178 186 ... print inst.args # arguments stored in .args 179 187 ... print inst # __str__ allows args to printed directly 180 ... x, y = inst # __getitem__ allows args to be unpacked directly188 ... x, y = inst.args 181 189 ... print 'x =', x 182 190 ... print 'y =', y … … 219 227 NameError: HiThere 220 228 221 The argument to :keyword:`raise` is an exception class or instance to be 222 raised. There is a deprecated alternate syntax that separates class and 223 constructor arguments; the above could be written as ``raise NameError, 224 'HiThere'``. Since it once was the only one available, the latter form is 225 prevalent in older code. 229 The sole argument to :keyword:`raise` indicates the exception to be raised. 230 This must be either an exception instance or an exception class (a class that 231 derives from :class:`Exception`). 226 232 227 233 If you need to determine whether an exception was raised but don't intend to … … 392 398 393 399 for line in open("myfile.txt"): 394 print line 400 print line, 395 401 396 402 The problem with this code is that it leaves the file open for an indeterminate … … 402 408 with open("myfile.txt") as f: 403 409 for line in f: 404 print line 410 print line, 405 411 406 412 After the statement is executed, the file *f* is always closed, even if a -
python/trunk/Doc/tutorial/floatingpoint.rst
r2 r391 49 49 0.0001100110011001100110011001100110011001100110011... 50 50 51 Stop at any finite number of bits, and you get an approximation. This is why 52 you see things like:: 53 54 >>> 0.1 55 0.10000000000000001 56 57 On most machines today, that is what you'll see if you enter 0.1 at a Python 58 prompt. You may not, though, because the number of bits used by the hardware to 59 store floating-point values can vary across machines, and Python only prints a 60 decimal approximation to the true decimal value of the binary approximation 61 stored by the machine. On most machines, if Python were to print the true 62 decimal value of the binary approximation stored for 0.1, it would have to 63 display :: 51 Stop at any finite number of bits, and you get an approximation. 52 53 On a typical machine running Python, there are 53 bits of precision available 54 for a Python float, so the value stored internally when you enter the decimal 55 number ``0.1`` is the binary fraction :: 56 57 0.00011001100110011001100110011001100110011001100110011010 58 59 which is close to, but not exactly equal to, 1/10. 60 61 It's easy to forget that the stored value is an approximation to the original 62 decimal fraction, because of the way that floats are displayed at the 63 interpreter prompt. Python only prints a decimal approximation to the true 64 decimal value of the binary approximation stored by the machine. If Python 65 were to print the true decimal value of the binary approximation stored for 66 0.1, it would have to display :: 64 67 65 68 >>> 0.1 66 69 0.1000000000000000055511151231257827021181583404541015625 67 70 68 instead! The Python prompt uses the built-in :func:`repr` function to obtain a 69 string version of everything it displays. For floats, ``repr(float)`` rounds 70 the true decimal value to 17 significant digits, giving :: 71 72 0.10000000000000001 73 74 ``repr(float)`` produces 17 significant digits because it turns out that's 75 enough (on most machines) so that ``eval(repr(x)) == x`` exactly for all finite 76 floats *x*, but rounding to 16 digits is not enough to make that true. 77 78 Note that this is in the very nature of binary floating-point: this is not a bug 79 in Python, and it is not a bug in your code either. You'll see the same kind of 80 thing in all languages that support your hardware's floating-point arithmetic 81 (although some languages may not *display* the difference by default, or in all 82 output modes). 83 84 Python's built-in :func:`str` function produces only 12 significant digits, and 85 you may wish to use that instead. It's unusual for ``eval(str(x))`` to 86 reproduce *x*, but the output may be more pleasant to look at:: 87 88 >>> print str(0.1) 71 That is more digits than most people find useful, so Python keeps the number 72 of digits manageable by displaying a rounded value instead :: 73 74 >>> 0.1 89 75 0.1 90 76 91 77 It's important to realize that this is, in a real sense, an illusion: the value 92 78 in the machine is not exactly 1/10, you're simply rounding the *display* of the 93 true machine value. 94 95 Other surprises follow from this one. For example, after seeing :: 96 97 >>> 0.1 98 0.10000000000000001 99 100 you may be tempted to use the :func:`round` function to chop it back to the 101 single digit you expect. But that makes no difference:: 102 103 >>> round(0.1, 1) 104 0.10000000000000001 105 106 The problem is that the binary floating-point value stored for "0.1" was already 107 the best possible binary approximation to 1/10, so trying to round it again 108 can't make it better: it was already as good as it gets. 109 110 Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 111 0.1 may not yield exactly 1.0, either:: 79 true machine value. This fact becomes apparent as soon as you try to do 80 arithmetic with these values :: 81 82 >>> 0.1 + 0.2 83 0.30000000000000004 84 85 Note that this is in the very nature of binary floating-point: this is not a 86 bug in Python, and it is not a bug in your code either. You'll see the same 87 kind of thing in all languages that support your hardware's floating-point 88 arithmetic (although some languages may not *display* the difference by 89 default, or in all output modes). 90 91 Other surprises follow from this one. For example, if you try to round the 92 value 2.675 to two decimal places, you get this :: 93 94 >>> round(2.675, 2) 95 2.67 96 97 The documentation for the built-in :func:`round` function says that it rounds 98 to the nearest value, rounding ties away from zero. Since the decimal fraction 99 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result 100 here to be (a binary approximation to) 2.68. It's not, because when the 101 decimal string ``2.675`` is converted to a binary floating-point number, it's 102 again replaced with a binary approximation, whose exact value is :: 103 104 2.67499999999999982236431605997495353221893310546875 105 106 Since this approximation is slightly closer to 2.67 than to 2.68, it's rounded 107 down. 108 109 If you're in a situation where you care which way your decimal halfway-cases 110 are rounded, you should consider using the :mod:`decimal` module. 111 Incidentally, the :mod:`decimal` module also provides a nice way to "see" the 112 exact value that's stored in any particular Python float :: 113 114 >>> from decimal import Decimal 115 >>> Decimal(2.675) 116 Decimal('2.67499999999999982236431605997495353221893310546875') 117 118 Another consequence is that since 0.1 is not exactly 1/10, summing ten values 119 of 0.1 may not yield exactly 1.0, either:: 112 120 113 121 >>> sum = 0.0 … … 116 124 ... 117 125 >>> sum 118 0.999999999999999 89126 0.9999999999999999 119 127 120 128 Binary floating-point arithmetic holds many surprises like this. The problem … … 132 140 While pathological cases do exist, for most casual use of floating-point 133 141 arithmetic you'll see the result you expect in the end if you simply round the 134 display of your final results to the number of decimal digits you expect. 135 :func:`str` usually suffices, and for finer control see the :meth:`str.format` 136 method'sformat specifiers in :ref:`formatstrings`.142 display of your final results to the number of decimal digits you expect. For 143 fine control over how a float is displayed see the :meth:`str.format` method's 144 format specifiers in :ref:`formatstrings`. 137 145 138 146 … … 142 150 ==================== 143 151 144 This section explains the "0.1" example in detail, and shows how you can perform145 an exact analysis of cases like this yourself. Basic familiarity with binary 146 floating-point representation is assumed.152 This section explains the "0.1" example in detail, and shows how you can 153 perform an exact analysis of cases like this yourself. Basic familiarity with 154 binary floating-point representation is assumed. 147 155 148 156 :dfn:`Representation error` refers to the fact that some (most, actually) … … 151 159 others) often won't display the exact decimal number you expect:: 152 160 153 >>> 0.1 154 0. 10000000000000001155 156 Why is that? 1/10 is not exactly representable as a binary fraction. Almost all157 machines today (November 2000) use IEEE-754 floating point arithmetic, and 158 a lmost all platforms map Python floats to IEEE-754 "double precision". 754159 doubles contain 53 bits of precision, so on input the computer strives to 160 convert 0.1 to the closest fraction it can of the form *J*/2**\ *N* where *J* is 161 an integer containing exactly 53 bits. Rewriting ::161 >>> 0.1 + 0.2 162 0.30000000000000004 163 164 Why is that? 1/10 and 2/10 are not exactly representable as a binary 165 fraction. Almost all machines today (July 2010) use IEEE-754 floating point 166 arithmetic, and almost all platforms map Python floats to IEEE-754 "double 167 precision". 754 doubles contain 53 bits of precision, so on input the computer 168 strives to convert 0.1 to the closest fraction it can of the form *J*/2**\ *N* 169 where *J* is an integer containing exactly 53 bits. Rewriting :: 162 170 163 171 1 / 10 ~= J / (2**N) … … 171 179 172 180 >>> 2**52 173 4503599627370496 L181 4503599627370496 174 182 >>> 2**53 175 9007199254740992 L183 9007199254740992 176 184 >>> 2**56/10 177 7205759403792793 L178 179 That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits. The180 best possible value for *J* is then that quotient rounded::185 7205759403792793 186 187 That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits. 188 The best possible value for *J* is then that quotient rounded:: 181 189 182 190 >>> q, r = divmod(2**56, 10) 183 191 >>> r 184 6 L192 6 185 193 186 194 Since the remainder is more than half of 10, the best approximation is obtained … … 188 196 189 197 >>> q+1 190 7205759403792794 L198 7205759403792794 191 199 192 200 Therefore the best possible approximation to 1/10 in 754 double precision is … … 196 204 197 205 Note that since we rounded up, this is actually a little bit larger than 1/10; 198 if we had not rounded up, the quotient would have been a little bit smaller than199 1/10. But in no case can it be *exactly* 1/10!206 if we had not rounded up, the quotient would have been a little bit smaller 207 than 1/10. But in no case can it be *exactly* 1/10! 200 208 201 209 So the computer never "sees" 1/10: what it sees is the exact fraction given … … 208 216 its 30 most significant decimal digits:: 209 217 210 >>> 7205759403792794 * 10**30 / 2**56218 >>> 7205759403792794 * 10**30 // 2**56 211 219 100000000000000005551115123125L 212 220 213 221 meaning that the exact number stored in the computer is approximately equal to 214 the decimal value 0.100000000000000005551115123125. Rounding that to 17 215 significant digits gives the 0.10000000000000001 that Python displays (well, 216 will display on any 754-conforming platform that does best-possible input and 217 output conversions in its C library --- yours may not!). 218 219 222 the decimal value 0.100000000000000005551115123125. In versions prior to 223 Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits, 224 giving '0.10000000000000001'. In current versions, Python displays a value 225 based on the shortest decimal fraction that rounds correctly back to the true 226 binary value, resulting simply in '0.1'. -
python/trunk/Doc/tutorial/index.rst
r2 r391 4 4 The Python Tutorial 5 5 ###################### 6 7 :Release: |version|8 :Date: |today|9 6 10 7 Python is an easy to learn, powerful programming language. It has efficient -
python/trunk/Doc/tutorial/inputoutput.rst
r2 r391 20 20 See the Library Reference for more information on this.) 21 21 22 .. index:: module: string23 24 22 Often you'll want more control over the formatting of your output than simply 25 23 printing space-separated values. There are two ways to format your output; the 26 24 first way is to do all the string handling yourself; using string slicing and 27 25 concatenation operations you can create any layout you can imagine. The 28 st andard module :mod:`string` contains someuseful operations for padding26 string types have some methods that perform useful operations for padding 29 27 strings to a given column width; these will be discussed shortly. The second 30 28 way is to use the :meth:`str.format` method. 29 30 The :mod:`string` module contains a :class:`~string.Template` class which offers 31 yet another way to substitute values into strings. 31 32 32 33 One question remains, of course: how do you convert values to strings? Luckily, … … 37 38 fairly human-readable, while :func:`repr` is meant to generate representations 38 39 which can be read by the interpreter (or will force a :exc:`SyntaxError` if 39 there is no tequivalent syntax). For objects which don't have a particular40 there is no equivalent syntax). For objects which don't have a particular 40 41 representation for human consumption, :func:`str` will return the same value as 41 42 :func:`repr`. Many values, such as numbers or structures like lists and … … 50 51 >>> repr(s) 51 52 "'Hello, world.'" 52 >>> str( 0.1)53 '0.1 '54 >>> repr( 0.1)55 '0.1 0000000000000001'53 >>> str(1.0/7.0) 54 '0.142857142857' 55 >>> repr(1.0/7.0) 56 '0.14285714285714285' 56 57 >>> x = 10 * 3.25 57 58 >>> y = 200 * 200 … … 103 104 way :keyword:`print` works: it always adds spaces between its arguments.) 104 105 105 This example demonstrates the :meth:`rjust` method of string objects, which 106 right-justifies a string in a field of a given width by padding it with spaces 107 on the left. There are similar methods :meth:`ljust` and :meth:`center`. These 108 methods do not write anything, they just return a new string. If the input 109 string is too long, they don't truncate it, but return it unchanged; this will 110 mess up your column lay-out but that's usually better than the alternative, 111 which would be lying about a value. (If you really want truncation you can 112 always add a slice operation, as in ``x.ljust(n)[:n]``.) 113 114 There is another method, :meth:`zfill`, which pads a numeric string on the left 115 with zeros. It understands about plus and minus signs:: 106 This example demonstrates the :meth:`str.rjust` method of string 107 objects, which right-justifies a string in a field of a given width by padding 108 it with spaces on the left. There are similar methods :meth:`str.ljust` and 109 :meth:`str.center`. These methods do not write anything, they just return a 110 new string. If the input string is too long, they don't truncate it, but 111 return it unchanged; this will mess up your column lay-out but that's usually 112 better than the alternative, which would be lying about a value. (If you 113 really want truncation you can always add a slice operation, as in 114 ``x.ljust(n)[:n]``.) 115 116 There is another method, :meth:`str.zfill`, which pads a numeric string on the 117 left with zeros. It understands about plus and minus signs:: 116 118 117 119 >>> '12'.zfill(5) … … 124 126 Basic usage of the :meth:`str.format` method looks like this:: 125 127 126 >>> print 'We are the { 0} who say "{1}!"'.format('knights', 'Ni')128 >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni') 127 129 We are the knights who say "Ni!" 128 130 129 131 The brackets and characters within them (called format fields) are replaced with 130 the objects passed into the :meth:` ~str.format` method. A number in the132 the objects passed into the :meth:`str.format` method. A number in the 131 133 brackets refers to the position of the object passed into the 132 :meth:` ~str.format` method. ::134 :meth:`str.format` method. :: 133 135 134 136 >>> print '{0} and {1}'.format('spam', 'eggs') … … 137 139 eggs and spam 138 140 139 If keyword arguments are used in the :meth:` ~str.format` method, their values141 If keyword arguments are used in the :meth:`str.format` method, their values 140 142 are referred to by using the name of the argument. :: 141 143 … … 154 156 155 157 >>> import math 156 >>> print 'The value of PI is approximately { 0}.'.format(math.pi)158 >>> print 'The value of PI is approximately {}.'.format(math.pi) 157 159 The value of PI is approximately 3.14159265359. 158 >>> print 'The value of PI is approximately { 0!r}.'.format(math.pi)160 >>> print 'The value of PI is approximately {!r}.'.format(math.pi) 159 161 The value of PI is approximately 3.141592653589793. 160 162 161 163 An optional ``':'`` and format specifier can follow the field name. This allows 162 164 greater control over how the value is formatted. The following example 163 truncates Pi to three places after the decimal.165 rounds Pi to three places after the decimal. 164 166 165 167 >>> import math … … 195 197 Jack: 4098; Sjoerd: 4127; Dcab: 8637678 196 198 197 This is particularly useful in combination with the new built-in :func:`vars`198 function, which returns a dictionary containing all local variables.199 This is particularly useful in combination with the built-in function 200 :func:`vars`, which returns a dictionary containing all local variables. 199 201 200 202 For a complete overview of string formatting with :meth:`str.format`, see … … 206 208 207 209 The ``%`` operator can also be used for string formatting. It interprets the 208 left argument much like a :c func:`sprintf`\ -style format string to be applied210 left argument much like a :c:func:`sprintf`\ -style format string to be applied 209 211 to the right argument, and returns the string resulting from this formatting 210 212 operation. For example:: … … 214 216 The value of PI is approximately 3.142. 215 217 216 Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%``217 operator. However, because this old style of formatting will eventually be218 removed from the language, :meth:`str.format` should generally be used.219 220 218 More information can be found in the :ref:`string-formatting` section. 221 219 … … 235 233 :: 236 234 237 >>> f = open(' /tmp/workfile', 'w')235 >>> f = open('workfile', 'w') 238 236 >>> print f 239 <open file ' /tmp/workfile', mode 'w' at 80a0960>237 <open file 'workfile', mode 'w' at 80a0960> 240 238 241 239 The first argument is a string containing the filename. The second argument is … … 294 292 '' 295 293 296 ``f.readlines()`` returns a list containing all the lines of data in the file. 297 If given an optional parameter *sizehint*, it reads that many bytes from the 298 file and enough more to complete a line, and returns the lines from that. This 299 is often used to allow efficient reading of a large file by lines, but without 300 having to load the entire file in memory. Only complete lines will be returned. 301 :: 302 303 >>> f.readlines() 304 ['This is the first line of the file.\n', 'Second line of the file\n'] 305 306 An alternative approach to reading lines is to loop over the file object. This is 307 memory efficient, fast, and leads to simpler code:: 294 For reading lines from a file, you can loop over the file object. This is memory 295 efficient, fast, and leads to simple code:: 308 296 309 297 >>> for line in f: … … 313 301 Second line of the file 314 302 315 The alternative approach is simpler but does not provide as fine-grained 316 control. Since the two approaches manage line buffering differently, they 317 should not be mixed. 303 If you want to read all the lines of a file in a list you can also use 304 ``list(f)`` or ``f.readlines()``. 318 305 319 306 ``f.write(string)`` writes the contents of *string* to the file, returning … … 338 325 beginning of the file as the reference point. :: 339 326 340 >>> f = open(' /tmp/workfile', 'r+')327 >>> f = open('workfile', 'r+') 341 328 >>> f.write('0123456789abcdef') 342 329 >>> f.seek(5) # Go to the 6th byte in the file … … 362 349 shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks:: 363 350 364 >>> with open(' /tmp/workfile', 'r') as f:351 >>> with open('workfile', 'r') as f: 365 352 ... read_data = f.read() 366 353 >>> f.closed -
python/trunk/Doc/tutorial/interactive.rst
r2 r391 124 124 # 125 125 # Store the file in ~/.pystartup, and set an environment variable to point 126 # to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash. 127 # 128 # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the 129 # full path to your home directory. 126 # to it: "export PYTHONSTARTUP=~/.pystartup" in bash. 130 127 131 128 import atexit … … 160 157 161 158 One alternative enhanced interactive interpreter that has been around for quite 162 some time is `IPython`_, which features tab completion, object exploration and159 some time is IPython_, which features tab completion, object exploration and 163 160 advanced history management. It can also be thoroughly customized and embedded 164 161 into other applications. Another similar enhanced interactive environment is 165 `bpython`_.162 bpython_. 166 163 167 164 … … 170 167 .. [#] Python will execute the contents of a file identified by the 171 168 :envvar:`PYTHONSTARTUP` environment variable when you start an interactive 172 interpreter. 169 interpreter. To customize Python even for non-interactive mode, see 170 :ref:`tut-customize`. 173 171 174 172 -
python/trunk/Doc/tutorial/interpreter.rst
r2 r391 23 23 24 24 On Windows machines, the Python installation is usually placed in 25 :file:`C:\\Python2 6`, though you can change this when you're running the25 :file:`C:\\Python27`, though you can change this when you're running the 26 26 installer. To add this directory to your path, you can type the following 27 27 command into the command prompt in a DOS box:: 28 28 29 set path=%path%;C:\python2 629 set path=%path%;C:\python27 30 30 31 31 Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on … … 59 59 if you had spelled out its full name on the command line. 60 60 61 Note that there is a difference between ``python file`` and ``python <file``.62 In the latter case, input requests from the program, such as calls to63 :func:`input` and :func:`raw_input`, are satisfied from *file*. Since this file64 has already been read until the end by the parser before the program starts65 executing, the program will encounter end-of-file immediately. In the former66 case (which is usually what you want) they are satisfied from whatever file or67 device is connected to standard input of the Python interpreter.68 69 61 When a script file is used, it is sometimes useful to be able to run the script 70 62 and enter interactive mode afterwards. This can be done by passing :option:`-i` 71 before the script. (This does not work if the script is read from standard 72 input, for the same reason as explained in the previous paragraph.) 63 before the script. 73 64 74 65 … … 79 70 80 71 When known to the interpreter, the script name and additional arguments 81 thereafter are passed to the script in the variable ``sys.argv``, which is a 82 list of strings. Its length is at least one; when no script and no arguments 72 thereafter are turned into a list of strings and assigned to the ``argv`` 73 variable in the ``sys`` module. You can access this list by executing ``import 74 sys``. The length of the list is at least one; when no script and no arguments 83 75 are given, ``sys.argv[0]`` is an empty string. When the script name is given as 84 76 ``'-'`` (meaning standard input), ``sys.argv[0]`` is set to ``'-'``. When … … 103 95 104 96 python 105 Python 2. 6 (#1, Feb 28 2007, 00:02:06)97 Python 2.7 (#1, Feb 28 2010, 00:02:06) 106 98 Type "help", "copyright", "credits" or "license" for more information. 107 99 >>> … … 174 166 175 167 168 .. _tut-source-encoding: 169 176 170 Source Code Encoding 177 171 -------------------- … … 192 186 For example, to write Unicode literals including the Euro currency symbol, the 193 187 ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value 194 164. This script will print the value 8364 (the Unicode codepoint corresponding195 to the Euro symbol) and then exit::188 164. This script, when saved in the ISO-8859-15 encoding, will print the value 189 8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit:: 196 190 197 191 # -*- coding: iso-8859-15 -*- … … 248 242 249 243 244 .. _tut-customize: 245 246 The Customization Modules 247 ------------------------- 248 249 Python provides two hooks to let you customize it: :mod:`sitecustomize` and 250 :mod:`usercustomize`. To see how it works, you need first to find the location 251 of your user site-packages directory. Start Python and run this code: 252 253 >>> import site 254 >>> site.getusersitepackages() 255 '/home/user/.local/lib/python2.7/site-packages' 256 257 Now you can create a file named :file:`usercustomize.py` in that directory and 258 put anything you want in it. It will affect every invocation of Python, unless 259 it is started with the :option:`-s` option to disable the automatic import. 260 261 :mod:`sitecustomize` works in the same way, but is typically created by an 262 administrator of the computer in the global site-packages directory, and is 263 imported before :mod:`usercustomize`. See the documentation of the :mod:`site` 264 module for more details. 265 266 250 267 .. rubric:: Footnotes 251 268 252 269 .. [#] A problem with the GNU Readline package may prevent this. 253 -
python/trunk/Doc/tutorial/introduction.rst
r2 r391 83 83 error will occur:: 84 84 85 >>> # try to access an undefined variable 86 ... n 85 >>> n # try to access an undefined variable 87 86 Traceback (most recent call last): 88 87 File "<stdin>", line 1, in <module> … … 179 178 '"Isn\'t," she said.' 180 179 180 The interpreter prints the result of string operations in the same way as they 181 are typed for input: inside quotes, and with quotes and other funny characters 182 escaped by backslashes, to show the precise value. The string is enclosed in 183 double quotes if the string contains a single quote and no double quotes, else 184 it's enclosed in single quotes. The :keyword:`print` statement produces a more 185 readable output for such input strings. 186 181 187 String literals can span multiple lines in several ways. Continuation lines can 182 188 be used, with a backslash as the last character on the line indicating that the … … 190 196 print hello 191 197 192 Note that newlines still need to be embedded in the string using ``\n`` ;the198 Note that newlines still need to be embedded in the string using ``\n`` -- the 193 199 newline following the trailing backslash is discarded. This example would print 194 200 the following: … … 233 239 This is a rather long string containing\n\ 234 240 several lines of text much as you would do in C. 235 236 The interpreter prints the result of string operations in the same way as they237 are typed for input: inside quotes, and with quotes and other funny characters238 escaped by backslashes, to show the precise value. The string is enclosed in239 double quotes if the string contains a single quote and no double quotes, else240 it's enclosed in single quotes. (The :keyword:`print` statement, described241 later, can be used to write strings without quotes or escapes.)242 241 243 242 Strings can be concatenated (glued together) with the ``+`` operator, and … … 523 522 >>> 3*a[:3] + ['Boo!'] 524 523 ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!'] 524 525 All slice operations return a new list containing the requested elements. This 526 means that the following slice returns a shallow copy of the list *a*:: 527 528 >>> a[:] 529 ['spam', 'eggs', 100, 1234] 525 530 526 531 Unlike strings, which are *immutable*, it is possible to change individual … … 625 630 626 631 * The *body* of the loop is *indented*: indentation is Python's way of grouping 627 statements. Python does not (yet!) provide an intelligent input line editing628 facility, so you have to type a tab or space(s) for each indented line. In629 practice you will prepare more complicated input for Python with a text editor;630 most text editors have an auto-indent facility. When a compound statement is631 entered interactively, it must be followed by a blank line to indicate632 completion (since the parser cannot guess when you have typed the last line).633 Note that each line within a basicblock must be indented by the same amount.632 statements. At the interactive prompt, you have to type a tab or space(s) for 633 each indented line. In practice you will prepare more complicated input 634 for Python with a text editor; all decent text editors have an auto-indent 635 facility. When a compound statement is entered interactively, it must be 636 followed by a blank line to indicate completion (since the parser cannot 637 guess when you have typed the last line). Note that each line within a basic 638 block must be indented by the same amount. 634 639 635 640 * The :keyword:`print` statement writes the value of the expression(s) it is -
python/trunk/Doc/tutorial/modules.rst
r2 r391 72 72 A module can contain executable statements as well as function definitions. 73 73 These statements are intended to initialize the module. They are executed only 74 the *first* time the module is imported somewhere. [#]_ 74 the *first* time the module name is encountered in an import statement. [#]_ 75 (They are also run if the file is executed as a script.) 75 76 76 77 Each module has its own private symbol table, which is used as the global symbol … … 156 157 .. index:: triple: module; search; path 157 158 158 When a module named :mod:`spam` is imported, the interpreter searches for a file 159 named :file:`spam.py` in the current directory, and then in the list of 160 directories specified by the environment variable :envvar:`PYTHONPATH`. This 161 has the same syntax as the shell variable :envvar:`PATH`, that is, a list of 162 directory names. When :envvar:`PYTHONPATH` is not set, or when the file is not 163 found there, the search continues in an installation-dependent default path; on 164 Unix, this is usually :file:`.:/usr/local/lib/python`. 165 166 Actually, modules are searched in the list of directories given by the variable 167 ``sys.path`` which is initialized from the directory containing the input script 168 (or the current directory), :envvar:`PYTHONPATH` and the installation- dependent 169 default. This allows Python programs that know what they're doing to modify or 170 replace the module search path. Note that because the directory containing the 171 script being run is on the search path, it is important that the script not have 172 the same name as a standard module, or Python will attempt to load the script as 173 a module when that module is imported. This will generally be an error. See 174 section :ref:`tut-standardmodules` for more information. 159 When a module named :mod:`spam` is imported, the interpreter first searches for 160 a built-in module with that name. If not found, it then searches for a file 161 named :file:`spam.py` in a list of directories given by the variable 162 :data:`sys.path`. :data:`sys.path` is initialized from these locations: 163 164 * the directory containing the input script (or the current directory). 165 * :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the 166 shell variable :envvar:`PATH`). 167 * the installation-dependent default. 168 169 After initialization, Python programs can modify :data:`sys.path`. The 170 directory containing the script being run is placed at the beginning of the 171 search path, ahead of the standard library path. This means that scripts in that 172 directory will be loaded instead of modules of the same name in the library 173 directory. This is an error unless the replacement is intended. See section 174 :ref:`tut-standardmodules` for more information. 175 175 176 176 … … 244 244 for efficiency or to provide access to operating system primitives such as 245 245 system calls. The set of such modules is a configuration option which also 246 depends on the underlying platform For example, the :mod:`winreg` module is only246 depends on the underlying platform. For example, the :mod:`winreg` module is only 247 247 provided on Windows systems. One particular module deserves some attention: 248 248 :mod:`sys`, which is built into every Python interpreter. The variables … … 284 284 >>> dir(fibo) 285 285 ['__name__', 'fib', 'fib2'] 286 >>> dir(sys) 287 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', 288 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 289 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 290 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 291 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 292 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 293 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 294 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 295 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 286 >>> dir(sys) # doctest: +NORMALIZE_WHITESPACE 287 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', 288 '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', 289 '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 290 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 291 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 292 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 293 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 294 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 295 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 296 'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion', 297 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 298 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 299 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 300 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 296 301 'version', 'version_info', 'warnoptions'] 297 302 … … 302 307 >>> fib = fibo.fib 303 308 >>> dir() 304 ['__builtins__', '__ doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']309 ['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys'] 305 310 306 311 Note that it lists all types of names: variables, modules, functions, etc. … … 313 318 314 319 >>> import __builtin__ 315 >>> dir(__builtin__) 316 ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 317 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 318 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 320 >>> dir(__builtin__) # doctest: +NORMALIZE_WHITESPACE 321 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 322 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 323 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 324 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 319 325 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 320 326 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', … … 325 331 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 326 332 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 327 'U serWarning', 'ValueError', 'Warning', 'WindowsError',333 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 328 334 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', 329 '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 330 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 331 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 332 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 333 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 334 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 335 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 336 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 337 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 338 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 335 '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 336 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 337 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 338 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 339 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 340 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 341 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 342 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 343 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 344 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 345 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 339 346 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] 340 347 … … 362 369 artificial stereo effect), so in addition you will be writing a never-ending 363 370 stream of modules to perform these operations. Here's a possible structure for 364 your package (expressed in terms of a hierarchical filesystem):: 371 your package (expressed in terms of a hierarchical filesystem): 372 373 .. code-block:: text 365 374 366 375 sound/ Top-level package … … 459 468 new version of the package is released. Package authors may also decide not to 460 469 support it, if they don't see a use for importing \* from their package. For 461 example, the file :file:`sound s/effects/__init__.py` could contain the following470 example, the file :file:`sound/effects/__init__.py` could contain the following 462 471 code:: 463 472 … … 545 554 546 555 .. [#] In fact function definitions are also 'statements' that are 'executed'; the 547 execution of a module-level function enters the function name in the module's548 global symbol table.549 556 execution of a module-level function definition enters the function name in 557 the module's global symbol table. 558 -
python/trunk/Doc/tutorial/stdlib.rst
r2 r391 15 15 16 16 >>> import os 17 >>> os.system('time 0:02')18 019 17 >>> os.getcwd() # Return the current working directory 20 18 'C:\\Python26' 21 >>> os.chdir('/server/accesslogs') 19 >>> os.chdir('/server/accesslogs') # Change current working directory 20 >>> os.system('mkdir today') # Run the command mkdir in the system shell 21 0 22 22 23 23 Be sure to use the ``import os`` style instead of ``from os import *``. This … … 73 73 The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix 74 74 :func:`getopt` function. More powerful and flexible command line processing is 75 provided by the :mod:` optparse` module.75 provided by the :mod:`argparse` module. 76 76 77 77 … … 146 146 147 147 There are a number of modules for accessing the internet and processing internet 148 protocols. Two of the simplest are :mod:`urllib2` for retrieving data from urls148 protocols. Two of the simplest are :mod:`urllib2` for retrieving data from URLs 149 149 and :mod:`smtplib` for sending mail:: 150 150 … … 279 279 self.assertEqual(average([20, 30, 70]), 40.0) 280 280 self.assertEqual(round(average([1, 5, 7]), 1), 4.3) 281 self.assertRaises(ZeroDivisionError, average, []) 282 self.assertRaises(TypeError, average, 20, 30, 70) 281 with self.assertRaises(ZeroDivisionError): 282 average([]) 283 with self.assertRaises(TypeError): 284 average(20, 30, 70) 283 285 284 286 unittest.main() # Calling from the command line invokes all tests -
python/trunk/Doc/tutorial/stdlib2.rst
r2 r391 72 72 ========== 73 73 74 The :mod:`string` module includes a versatile :class:` Template` class with a75 simplified syntax suitable for editing by end-users. This allows users to 76 customize their applications without having to alter the application.74 The :mod:`string` module includes a versatile :class:`~string.Template` class 75 with a simplified syntax suitable for editing by end-users. This allows users 76 to customize their applications without having to alter the application. 77 77 78 78 The format uses placeholder names formed by ``$`` with valid Python identifiers … … 86 86 'Nottinghamfolk send $10 to the ditch fund.' 87 87 88 The :meth:` substitute` method raises a :exc:`KeyError` when a placeholder is not89 supplied in a dictionary or a keyword argument. For mail-merge style 90 applications, user supplied data may be incomplete and the91 :meth:` safe_substitute` method may be more appropriate --- it will leave92 placeholders unchanged if data is missing::88 The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when a 89 placeholder is not supplied in a dictionary or a keyword argument. For 90 mail-merge style applications, user supplied data may be incomplete and the 91 :meth:`~string.Template.safe_substitute` method may be more appropriate --- 92 it will leave placeholders unchanged if data is missing:: 93 93 94 94 >>> t = Template('Return the $item to $owner.') … … 96 96 >>> t.substitute(d) 97 97 Traceback (most recent call last): 98 . ..98 ... 99 99 KeyError: 'owner' 100 100 >>> t.safe_substitute(d) … … 133 133 ======================================= 134 134 135 The :mod:`struct` module provides :func:`pack` and :func:`unpack` functions for 136 working with variable length binary record formats. The following example shows 135 The :mod:`struct` module provides :func:`~struct.pack` and 136 :func:`~struct.unpack` functions for working with variable length binary 137 record formats. The following example shows 137 138 how to loop through header information in a ZIP file without using the 138 139 :mod:`zipfile` module. Pack codes ``"H"`` and ``"I"`` represent two and four … … 219 220 logging.critical('Critical error -- shutting down') 220 221 221 This produces the following output:: 222 This produces the following output: 223 224 .. code-block:: none 222 225 223 226 WARNING:root:Warning:config file server.conf not found … … 228 231 is sent to standard error. Other output options include routing messages 229 232 through email, datagrams, sockets, or to an HTTP Server. New filters can select 230 different routing based on message priority: :const:`DEBUG`, :const:`INFO`, 231 :const:`WARNING`, :const:`ERROR`, and :const:`CRITICAL`. 233 different routing based on message priority: :const:`~logging.DEBUG`, 234 :const:`~logging.INFO`, :const:`~logging.WARNING`, :const:`~logging.ERROR`, 235 and :const:`~logging.CRITICAL`. 232 236 233 237 The logging system can be configured directly from Python or can be loaded from … … 256 260 >>> class A: 257 261 ... def __init__(self, value): 258 ... 262 ... self.value = value 259 263 ... def __repr__(self): 260 ... 264 ... return str(self.value) 261 265 ... 262 266 >>> a = A(10) # create a reference … … 286 290 performance trade-offs. 287 291 288 The :mod:`array` module provides an :class:` array()` object that is like a list289 that stores only homogeneous data and stores it more compactly. The following 290 example shows an array of numbers stored as two byte unsigned binary numbers 291 (typecode ``"H"``) rather than the usual 16 bytes per entry for regular lists of 292 Python int objects::292 The :mod:`array` module provides an :class:`~array.array()` object that is like 293 a list that stores only homogeneous data and stores it more compactly. The 294 following example shows an array of numbers stored as two byte unsigned binary 295 numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular 296 lists of Python int objects:: 293 297 294 298 >>> from array import array … … 299 303 array('H', [10, 700]) 300 304 301 The :mod:`collections` module provides a :class:` deque()` object that is like a302 list with faster appends and pops from the left side but slower lookups in the 303 middle. These objects are well suited for implementing queues and breadth first 304 tree searches::305 The :mod:`collections` module provides a :class:`~collections.deque()` object 306 that is like a list with faster appends and pops from the left side but slower 307 lookups in the middle. These objects are well suited for implementing queues 308 and breadth first tree searches:: 305 309 306 310 >>> from collections import deque … … 309 313 >>> print "Handling", d.popleft() 310 314 Handling task1 315 316 :: 311 317 312 318 unsearched = deque([starting_node]) … … 346 352 ================================= 347 353 348 The :mod:`decimal` module offers a :class:` Decimal` datatype for decimal349 floating point arithmetic. Compared to the built-in :class:`float`354 The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for 355 decimal floating point arithmetic. Compared to the built-in :class:`float` 350 356 implementation of binary floating point, the class is especially helpful for 351 357 … … 363 369 364 370 >>> from decimal import * 365 >>> Decimal('0.70') * Decimal('1.05') 371 >>> x = Decimal('0.70') * Decimal('1.05') 372 >>> x 366 373 Decimal('0.7350') 367 >>> .70 * 1.05 368 0.73499999999999999 369 370 The :class:`Decimal` result keeps a trailing zero, automatically inferring four 371 place significance from multiplicands with two place significance. Decimal 372 reproduces mathematics as done by hand and avoids issues that can arise when 373 binary floating point cannot exactly represent decimal quantities. 374 375 Exact representation enables the :class:`Decimal` class to perform modulo 376 calculations and equality tests that are unsuitable for binary floating point:: 374 >>> x.quantize(Decimal('0.01')) # round to nearest cent 375 Decimal('0.74') 376 >>> round(.70 * 1.05, 2) # same calculation with floats 377 0.73 378 379 The :class:`~decimal.Decimal` result keeps a trailing zero, automatically 380 inferring four place significance from multiplicands with two place 381 significance. Decimal reproduces mathematics as done by hand and avoids 382 issues that can arise when binary floating point cannot exactly represent 383 decimal quantities. 384 385 Exact representation enables the :class:`~decimal.Decimal` class to perform 386 modulo calculations and equality tests that are unsuitable for binary floating 387 point:: 377 388 378 389 >>> Decimal('1.00') % Decimal('.10') -
python/trunk/Doc/tutorial/whatnow.rst
r2 r391 55 55 around 120 postings a day (with peaks up to several hundred), asking (and 56 56 answering) questions, suggesting new features, and announcing new modules. 57 Before posting, be sure to check the list of `Frequently Asked Questions 58 <http://www.python.org/doc/faq/>`_ (also called the FAQ), or look for it in the 59 :file:`Misc/` directory of the Python source distribution. Mailing list 57 Before posting, be sure to check the list of :ref:`Frequently Asked Questions 58 <faq-index>` (also called the FAQ). Mailing list 60 59 archives are available at http://mail.python.org/pipermail/. The FAQ answers 61 60 many of the questions that come up again and again, and may already contain the
Note:
See TracChangeset
for help on using the changeset viewer.