
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
3.3 行与缩进

通常来说,一条Python语句应在一行内写完,但如果语句很长,可以使用反斜杠“\”来实现多行语句,例如:

需要注意的是,在成对的大括号“{}”、中括号“[]”或小括号“()”中的多行语句,不需要使用反斜杠“\”,例如:

可见,在编写程序时使用的是物理行,Python环境使用的则是逻辑行。在Python中可以使用分号“;”标识一个逻辑行的结束,但为了避免使用分号,通常在每个物理行中只写一个逻辑行。
Python最具特色的语法是使用缩进来表示代码块,好处是不需要像其他语言一样使用大括号“{}”。行首的空白(空格或制表符)用来决定逻辑行的缩进层次,从而决定语句的分组(即代码块),这意味着不同代码块缩进的距离(即行首空白)可以不同,但同一代码块的语句必须有相同的缩进距离,每一组这样的语句称为一个代码块。例如:


而以下代码由于最后一行语句缩进距离不一致,运行时将出现如图3-5所示的错误。


图3-5 缩进距离不一致导致运行错误

不要混合使用空格和制表符来缩进,这将导致同一段Python代码在不同的操作系统中无法正常工作。