REPL

REPL是一种用Python与计算机交谈的交互方式。为了使这项工作,计算机做了四件事:

1、Read the user input (你的Python命令).

2、Evaluate your code (弄清楚你的意思).

3、Print any results (你可以看到计算机的响应).

4、Loop back to step 1 (继续第一步).

术语“REPL”是Read,Evaluate,Print和Loop的首字母缩写,因为这正是计算机所做的......

计算机通过向您显示三个V形符号>>>或编号提示符In [1]:来告诉您它正在等待指令。

你在需要“解决问题”时使用REPL,由于您从REPL获得的即时反馈,因此可以轻松地即兴发挥,深入研究计算机正在做什么。

虽然所有REPL都以相同的方式工作,但REPL的特性和功能将根据您目前使用的模式而有所不同。但是,有两个命令适用于所有版本的REPL,这些命令非常有用:dirhelp

dir令告诉你它是什么。如果您自己使用它,它会告诉您Python目前所知道的内容:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

虽然这个名称列表目前可能看起来很神秘,但如果你创建一个新变量,你会在Python知道的事物列表中看到它:

>>> name = "Nicholas"
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'name']

但是dir可以做得更多!如果你使用Python知道的东西的名称,那么dir将返回该东西的所有属性。例如,name变量实际上是一个字符串对象,字符串对象具有各种有用的属性。如果我想知道它们是什么,我会将name对象传递给 dir这样:

>>> dir(name)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']

这有很多属性!鉴于其中一些的名称,它们可能非常有用。例如,假设我想获得该name对象的大写版本。我注意到upper返回的列表中有一个属性,dir所以我需要一些方法来检查它的作用。这是help它自己的地方。如果你传递了Python知道的东西,help它会回复一些有用的文档:

>>> help(name.upper)
Help on built-in function upper:

upper(...) method of builtins.str instance
    S.upper() -> str

    Return a copy of S converted to uppercase.

第一行告诉您这upper是内置字符串类的方法。第二行告诉您调用的upper结果会产生一个新的字符串(-> str)。最后一行包含一个简单的英文描述 upper。所以,我应该期望它返回值的大写版本name

>>> name.upper()
`NICHOLAS`

只需使用dirhelp命令,您就可以查询和查询整个Python。


举个例子

让我们假装你需要做一些算术,那么为什么不把REPL用作计算器呢?

>>> 1 + 1
2
>>> 10 - 1
9
>>> (5 * 5 + 5 ) / 4
7.5

更高级的数学最初可能不会出现。但是,如果我们导入math模块并使用dirhelp我们很快就会找到我们可能需要的东西:

>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'tau', 'trunc']
>>> help(math.sqrt)
Help on built-in function sqrt in module math:

sqrt(...)
    sqrt(x)

    Return the square root of x.

>>> math.sqrt(12345)
111.1080555135405

就像在“普通”Python中一样,您可以导入模块,为对象赋值,使用函数和创建循环:

>>> import random
>>> names = ['Lisa', 'Kushal', 'Mary', 'Kate', 'Carlos', 'Zander', ]
>>> while True:
...   print(random.choice(names))
...   wait = input()
...
Kate
Kate
Zander
Mary
Zander
Kushal

要打破无限循环,你需要按CTRL-C。这将导致显示如下消息:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt