Python Statement
Python Statement
Instructions that a python interpreter can execute are all statement.
for example, a=1 is an assignment statement.
if statement, for statement, while statement, etc., are other kind of statements which will be discussed later.
Multi-line statement
In python, end of a statement is marked by a new character. But we can make a statement extend over multiple lines with the line continuation character (\).
For example
1 2 3 | a = 1 + 2 + 3 + \ 4 + 5 + 6 + \ 7 + 8 + 9 |
this is explicit line continuation. In python, line continuation is implied inside parentheses( ), breackets [ ] and braces { }.
For instance, we can implement the above multi-line statement as
1 2 3 | a = ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 ) |
Here, the surrounding parentheses ( ) do the line continuation implicity. Same is the case with [ ] and { }.
For example,
1 2 3 | colors = [ 'red' , 'blue' , 'green' ] |
We can also put multiple statements in a single line using semicolons, as follows:
1 | a = 1 ; b = 2 ; c = 3 ; |
Python Indentation
Most of the programming language like C, C++ and Java use braces { } to define a block of code. Python however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four white-spaces are used for indentation and are preferred over tabs. Here is an example.
1 2 3 4 | for i in range ( 1 , 11 ): print (i) if i = = 5 : break |
and
1 | if True : print ( 'Hello' ); a = 5 |
both are valid and do the same thing, but the former style is clearer.
Incorrect indentation will result in IndentationError
.
No comments:
Post a Comment