2017.4.21

  • argument

  • A value passed to a function (or method) when calling the function. There are two kinds of argument:

    Arguments are assigned to the named local variables in a function body. See the Calls section for the rules governing this assignment. Syntactically, any expression can be used to represent an argument; the evaluated value is assigned to the local variable.

    • keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following calls to complex():

      complex(real=3, imag=5)complex(**{'real': 3, 'imag': 5})
    • positional argument: an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3 and 5 are both positional arguments in the following calls:

      complex(3, 5)complex(*(3, 5))


2.2. The Interpreter and Its Environment

2.2.1. Source Code Encoding

By default, Python source files are treated as encoded in UTF-8. In that encoding,although the standard library only uses ASCII characters for identifiers.

To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows:

# -*- coding: encoding -*-

where encoding is one of the valid codecs supported by Python.

For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be:

# -*- coding: cp-1252 -*-

One exception to the first line rule is when the source code starts with a UNIX “shebang” line. In this case, the encoding declaration should be added as the second line of the file. For example:

#!/usr/bin/env python3# -*- coding: cp-1252 -*-


3.1. Using Python as a Calculator

3.1.1. Numbers

Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:

>>>

>>> 17 / 3  # classic division returns a float5.666666666666667
>>> 17 // 3  # floor division discards the fractional part5
>>> 17 % 3  # the % operator returns the remainder of the division2
>>> 5 * 3 + 2  # result * divisor + remainder17


With Python, it is possible to use the ** operator to calculate powers [1]:

>>>

>>> 5 ** 2  # 5 squared25>>> 2 ** 7  # 2 to the power of 7128
[1]Since ** has higher precedence than --3**2 will be interpreted as -(3**2) and thus result in -9. To avoid this and get 9, you can use (-3)**2.

浮点数和整型数值计算结果还是浮点数。

>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.5

交互式代码中,_代表上一个表达式。

>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).


3.1.2. Strings

The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

>>>

>>> print('C:\some\name')  # here \n means newline!C:\someame
>>> print(r'C:\some\name')  # note the r before the quoteC:\some\name


Strings can be concatenated (glued together) with the + operator, and repeated with *:include literals,variables,expressions.

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

This feature is particularly useful when you want to break long strings:

>>>

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text'Put several strings within parentheses to have them joined together.'

Strings can be indexed (subscripted), with the first character having index 0;Note that since -0 is the same as 0, negative indices start from -1.

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[-1]  # last character
'n'

In addition to indexing, slicing is also supported.

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used for slicing:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42]
'on'
>>> word[42:]
''

Python strings cannot be changed — they are immutable.If you need a different string, you should create a new one:

>>> word[0] = 'J' 
 ...
TypeError: 'str' object does not support item assignment
>>> 'J' + word[1:]
'Jython'

The built-in function len() returns the length of a string:


3.1.3. Lists

Lists might contain items of different types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list.

Unlike strings, which are immutable, lists are a mutable type

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using the append() method

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists).


3.2. First Steps Towards Programming

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

>>>

>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

4. More Control Flow Tools

4.1. if Statements

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More


4.2. for Statements

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. 

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

If you need to modify the sequence you are iterating over while inside the loop, it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> for w in words[:]:  # Loop over a slice copy of the entire list
....     if len(w) > 6:
...         words.insert(0, w)
...>
>> words
['defenestrate', 'cat', 'window', 'defenestrate']

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

4.3. The range() Function

>>> print(range(10))range(0, 10)

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:

>>> list(range(5))
[0, 1, 2, 3, 4]

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

range(5, 10)
   5 through 9
range(0, 10, 3)
   0, 3, 6, 9
range(-10, -100, -30)
  -10, -40, -70

To iterate over the indices of a sequenceuse the enumerate() function:


  • enumerate(iterablestart=0)

  • Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

    >>>

    >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
  • >>> list(enumerate(seasons))
  • [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
  • >>> list(enumerate(seasons, start=1))
  • [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

4.4. break and continue Statements, and else Clauses on Loops