88bifa必发唯一官网:Python内置函数

 

 

英文文书档案:

Python内置函数

我们就从相比难以精通的三个函数先河吧,先啃硬骨头T.T

一 使用如下代码将keywords+builtins+modules输出到文件

eval(expression, globals=None,
locals=None)

1. eval(expression,globals=None,locals=None)

Python docs description:
The arguments are a string and optional globals and locals.
If provided,globals must be a dictionnary.
If provided,locals can be any mapping object.
The expression argument is parsed and evaluated as a Python
expression1 using the globals and locals dictinaries as global and
local namespace.
纵使内定表明式所处的全局空间和壹部分空间,在施行语句发生的具备指标都会存到钦赐的半空中中
If the globals dictionary is present and lacks ‘__builtins__’,the
current globals are copied into globals before expression is parsed.
那句话就厉害了,因为钦点了大局命名空间,所以即使代码中留存使用内置函数的话语的话,也许就找不到。python消除这几个难题不怕,在分析代码前,会将最近的全局复制到钦定的大局空间中二脚注中尝试证实。
This means that expression normally has full access to the standard
builtins 模块 and restricted environments are propagated.
If the locals dictionary is omitted it defaults to the globals
dictionary.
If both dictionaries are omitted,the expression is executed in the
environment where eval() is
called.说是三个空中都没内定的话,那么就使用eval()所处的情状.
The return value is the result of the evaluated expression.
eval()是动态实行表明式,若是要动态实施代码语句使用exec()。
python
提供globals()和locals()再次回到四个当下全局和局地的上空内容,能够钦定给那三个函数作为前面包车型客车参数。

import sys

The arguments are a string and optional globals and locals. If provided,
globals must be a dictionary. If provided, locals can be any mapping
object.

2. exec(object[,globals[,locals]])

This function supoorts dynamic execution of Python
code.能够使当前代码动态的扭转,动态的剧情在于参数object。object must
be a string or a code object.
If it is a string, the string is parsed as a suite of Python
statements which is then executed (unless a syntax error occurs).
If it is a code object,it is simply executed.
In all cases, the code that’s executed is expected to valid as file
input(see the section “file input” in the Reference Manual).
Be aware that the return and yield statements may not be used outside
of functions even within the context of code passed to the exec()
function.
The return value is None
In all cases,if the optional parts are omitted,the code is executed in
the current scope.
If only globals is provided,it must be a dictionary,which will be used
for both the global and the local variables.
If globals and locals are given,they are used for the global and local
variables,respectively.
If provided,locals can be any mapping object.
Remember that at module level,globals and locals are the same
dictionary.
If exec gets two separate objects as globals and locals,the code will
be executed as if (好似)it were embedded(嵌套在) in a class
definition.
If the globals dictionary does not contain a value for the key
__builtins__ ,a reference to the dictionary of the built-in
module builtins is inserted under that key.
That way you can control what builtins are available to the executed
code by inserting your oun __builtins__ dictionary into globals
before pasing it to exec().

牛逼的exec 和eval

def stdoutToFile(filename, function, args ):
    oldStdout = sys.stdout
    f = open(filename, “w” )
    sys.stdout = f 
    function(args)
    #sys.stdout.flush()
    #f.close()
    sys.stdout = oldStdout

The expression argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the globals and
locals dictionaries as global and local namespace. If the globals
dictionary is present and lacks ‘__builtins__’, the current globals
are copied into globals before expression is parsed. This means that
expression normally has full access to the standard builtins module
and restricted environments are propagated. If the locals dictionary
is omitted it defaults to the globals dictionary. If both dictionaries
are omitted, the expression is executed in the environment where
eval() is called. The return value is the result of the evaluated
expression. Syntax errors are reported as exceptions. Example:

3. open(…)

调用:open(file,mode=’r’,buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)

Open file and return a corresponding file object .If the file
cannot be opened,an OSError is raised.
再次来到三个file-object对象如若file不可张开的话,抛出OSError非凡
file is either a string or bytes object giving the pathname of the
file to be opened or an integer file descriptor of the file to be
wrapped.(If a file descriptor is given,it is closed when the returned
I/O object is closed ,unless closefd is set to False)
file参数给出字节或文本对象所在文书的相对路线恐怕相对路线(相对于当前专门的学业路线)
mode is an optional string that specifies the mode in which the
file is opened .It defaults to ‘r’ which means open for reading in
text mode.Other common values are ‘w’ for writing (truncating the file
if it already exists ) ,’x’ for exclusive(排外的) creation and ‘a’ for
appending (which on some Unix systems ,means that all writes append to
the end of the file regardless of the current seek position). In text
mode, if encoding is not specified the encoding used is paltform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding .(For reading and writing raw bytes use binary
mode and leave encoding unspecified )

character meaning
‘r’ open for reading(default)
‘w’ open for writing,truncating the file first
‘a’ open for writing,appending to the end of the file if it exists
‘x’ open for exclusive creation,writing,non-reading,failing if the file already exists
‘b’ binary mode
‘t’ text mode(default)
‘+’ open a disk file for updating (reading and writing)
‘U’ univeral newlines mode(deprecated弃用;不赞成)
  • 第3暗中同意情势是’r’
    由于‘t’方式也是暗许的,所以不钦赐’b’就使用私下认可的’t’,即text mode,’r’
    <=>
    ’rt’,’w’<=>’wt’,’x’<=>’xt’,’a'<=>’at’。假使都若是字节情势,那么就把‘t’换到’b’就行了,那样open()将回来TextIOWrapper变为回到BufferedWriter。自然二种协助的其余操作就有分别了。
  • ‘x’
    情势必须是文件不存在,所以open成功最后都以写入三个空白文件中。那种方式的存在正是须求要写文件,又怕将已存在的公文假若通过’w’把文件truncate了。
  • python是要区分binary和text I/O的,文件展开是binary
    mode的归来三个bytes
    oject,是不要求decoding。而str是索要开始展览decoding,所以要钦命text文件的编码,私下认可使用操作系统的编码实行解码。

buffering is an optional integer used to set the buffering
policy.Pass 0 to switch buffering off(only allowed in binary mode),
Pass 1 to select line buffering(only useable in text mode),and an
integer > 1 to indicate the size in bytes of a fixed-size chunk
buffer.When no buffering argument is given , the ddefault buffering
policy works as fallows:

Binary files are buffered in fixed-size chunks;the size of the
buffer is chosen using a heuristic启发式的 trying to determine the
underlying devices’s “block size” and falling back on
io.DEFAULT_BUFFER_SIZE.on many system s ,the buffer will typically
be 4096 or 8192 bytes long.
“Interactive”
bytes形式援救关闭buffer,文本方式辅助行buffer,内定别的大于一的值,表示是钦命字节块buffer大小,倘若是暗中认可的-一,二进制则依照系统的私下认可buffer大小,假如是文本,又分是终端式交互类型,那种是以行buffer,假如日常文书文件,就和bytes是同样的
encoding 内定decode或encode的编码。 只会设有在text mode。
errors 直接官方网站。轻易说,和encoding参数是联动的,所以是只在text
mode
的。那么些参数是编码错误怎么样被handled的。分品级来handle分化编码上的荒谬。
newline 用于text mode,
对换行符的钦定,暗中认可是利用通用的,如有特殊,能够钦点。
closefd 使用False值的话,file就应用文件描述符,而不是文本名。the
underlying file descriptor底层文件讲述符 will be kept open when the
file is closed直到文件被关闭。
opener 钦赐自定义的opener,张开文件的秘技。

 

四. all(可迭代对象)

判别可迭代对象中,各种成分,如若有三个因素是bool(ele)->False的,all()再次来到False,不然再次回到True.可迭代对象是空重返True.

5.
any(可迭代对象)

可迭代对象中,大4有1个要素是bool(ele)->True的,angy()就赶回True,不然再次来到False。可迭代对象是空的False.

 

  1. technically speaking: a condition
    list—技能上讲:一个尺度列表 ↩
  2. 代码>>> global_space =
    {“a”:1,”b”:2} >>> exec(“c =
    100”,global_space) >>> print(global_space)
    会打印global_space里面有了__builtins__ ↩

if __name__==’__main__’:
  print(“modules”)
  stdoutToFile(“modules.txt”, help, “modules”)
  print(“builtins”)
  stdoutToFile(“builtins.txt”, help, “builtins”)
  print(“keywords”)
  stdoutToFile(“keyword.txt”, help, “keywords”)

>>> x = 1
>>> eval('x+1')
2

 

This function can also be used to execute arbitrary code objects (such
as those created by compile()). In this case pass a code object
instead of a string. If the code object has been compiled with 'exec'
as the mode argument, eval()‘s return value will be None.

唯独此代码中有个难点,modules和keywords会输出到同三个文件。为啥???

Hints: dynamic execution of statements is supported by the exec()
function. The globals() and locals() functions returns the current
global and local dictionary, respectively, which may be useful to pass
around for use by eval() or exec().

 

See ast.literal_eval() for a function that can safely evaluate strings
with expressions containing only literals.

二 keywords

说明:

help(“keywords”)

  

关键字:

  壹. 奉行动态语句,重回语句施行的值。

Here is a list of the Python keywords.  Enter any keyword to get more help.

>>> eval('1+2+3+4')
10

and                 elif                import              return
as                  else                in                  try
assert              except              is                  while
break               finally             lambda              with
class               for                 not                 yield
continue            from                or                  
def                 global              pass                
del                 if                  raise               

  2.
第二个参数为语句字符串,globals参数和locals参数为可选参数,如若提供,globals参数必需是字典,locals参数为mapping对象。

 

  叁.
globals参数用来钦命代码实行时方可使用的全局变量以及采访代码试行后的全局变量。

 

>>> g = {'num':2}

>>> eval('num + 2') #num未定义
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    eval('num + 2')
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined

>>> eval('num + 2',g) #g中有定义num,可执行
4

三 builtins

   四. locals参数用来钦命代码施行时能够运用的片段变量以及采访代码实施后的片段变量

help(“builtins”)

>>> g = {'num1':2}
>>> l = {'num2':4}
>>> eval('num1+num2',g,l)
6

放手类型:

   伍. 为了保证代码成功运营,globals参数字典不带有 __builtins__ 那一个key
时,Python会自动抬高2个key为 __builtins__ ,value为builtins模块的引用。要是真的要限量代码不行使builtins模块,必要在global增多贰个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

builtin class
CLASSES
    object
        BaseException
            Exception
                ArithmeticError
                    FloatingPointError
                    OverflowError
                    ZeroDivisionError
                AssertionError
                AttributeError
                BufferError
                EOFError
                EnvironmentError
                    IOError
                    OSError
                        WindowsError
                ImportError
                LookupError
                    IndexError
                    KeyError
                MemoryError
                NameError
                    UnboundLocalError
                ReferenceError
                RuntimeError
                    NotImplementedError
                StopIteration
                SyntaxError
                    IndentationError
                        TabError
                SystemError
                TypeError
                ValueError
                    UnicodeError
                        UnicodeDecodeError
                        UnicodeEncodeError
                        UnicodeTranslateError
                Warning
                    BytesWarning
                    DeprecationWarning
                    FutureWarning
                    ImportWarning
                    PendingDeprecationWarning
                    RuntimeWarning
                    SyntaxWarning
                    UnicodeWarning
                    UserWarning
            GeneratorExit
            KeyboardInterrupt
            SystemExit
        bytearray
        bytes
        classmethod
        complex
        dict
        enumerate
        filter
        float
        frozenset
        int
            bool
        list
        map
        memoryview
        property
        range
        reversed
        set
        slice
        staticmethod
        str
        super
        tuple
        type
        zip

>>> g = {}
>>> eval('abs(-1)',g)
1

>>> g = {'__builtins__':{}}
>>> eval('abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    eval('abs(-1)',g)
  File "<string>", line 1, in <module>
NameError: name 'abs' is not defined

 

   六.
当globals参数不提供是,Python暗许使用globals()函数再次来到的字典去调用。当locals参数不提供时,暗中认可使用globals参数去调用。

 

>>> num = 1
>>> eval('num+2')
3

>>> globals() #返回字典中含有num的key
{'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}

>>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    eval('num+2',{})
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined

>>> l = locals() 
>>> eval('num+2',{},l) #locals参数含有num的key,能求值
3

>>> locals()
{'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>> 

停放函数:

 

FUNCTIONS
    __build_class__(…)
        __build_class__(func, name, *bases, metaclass=None, **kwds) -> class
        
        Internal helper function used by the class statement.
    
    __import__(…)
        __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
        
        Import a module.  The globals are only used to determine the context;
        they are not modified.  The locals are currently unused.  The fromlist
        should be a list of names to emulate “from name import …”, or an
        empty list to emulate “import name”.
        When importing a module from a package, note that __import__(‘A.B’, …)
        returns package A when fromlist is empty, but its submodule B when
        fromlist is not empty.  Level is used to determine whether to perform 
        absolute or relative imports.  -1 is the original strategy of attempting
        both absolute and relative imports, 0 is absolute, a positive number
        is the number of parent directories to search relative to the current module.
    
    abs(…)
        abs(number) -> number
        
        Return the absolute value of the argument.
    
    all(…)
        all(iterable) -> bool
        
        Return True if bool(x) is True for all values x in the iterable.
    
    any(…)
        any(iterable) -> bool
88bifa必发唯一官网,        
        Return True if bool(x) is True for any x in the iterable.
    
    ascii(…)
        ascii(object) -> string
        
        As repr(), return a string containing a printable representation of an
        object, but escape the non-ASCII characters in the string returned by
        repr() using \x, \u or \U escapes.  This generates a string similar
        to that returned by repr() in Python 2.
    
    bin(…)
        bin(number) -> string
        
        Return the binary representation of an integer or long integer.
    
    chr(…)
        chr(i) -> Unicode character
        
        Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
        If 0x10000 <= i, a surrogate pair is returned.
    
    compile(…)
        compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
        
        Compile the source string (a Python module, statement or expression)
        into a code object that can be executed by exec() or eval().
        The filename will be used for run-time error messages.
        The mode must be ‘exec’ to compile a module, ‘single’ to compile a
        single (interactive) statement, or ‘eval’ to compile an expression.
        The flags argument, if present, controls which future statements influence
        the compilation of the code.
        The dont_inherit argument, if non-zero, stops the compilation inheriting
        the effects of any future statements in effect in the code calling
        compile; if absent or zero these statements do influence the compilation,
        in addition to any features explicitly specified.
    
    delattr(…)
        delattr(object, name)
        
        Delete a named attribute on an object; delattr(x, ‘y’) is equivalent to
        “del x.y”.
    
    dir(…)
        dir([object]) -> list of strings
        
        If called without an argument, return the names in the current scope.
        Else, return an alphabetized list of names comprising (some of) the attributes
        of the given object, and of attributes reachable from it.
        If the object supplies a method named __dir__, it will be used; otherwise
        the default dir() logic is used and returns:
          for a module object: the module’s attributes.
          for a class object:  its attributes, and recursively the attributes
            of its bases.
          for any other object: its attributes, its class’s attributes, and
            recursively the attributes of its class’s base classes.
    
    divmod(…)
        divmod(x, y) -> (div, mod)
        
        Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
    
    eval(…)
        eval(source[, globals[, locals]]) -> value
        
        Evaluate the source in the context of globals and locals.
        The source may be a string representing a Python expression
        or a code object as returned by compile().
        The globals must be a dictionary and locals can be any mapping,
        defaulting to the current globals and locals.
        If only globals is given, locals defaults to it.
    
    exec(…)
        exec(object[, globals[, locals]])
        
        Read and execute code from a object, which can be a string or a code
        object.
        The globals and locals are dictionaries, defaulting to the current
        globals and locals.  If only globals is given, locals defaults to it.
    
    format(…)
        format(value[, format_spec]) -> string
        
        Returns value.__format__(format_spec)
        format_spec defaults to “”
    
    getattr(…)
        getattr(object, name[, default]) -> value
        
        Get a named attribute from an object; getattr(x, ‘y’) is equivalent to x.y.
        When a default argument is given, it is returned when the attribute doesn’t
        exist; without it, an exception is raised in that case.
    
    globals(…)
        globals() -> dictionary
        
        Return the dictionary containing the current scope’s global variables.
    
    hasattr(…)
        hasattr(object, name) -> bool
        
        Return whether the object has an attribute with the given name.
        (This is done by calling getattr(object, name) and catching exceptions.)
    
    hash(…)
        hash(object) -> integer
        
        Return a hash value for the object.  Two objects with the same value have
        the same hash value.  The reverse is not necessarily true, but likely.
    
    hex(…)
        hex(number) -> string
        
        Return the hexadecimal representation of an integer or long integer.
    
    id(…)
        id(object) -> integer
        
        Return the identity of an object.  This is guaranteed to be unique among
        simultaneously existing objects.  (Hint: it’s the object’s memory address.)
    
    input(…)
        input([prompt]) -> string
        
        Read a string from standard input.  The trailing newline is stripped.
        If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
        On Unix, GNU readline is used if enabled.  The prompt string, if given,
        is printed without a trailing newline before reading.
    
    isinstance(…)
        isinstance(object, class-or-type-or-tuple) -> bool
        
        Return whether an object is an instance of a class or of a subclass thereof.
        With a type as second argument, return whether that is the object’s type.
        The form using a tuple, isinstance(x, (A, B, …)), is a shortcut for
        isinstance(x, A) or isinstance(x, B) or … (etc.).
    
    issubclass(…)
        issubclass(C, B) -> bool
        
        Return whether class C is a subclass (i.e., a derived class) of class B.
        When using a tuple as the second argument issubclass(X, (A, B, …)),
        is a shortcut for issubclass(X, A) or issubclass(X, B) or … (etc.).
    
    iter(…)
        iter(iterable) -> iterator
        iter(callable, sentinel) -> iterator
        
        Get an iterator from an object.  In the first form, the argument must
        supply its own iterator, or be a sequence.
        In the second form, the callable is called until it returns the sentinel.
    
    len(…)
        len(object) -> integer
        
        Return the number of items of a sequence or mapping.
    
    locals(…)
        locals() -> dictionary
        
        Update and return a dictionary containing the current scope’s local variables.
    
    max(…)
        max(iterable[, key=func]) -> value
        max(a, b, c, …[, key=func]) -> value
        
        With a single iterable argument, return its largest item.
        With two or more arguments, return the largest argument.
    
    min(…)
        min(iterable[, key=func]) -> value
        min(a, b, c, …[, key=func]) -> value
        
        With a single iterable argument, return its smallest item.
        With two or more arguments, return the smallest argument.
    
    next(…)
        next(iterator[, default])
        
        Return the next item from the iterator. If default is given and the iterator
        is exhausted, it is returned instead of raising StopIteration.
    
    oct(…)
        oct(number) -> string
        
        Return the octal representation of an integer or long integer.
    
    open(…)
        Open file and return a stream.  Raise IOError upon failure.
        
        file is either a text or byte string giving the name (and the path
        if the file isn’t in the current working directory) of the file to
        be opened or an integer file descriptor of the file to be
        wrapped. (If a file descriptor is given, it is closed when the
        returned I/O object is closed, unless closefd is set to False.)
        
        mode is an optional string that specifies the mode in which the file
        is opened. It defaults to ‘r’ which means open for reading in text
        mode.  Other common values are ‘w’ for writing (truncating the file if
        it already exists), and ‘a’ for appending (which on some Unix systems,
        means that all writes append to the end of the file regardless of the
        current seek position). In text mode, if encoding is not specified the
        encoding used is platform dependent. (For reading and writing raw
        bytes use binary mode and leave encoding unspecified.) The available
        modes are:
        
        ========= ===============================================================
        Character Meaning
        ——— —————————————————————
        ‘r’       open for reading (default)
        ‘w’       open for writing, truncating the file first
        ‘a’       open for writing, appending to the end of the file if it exists
        ‘b’       binary mode
        ‘t’       text mode (default)
        ‘+’       open a disk file for updating (reading and writing)
        ‘U’       universal newline mode (for backwards compatibility; unneeded
                  for new code)
        ========= ===============================================================
        
        The default mode is ‘rt’ (open for reading text). For binary random
        access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while
        ‘r+b’ opens the file without truncation.
        
        Python distinguishes between files opened in binary and text modes,
        even when the underlying operating system doesn’t. Files opened in
        binary mode (appending ‘b’ to the mode argument) return contents as
        bytes objects without any decoding. In text mode (the default, or when
        ‘t’ is appended to the mode argument), the contents of the file are
        returned as strings, the bytes having been first decoded using a
        platform-dependent encoding or using the specified encoding if given.
        
        buffering is an optional integer used to set the buffering policy. By
        default full buffering is on. Pass 0 to switch buffering off (only
        allowed in binary mode), 1 to set line buffering, and an integer > 1
        for full buffering.
        
        encoding is the name of the encoding used to decode or encode the
        file. This should only be used in text mode. The default encoding is
        platform dependent, but any encoding supported by Python can be
        passed.  See the codecs module for the list of supported encodings.
        
        errors is an optional string that specifies how encoding errors are to
        be handled—this argument should not be used in binary mode. Pass
        ‘strict’ to raise a ValueError exception if there is an encoding error
        (the default of None has the same effect), or pass ‘ignore’ to ignore
        errors. (Note that ignoring encoding errors can lead to data loss.)
        See the documentation for codecs.register for a list of the permitted
        encoding error strings.
        
        newline controls how universal newlines works (it only applies to text
        mode). It can be None, ”, ‘\n’, ‘\r’, and ‘\r\n’.  It works as
        follows:
        
        * On input, if newline is None, universal newlines mode is
          enabled. Lines in the input can end in ‘\n’, ‘\r’, or ‘\r\n’, and
          these are translated into ‘\n’ before being returned to the
          caller. If it is ”, universal newline mode is enabled, but line
          endings are returned to the caller untranslated. If it has any of
          the other legal values, input lines are only terminated by the given
          string, and the line ending is returned to the caller untranslated.
        
        * On output, if newline is None, any ‘\n’ characters written are
          translated to the system default line separator, os.linesep. If
          newline is ”, no translation takes place. If newline is any of the
          other legal values, any ‘\n’ characters written are translated to
          the given string.
        
        If closefd is False, the underlying file descriptor will be kept open
        when the file is closed. This does not work when a file name is given
        and must be True in that case.
        
        open() returns a file object whose type depends on the mode, and
        through which the standard file operations such as reading and writing
        are performed. When open() is used to open a file in a text mode (‘w’,
        ‘r’, ‘wt’, ‘rt’, etc.), it returns a TextIOWrapper. When used to open
        a file in a binary mode, the returned class varies: in read binary
        mode, it returns a BufferedReader; in write binary and append binary
        modes, it returns a BufferedWriter, and in read/write mode, it returns
        a BufferedRandom.
        
        It is also possible to use a string or bytearray as a file for both
        reading and writing. For strings StringIO can be used like a file
        opened in a text mode, and for bytes a BytesIO can be used like a file
        opened in a binary mode.
    
    ord(…)
        ord(c) -> integer
        
        Return the integer ordinal of a one-character string.
        A valid surrogate pair is also accepted.
    
    pow(…)
        pow(x, y[, z]) -> number
        
        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
    
    print(…)
        print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout)
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file: a file-like object (stream); defaults to the current sys.stdout.
        sep:  string inserted between values, default a space.
        end:  string appended after the last value, default a newline.
    
    repr(…)
        repr(object) -> string
        
        Return the canonical string representation of the object.
        For most object types, eval(repr(object)) == object.
    
    round(…)
        round(number[, ndigits]) -> number
        
        Round a number to a given precision in decimal digits (default 0 digits).
        This returns an int when called with one argument, otherwise the
        same type as the number. ndigits may be negative.
    
    setattr(…)
        setattr(object, name, value)
        
        Set a named attribute on an object; setattr(x, ‘y’, v) is equivalent to
        “x.y = v”.
    
    sorted(…)
        sorted(iterable, key=None, reverse=False) –> new sorted list
    
    sum(…)
        sum(iterable[, start]) -> value
        
        Returns the sum of an iterable of numbers (NOT strings) plus the value
        of parameter ‘start’ (which defaults to 0).  When the iterable is
        empty, returns start.
    
    vars(…)
        vars([object]) -> dictionary
        
        Without arguments, equivalent to locals().
        With an argument, equivalent to object.__dict__.

 

 

四 modules

help(“modules”)

python安装后含有的modules:

Please wait a moment while I gather a list of all available modules…

WConio              base64              importlib           shelve
_WConio             bdb                 inspect             shlex
__future__          binascii            io                  shutil
_abcoll             binhex              itertools           signal
_ast                bisect              json                site
_bisect             build_class         keyword             smtpd
_codecs             builtins            lib2to3             smtplib
_codecs_cn          bz2                 linecache           sndhdr
_codecs_hk          cProfile            locale              socket
_codecs_iso2022     calendar            logging             socketserver
_codecs_jp          cgi                 macpath             sqlite3
_codecs_kr          cgitb               macurl2path         sre_compile
_codecs_tw          chunk               mailbox             sre_constants
_collections        cmath               mailcap             sre_parse
_compat_pickle      cmd                 marshal             ssl
_csv                code                math                stat
_ctypes             codecs              mimetypes           stdredirect
_ctypes_test        codeop              mmap                string
_dummy_thread       collections         modulefinder        stringprep
_elementtree        colorsys            msilib              struct
_functools          compileall          msvcrt              subprocess
_hashlib            configparser        multiprocessing     sunau
_heapq              contextlib          netrc               symbol
_io                 copy                nntplib             symtable
_json               copyreg             nt                  sys
_locale             csv                 ntpath              tabnanny
_lsprof             ctypes              nturl2path          tarfile
_markupbase         curses              numbers             telnetlib
_md5                datetime            opcode              tempfile
_msi                dbm                 operator            test
_multibytecodec     decimal             optparse            textwrap
_multiprocessing    difflib             os                  this
_pickle             dis                 os2emxpath          thread
_pyio               distutils           parser              threading
_random             doctest             pdb                 time
_sha1               dummy_threading     pickle              timeit
_sha256             email               pickletools         tkinter
_sha512             encodings           pipes               token
_socket             errno               pkgutil             tokenize
_sqlite3            filecmp             platform            trace
_sre                fileinput           plistlib            traceback
_ssl                fnmatch             poplib              tty
_strptime           formatter           posixpath           turtle
_struct             fractions           pprint              types
_subprocess         ftplib              profile             unicodedata
_symtable           functools           pstats              unittest
_testcapi           gc                  pty                 urllib
_thread             genericpath         py_compile          uu
_threading_local    getopt              pyclbr              uuid
_tkinter            getpass             pydoc               warnings
_warnings           gettext             pydoc_data          wave
_weakref            glob                pyexpat             weakref
_weakrefset         gzip                pythontips          webbrowser
abc                 hashlib             queue               winreg
activestate         heapq               quopri              winsound
aifc                hmac                random              wsgiref
antigravity         html                re                  xdrlib
array               http                reprlib             xml
ast                 httplib2            rlcompleter         xmlrpc
asynchat            idlelib             rpyc                xxsubtype
asyncore            imaplib             runpy               zipfile
atexit              imghdr              sched               zipimport
audioop             imp                 select              zlib

Enter any module name to get more help.  Or, type “modules spam” to search
for modules whose descriptions contain the word “spam”.

 

 

完!