打开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函数输出多个结果
Python使用空白字符(“Tab”键和4个空格)来组织代码(R使用括号,SAS使用分号)。在Python的流程控制语句、函数定义、异常处理等语句中,用行尾的冒号和下一行的缩进表示下一个代码块的开始,而缩进的结束则表示此代码块的结束。在其他编程语言中使用缩进多是为了提高可读性,而在Python中对代码缩进的要求非常严格,同一个级别代码块的缩进量必须一样,否则解释器会报“SyntaxError”错误。例如if-else语句(代码清单2-1),冒号之后所有代码的缩进量必须相同,直到代码块结束为止。
Python语言及其数据科学生态系统是根据用户需求而创建的,在编程过程中可以轻松获取帮助文件。
命令: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.
命令: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
在Jupyter Notebook中编写代码时,可以使用“Tab”键自动补全代码。这是个非常实用的技巧,可以提示接下来的可能代码,快速完成代码编写,节省时间。例如在导入库时,输入“import pan”,按“Tab”键可以自动补全“import pandas”。