2017.4.21
) in a function call or passed as a value in a dictionary preceded by
- name=
. For example,
- **
and
- 3
are both keyword arguments in the following calls to
- 5
:
- complex()
- complex(real = 3, imag = 5) complex( * *{'real': 3,
- 'imag': 5
- })
. For example,
- *
and
- 3
are both positional arguments in the following calls:
- 5
- complex(3, 5)complex(*(3, 5))
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
supported by Python.
- codecs
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 -*-
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 , will be interpreted as and thus result in . To avoid this and get , you can use . |
浮点数和整型数值计算结果还是浮点数。
- >>> 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
and
- int
, Python supports other types of numbers, such as
- float
and
- Decimal
. Python also has built-in support for complex numbers, and uses the
- Fraction
or
- j
suffix to indicate the imaginary part (e.g.
- J
).
- 3+5j
The
function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
- print()
If you don't want characters prefaced by
to be interpreted as special characters, you can use raw strings by adding an
- \
before the first quote:
- r
>>>
- >>> 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
returns the length of a string:
- len()
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
method
- append()
- >>> 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
also applies to lists:
- len()
It is possible to nest lists (create lists containing other lists).
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,
Statements
- if
There can be zero or more
parts, and the
- elif
part is optional. The keyword '
- else
'is short for'else if', and is useful to avoid excessive indentation
- elif
- >>> 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
Statements
- for
Python's
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
- for
- >>> # 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
, the example would attempt to create an infinite list, inserting
- for w in words:
over and over again.
- defenestrate
Python 3.6 文档阅读笔记
来源: http://www.bubuko.com/infodetail-2035372.html