
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.2.3 代码换行与并行
在编写Python程序的过程中,有时会遇到两行代码放在同一行更易懂,或者为了显得结构清晰,过长的代码不适合放在同一行的情形。下面将探讨在Python中如何处理代码换行与并行的问题。
1.代码换行
在Python编程中,一般在一行写完所有代码,如果遇到一行写不完需要换行的情形,则也允许采用代码换行的方式将一行代码分成多行编写。有如下4种方法可供选择。
【范例2-4】代码换行。
(1)在该行代码末尾加上续行符“\”。

(2)语句中包含()、{}、[],分行不需要加换行符。

(3)采用3个单引号。

(4)采用3个双引号。

2.代码并行
在Python代码缩进语句块中,如果只有一条语句,那么,将下一行代码直接写在“:”后面也是正确的。
【范例2-5】代码并行。

在上述代码中,第3、8行代码是不允许并到上一行代码“:”后面的。这是因为这两行代码中包含一个判断语句块,不是一条独立的语句。其他代码并行后的效果如下:
