第二章

IPython基础

运行IPython命令行

C:\Users\chen5>ipython
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: a = 5

In [2]: a
Out[2]: 5

In [3]: import numpy as np

In [4]: data = {i : np.random.randn() for i in range(7)}

In [5]: data
Out[5]:
{0: -0.6126392548071153,
1: -2.160489745375714,
2: -1.0292318083104628,
3: 0.9929643077235,
4: 0.5220025269732854,
5: 1.509591474490788,
6: 0.34011264332460117}


前两行是python语句,其中第二行创建了一个名为data的变量,并引用了新建的python字典。最后一行在控制台打印了data的值。

In [6]: print(data)
{0: -0.6126392548071153, 1: -2.160489745375714, 2: -1.0292318083104628, 3: 0.9929643077235, 4: 0.5220025269732854, 5: 1.509591474490788, 6: 0.34011264332460117}


print语句与打印变量的区别。

运行Jupyter notebook

Jupyter项目中的主要组件就是notebook,是一种交互式的文档类型。

内省

在一个变量名的前后使用问号 ? 可以显示一些关于该对象的概要信息

In [10]: b = [1, 2, 3]

In [11]: b?
Type: list
String form: [1, 2, 3]
Length: 3
Docstring:
Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.

In [12]: print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

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.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method


使用双问号可以显示函数的源代码

IPython介绍