Multi-line Statements
A brief introduction to multi-line statements and usage.
Python codes are merely just text, aka physical lines. Python compiles physical lines into logical lines then tokenise them.
Physical line end with a physical newline character. Logical line end with a logical NEWLINE token.
Physical newline vs logical newline
Physical newlines are ignored in order to combine multiple physical lines into a single logical line of code terminated by a logical NEWLINE token.
Conversion from physical line to logical line can either be implicit
or explicit
.
Implicit
Implicit conversion of multiple physical lines into a logical line happen automatically by Python without the user.
These expressions support are implicitly convert multiple physical lines into a logical line:
list literals: [ ]
Python implicitly understand that there is continuation of lines
tuple literals: ( )
dictionary literals: { }
set literals: { }
function arguments / parameters
supports inline comments
Explicit
Explicit conversion of multiple physical lines into a logical line happen where the user explicitly tells Python.
You can break up statements over multiple lines explicitly, by using the (backslash
) character. Multi-line statements are not implicitly converted to a single logical line.
When we write codes, we do not want to have very long lines and have to keep readability in mind. In this example the code works as intended.
But this one fails because Python cannot implicitly understand that there is continuation.
We can explicitly tell Python that there is continuation by adding backslash \
.The code runs successfully and prints the below output.
We can also use parenthesis ()
to explicitly tell the physical lines about continuation.
Multi-line Strings
Multi-line string literals can be created using triple delimiters (' single
or " double
)
A multi-line string is just a regular string.
Basically, whatever you type is part of your multi-line comment such as tabs, spaces, newlines etc. are part of your multi-line statement
You can use escaped characters (e.g. \n
, \t
), use string formatting.
Multi-line strings are not comments, although they can be used as such, especially with special comments called docstrings
.
Last updated