[转载] (三)Python关键字和内置函数

参考链接: Python中的数学函数 4(特殊函数和常量)

一、Python的关键字 

和其他语言一样,关键字有特殊含义,并且关键字不能作为变量名、函数名、类名等标识符。 快速查看关键字的方法除了上csdn和百度搜索外,还可以在命令行交互环境中查看 

>>> from keyword import kwlist

>>> print(kwlist)

['False', 'None', 'True', 'and',

 'as', 'assert', 'async', 'await', 

 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 

'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 

'is', 'lambda', 'nonlocal', 'not', 

'or', 'pass', 'raise', 'return', 

'try', 'while', 'with', 'yield'

]

 

在python3.5更新后,关键字中加入了异步关键字async和await。 

这些关键字在各个章节中会介绍。 

二、Python内置函数(库) 

了解python内置函数的使用(扩展库,自定义函数、库),都可以这样做 

在命令行中输入help('func'),参数为函数名的字符串,会显示相关库、函数、类等的文档 

>>>help('math') #数学运算库的文档

 

Help on module math:

 

NAME

    math

 

MODULE REFERENCE

    https://docs.python.org/3.7/library/math

    

    The following documentation is automatically generated from the Python

    source files.  It may be incomplete, incorrect or include features that

    are considered implementation detail and may vary between Python

    implementations.  When in doubt, consult the module reference at the

    location listed above.

 

DESCRIPTION

    This module provides access to the mathematical functions

    defined by the C standard.

 

FUNCTIONS

    acos(x, /)

        Return the arc cosine (measured in radians) of x.

    

    acosh(x, /)

        Return the inverse hyperbolic cosine of x.

    

    asin(x, /)

        Return the arc sine (measured in radians) of x.

    

    asinh(x, /)

        Return the inverse hyperbolic sine of x.

:

#节选了文档中的一部分内容

 

>>>help('abs') #绝对值函数的说明

 

Help on built-in function abs in module builtins:

abs(x, /)

    Return the absolute value of the argument.

 

 

第二种方法是,如果使用ipython交互环境,可以直接使用 func + ? 的方式获得帮助 

In [8]: time?

Out[9]:

Docstring:

Time execution of a Python statement or expression.

 

The CPU and wall clock times are printed, and the value of the

expression (if any) is returned.  Note that under Win32, system time

is always reported as 0, since it can not be measured.

 

This function can be used both as a line and cell magic:

 

- In line mode you can time a single-line statement (though multiple

  ones can be chained with using semicolons).

 

- In cell mode, you can time the cell body (a directly

  following statement raises an error).

 

This function provides very basic timing functionality.  Use the timeit

magic for more control over the measurement.

 

.. versionchanged:: 7.3

    User variables are no longer expanded,

    the magic line is always left unmodified.

 

Examples

--------

::

 

  In [1]: %time 2**128

  CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s

  Wall time: 0.00

  Out[1]: 340282366920938463463374607431768211456L

 

:

 

 

In [13]: math.sin?                                         

Signature: math.sin(x, /)

Docstring: Return the sine of x (measured in radians).

Type:      builtin_function_or_method

 

有了这个,可以很快地查看帮助文档而不是网上搜索辣。 

使用dir(__builtins__) 

In [14]: dir(__builtins__)                                 

Out[14]: 

['ArithmeticError',

 'AssertionError',

 'AttributeError',

 'BaseException',

 'BlockingIOError',

 'BrokenPipeError',

 'BufferError',

 'BytesWarning',

 'ChildProcessError',

 'ConnectionAbortedError',

 'ConnectionError',

 'ConnectionRefusedError',

 'ConnectionResetError',

 'DeprecationWarning',

 'EOFError',

 'Ellipsis',

 'EnvironmentError',

 'Exception',

 'False',

 'FileExistsError',

 'FileNotFoundError',

 'FloatingPointError',

 'FutureWarning',

 'GeneratorExit',

 'IOError',

 'ImportError',

 'ImportWarning',

 'IndentationError',

 'IndexError',

 'InterruptedError',

 'IsADirectoryError',

 'KeyError',

 'KeyboardInterrupt',

 'LookupError',

 'MemoryError',

 'ModuleNotFoundError',

 'NameError',

 'None',

 'NotADirectoryError',

 'NotImplemented',

 'NotImplementedError',

 'OSError',

 'OverflowError',

 'PendingDeprecationWarning',

 'PermissionError',

 'ProcessLookupError',

 'RecursionError',

 'ReferenceError',

 'ResourceWarning',

 'RuntimeError',

 'RuntimeWarning',

 'StopAsyncIteration',

 'StopIteration',

 'SyntaxError',

 'SyntaxWarning',

 'SystemError',

 'SystemExit',

 'TabError',

 'TimeoutError',

 'True',

 'TypeError',

 'UnboundLocalError',

 'UnicodeDecodeError',

 'UnicodeEncodeError',

 'UnicodeError',

 'UnicodeTranslateError',

 'UnicodeWarning',

 'UserWarning',

 'ValueError',

 'Warning',

 'ZeroDivisionError',

 '__IPYTHON__',

 '__build_class__',

 '__debug__',

 '__doc__',

 '__import__',

 '__loader__',

 '__name__',

 '__package__',

 '__spec__',

 'abs',

 'all',

 'any',

 'ascii',

 'bin',

 'bool',

 'breakpoint',

 'bytearray',

 'bytes',

 'callable',

 'chr',

 'classmethod',

 'compile',

 'complex',

 'copyright',

 'credits',

 'delattr',

 'dict',

 'dir',

 'display',

 'divmod',

 'enumerate',

 'eval',

 'exec',

 'filter',

 'float',

 'format',

 'frozenset',

 'get_ipython',

 'getattr',

 'globals',

 'hasattr',

 'hash',

 'help',

 'hex',

 'id',

 'input',

 'int',

 'isinstance',

 'issubclass',

 'iter',

 'len',

 'license',

 'list',

 'locals',

 'map',

 'max',

 'memoryview',

 'min',

 'next',

 'object',

 'oct',

 'open',

 'ord',

 'pow',

 'print',

 'property',

 'range',

 'repr',

 'reversed',

 'round',

 'set',

 'setattr',

 'slice',

 'sorted',

 'staticmethod',

 'str',

 'sum',

 'super',

 'tuple',

 'type',

 'vars',

 'zip']

 

三、Python的常用内置函数 

1. 类型转换和判断 

类型转换 

In [20]: bin(55) #转换为二进制                             

Out[20]: '0b110111'

 

In [21]: oct(33) #转换为八进制                             

Out[21]: '0o41'

 

In [22]: hex(114514) #转换为十六进制                       

Out[22]: '0x1bf52'

 

In [23]: int('123') #转换为整数                            

Out[23]: 123

 

In [24]: int('0xff2', 16) #转换十六进制数字符串,要加上16参数                                                

Out[24]: 4082

 

In [25]: float(3) #转换成浮点数                            

Out[25]: 3.0

 

In [26]: complex(3,4) #按照实部和虚部生成复数              

Out[26]: (3+4j)

 

In [27]: ord('野') #转换字符为unicode编码                  

Out[27]: 37326

 

In [28]: chr(114514) #得到数字对应的Unicode字符            

Out[28]: '\U0001bf52'

 

In [29]: str([1,2,3]) #转换其他类型为字符串类型            

Out[29]: '[1, 2, 3]'

 

In [30]: ascii('A') #获得字符的Ascii编码                   

Out[30]: "'A'"

 

In [31]: type('sss') #获得某个变量或者常量的类型           

Out[31]: str

 

 

2. 基本输入输出 

>>>print('name{}'.format(3+1))

name4

>>>t = input('请输入一个数字')

请输入一个数字1

>>>print(t)

1

 

使用print函数默认是换行的,如果不想换行,可以设置参数 

In [2]: for i in range(1000,1050): 

   ...:     print(chr(i), end='') 

   ...:                                                                         

ϨϩϪϫϬϭϮϯϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙ

 

3. 将字符串转换成可执行命令 

函数eval()提供了将字符串转换成可执行命令的功能 

In [3]: eval('1 + 2')                                                           

Out[3]: 3

 

In [4]: eval('print("name")')                                                   

name

你可能感兴趣的:([转载] (三)Python关键字和内置函数)