Python Statements, Comments & Indentation Tutorial

In this tutorial we learn about execution statements, documenting our code with comments, and how indentation defines scope.

Statements

A statement is a line of code that the Python interpreter can execute. In Python a statement is terminated by a carriage return (a new line character).

In many other languages such as C , C# , Java etc. statements are terminated with a ; (semicolon).

In Python we don’t need the semicolon and can simply hit the Enter key to create a new line and end the statement.

Example:
message = "Hello World!"
print(1 + 2)
shopping_list = ["Bread", "Milk"]

Each of the lines in the example above is a single statement.

One statement on multiple lines

Python allows us to break some statements into multiple lines by using a single \ (backslash).

We write a space and a backslash where we want the statement to cut and continue the statement on a new line.

Example: break a statement onto multiple lines
# single line
result = 1 + 2

# multi line
result = 1 \
         + \
         2
Example: break a string onto multiple lines in source code
# single line
message = "Python is one of the best programming languages in the world"

# multi line
message = "Python is one of the best" \
          "programming languages in " \
          "the world"

Multiple statements on one line

If we want to write multiple statements on one line we have to terminate each statement with a ; (semicolon).

Example: multiple statements on one line
 message = "Hello World!"; print(1 + 2); shopping_list = ["Bread", "Milk"]

Indentation & Scope

We will often need to define a set of multiple statements into a code block. Most other general programming languages define code blocks with { } (open and close curly braces).

In Python we use a single indentation to define a code block, everything on the same indentation will be in that scope.

Example: code block in Python
if 1 == 1:
    print(True)
    # block of statements, everything
    # in this indentation level will
    # be considered as part of this
    # scope

# if we move back an indentation, we
# are outside of the scope of the
# code block above

We are allowed to have multiple statements in each indentation level, and multiple indentation levels.

Because indentation defines scope, we are almost forced into indenting our statements. This results in code that is easy to read, neat and consistent.

In general, a tab consisting of four spaces is considered one indentation level. If you want to edit the default indentation settings in Pycharm, go to File > Settings > Editor > Code Style > Python > Tabs and Indents.

Comments

Comments are a way for programmers to document their code and to enhance its readability. Python comments are ignored by the interpreter, which means the interpreter won’t try to execute any text written inside a comment.

In general, our code should be written cleanly and clearly enough so that it’s obvious as to what the code does. In most cases our code won’t need comments, but there are situations where we should include comments.

  • When learning we’re not yet used to how a language operates and even if we know another language, Python might behave differently to what we’re used to.
  • When we’re working on projects as part of a group we want to comment our code so that other programmers immediately understand what’s going on.
  • When using external libraries we should comment what non-obvious things do so that it’s not necessary to go back and forth to the library’s documentation for lookup in the future.
  • Commenting on complex code is useful to quickly see what it’s doing or what it’s for.
  • In some cases we may want to temporarily disable a piece of code, we can simply comment it out.

Line comment

In Python we have two ways to comment our code, single and (technically) multi-line comments.

To write a single line comment, commonly referred to as a line comment, we simply preface a line of text with a # (octothorp - more commonly known as the pound symbol or hashtag).

Example: single line comment
# this is a single line comment, it only spans one line

The interpreter will look at the code and skip anything after the octothorp on that single line. Single line comments can be written after code as well, but not between code.

Example:
print("Hello there") # valid comment

print(# will produce an error "Hello there")

In the example above our first statement has a comment after the code, known as an inline comment, the interpreter parses the code and when it gets to the octothorp it skips to the next line.

Our second statement has a single line comment inside the code, when the interpreter gets to the octothorp it will skip to the next line but realize that the print function is missing its closing parentheses.

The interpreter will then stop and raise a SyntaxError:

Output:
 SyntaxError: unexpected EOF while parsing

Block comment, multi-line comment, docstrings

Python doesn’t have block comments as other languages do. Programmers have taken to using multi-line strings as block comments, or docstrings where appropriate.

A multi-line string in Python is wrapped with 3 quotes (single or double).

Example:
# multi-line string
"""This is a
string that
can fit onto
multiple lines"""

# single line string
"This string can only fit on a single line"

A multi-line string is treated as a regular string but if they’re not assigned to a data container, such as a variable, Python will garbage collect it (throw it away) at some time after code executes. This way, they can act as block comments.

Even though the creator of Python said it could be done ( Twitter: Guido van Rossum ‏@gvanrossum 10 Sep 2011 ), that doesn’t mean it should be done.

tip Multi-line strings affect memory allocation in the interpreter, so they will affect the performance of the application (even if just a tiny bit). It’s better practice to get used to your IDE’s shortcut for line comments.

Docstrings are also multi-line strings but they occur as the first statement in a class, method, module or function definition. They’re used to provide documentation on the surrounding code.

Example: a docstring
def is_odd_or_even(num):
    """Checks if a number is even or odd"""
    if num % 2 == 0:
        print(num, "is an even number")
    else:
        print(num, "is an odd number")

print(is_odd_or_even.__doc__)

In the example above, our docstring is the first statement inside the function code block so it will be recognized as a docstring.

We can access the docstring with __doc__ which is especially useful when the project is split into multiple files.

IDE Comment shortcuts (PyCharm)

Most IDE programs include a shortcut to quickly comment out lines of code. If you’re not using PyCharm as your IDE, you may have to search online for its shortcuts or comment addons/extensions.

PyCharm: Line comment shortcut

Highlight the line, or lines, that you want to comment out and press Ctrl / in Windows or Cmd / in Mac.

Or in the main menu, choose Code > Comment with Line Comment

Summary: Points to remember

  • A statement is a single line of code and is terminated by a new line.
  • We can break up a statement into multiple lines with a \ (backslash).
  • We can write multiple statements on one line if each statement is terminated by a ; (semicolon).
  • Indentation defines scope for a code block.
  • Comments are prefixed with a # octothorp and are ignored by the compiler
    • Multi-line strings as comments are considered bad practice and not recommended.
    • PyCharm comment shortcut is Ctrl / or Cmd / on highlighted lines.