Python Statement, Indentation and Comments#
You will learn about Python statements, why indentation is important and use of comments in programming.
Statement#
Instructions that a Python interpreter can execute are called statements. For example, a = 1
is an assignment statement. if
statement, for
statement, while
statement, etc. are other kinds of statements which will be discussed later.
Multi-line statement#
In Python, the end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character \
.
>>> 1+2
>>> +3 #illegal continuation of the sum
A single backslash at the end of the line can also be used to indicate that a statement is still incomplete
>>> 1 + \
>>> 2 + 3 # this is also okay
For example:
1+2 # assignment line 1
+3 # assignment line 2
# Python is only calculating assignment line 1
3
1+2 \ # '\' means assignment line is continue to next line
+3
Note: This would result in error because there should be no comment
#
or space after\
.
# Method 1:
1+2 \
+3
6
1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
45
This is an explicit line continuation. In Python, line continuation is implied inside:
parentheses
( )
, For Example:
(1+2 + 3) # perfectly OK even with spaces
2. brackets **`[ ]`**, and
3. braces **`{ }`**.
For instance, we can implement the above multi-line statement as:
# Method 2:
(1+2
+3)
6
(1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
45
Here, the surrounding parentheses ( )
do the line continuation implicitly. Same is the case with [ ]
and { }
. For example:
['red',
'blue',
'green', '99']
['red', 'blue', 'green', '99']
Python Indentation#
No spaces or tab characters allowed at the start of a statement: Indentation plays a special role in Python (see the section on control statements). For now simply ensure that all statements start at the beginning of the line.
Most of the programming languages like C, C++, and Java use braces { }
to define a block of code. Python, however, uses indentation.
A comparison of C & Python will help you understand it better.
In the case of Python, indentation is not for styling purpose. It is rather a requirement for your code to get compiled and executed. Thus it is mandatory!!!
for i in range(1,11):
print(i) #press "Tab" one time for 1 indentation
if i == 6:
break
1
2
3
4
5
6
The enforcement of indentation in Python makes the code look neat and clean. This results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but itβs always a good idea to indent. It makes the code more readable. For example:
if True:
print('Hello')
a = 6
Hello
or
if True: print('Hello'); a = 6
Hello
both are valid and do the same thing, but the former style is clearer.
Incorrect indentation will result in IndentationError
.
Python Comments#
In Python, we use the hash #
symbol to start writing a comment.
Generally, comments will look something like this:
#This is a Comment
Comments are in the source code for humans to read, not for computers to execute.
#This is a Comment
1. Single lined comment:#
In case user wants to specify a single line comment, then comment must start with #
.
#This is single line comment.
#This is single line comment.
2. Inline comments#
If a comment is placed on the same line as a statement, it is called an inline comment. Similar to the block comment, an inline comment begins with a single hash (#) sign and followed by a space and comment.
>>>n+=1 # increase/add n by 1
n=9
n+=1 # increase/add n by 1
n
10
3. Multi lined comment:#
We can have comments that extend up to multiple lines. One way is to use the hash #
symbol at the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
#This is a comment
#print out Hello
print('Hello')
Hello
Another way of doing this is to use triple quotes, either '''
or """
.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-line comment as well. Unless they are not docstrings.
#single line comment
>>>print ("Hello Python"
'''This is
multiline comment''')
"""This is also a
perfect example of
multi-line comments"""
'This is also a\nperfect example of\nmulti-line comments'
'''This is also a
perfect example of
multi-line comments'''
'This is also a\nperfect example of\nmulti-line comments'
#single line comment
print ("Hello Python"
'''This is
multiline comment''')
Hello PythonThis is
multiline comment
Docstrings in Python#
A docstring is short for documentation string.
Triple quotes are used while writing docstrings. For example:
>>>def double(num):
>>> """Function to double the value"""
>>> return 3*num
Docstrings appear right after the definition of a function, class, or a module.
The docstrings are associated with the object as their __doc__
attribute.
So, we can access the docstrings of the above function with the following lines of code:
def double(num):
"""Function to double the value"""
return 3*num
print(double.__doc__)
Function to double the value
To learn more about docstrings in Python, visit Python Docstrings .
Help topics#
Python has extensive help built in. You can execute help()
for an overview or help(x)
for any library, object or type x
. Try using help("topics")
to get a list of help pages built into the help system.
help("topics")
help("topics")
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DELETION LOOPING SHIFTING
ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS
ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES
ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS
BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS
BINARY EXECUTION NONE STRINGS
BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS
BOOLEAN FLOAT NUMBERS TRACEBACKS
CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE
CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS
CLASSES FRAMES PACKAGES TUPLES
CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS
COMPARISON IDENTIFIERS PRECEDENCE TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS
DEBUGGING LITERALS SEQUENCES