购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

2.1 Python快速入门

2.1.1 第一个Python程序

打开Jupyter Notebook,就可以在编辑单元(Cell)中编写程序了,如输入命令:print(“hellow world”) #第一个Python程序。点击“运行”或使用快捷键“Ctrl”+“Enter”(或“Shift”+“Enter”)运行程序。程序和结果详见图2-1。

图2-1 第一个Python程序

程序行中,#号后的内容为该程序的注释。Python中,单行注释以#开头。

注意:在Jupyter Notebook中,如果在每个编辑单元只输出一个命令结果,可以不使用print函数;如果要同时输出多个命令的结果,需要使用print函数(图2-2)。

图2-2 使用print函数输出多个结果

2.1.2 Python的缩进

Python使用空白字符(“Tab”键和4个空格)来组织代码(R使用括号,SAS使用分号)。在Python的流程控制语句、函数定义、异常处理等语句中,用行尾的冒号和下一行的缩进表示下一个代码块的开始,而缩进的结束则表示此代码块的结束。在其他编程语言中使用缩进多是为了提高可读性,而在Python中对代码缩进的要求非常严格,同一个级别代码块的缩进量必须一样,否则解释器会报“SyntaxError”错误。例如if-else语句(代码清单2-1),冒号之后所有代码的缩进量必须相同,直到代码块结束为止。

代码清单2-1 缩进示例

2.1.3 查询帮助文件

Python语言及其数据科学生态系统是根据用户需求而创建的,在编程过程中可以轻松获取帮助文件。

(1)使用help()函数获取print函数的帮助文件

命令:help(print)

输出结果:

Help on built-in function print in module builtins:print(...)

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.

(2)使用问号“?”获取print函数的帮助文件

命令: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

2.1.4 Tab键自动补全代码

在Jupyter Notebook中编写代码时,可以使用“Tab”键自动补全代码。这是个非常实用的技巧,可以提示接下来的可能代码,快速完成代码编写,节省时间。例如在导入库时,输入“import pan”,按“Tab”键可以自动补全“import pandas”。 CoxFmbYmpm/sCzNgdicog4S7mxMbndK6f+UbzPkpVmxJSRVbKDCZ9RxBKrrKFQYM

点击中间区域
呼出菜单
上一章
目录
下一章
×