Python Statements, Comments & Indentation

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++, C#, Java etc. statements are terminated with a semicolon ( ; ).

In Python, we don’t need the semicolon and can simply hit the Enter/Return 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 the backslash operator ( \ ).

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 linesCOPY

Example

# single line result = 1 + 2 # multi line result = 1 \ + \ 2

Break a string onto multiple lines in source code

Example

# 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 the semicolon operator ( ; ).

Example

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. Languages such as C, C++, C#, Java etc. 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 PythonCOPY

Example

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 an octothorp # , more commonly known as the pound symbol or hashtag.Example: single line commentCOPY

Example

# 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:COPY

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

Inline comments should be used sparingly when coding in a real world scenario, specially when working in a team. People often find inline comments unnecessary and distracting.

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.

Multi-line strings do affect memory allocation in the interpreter and so will affect 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 it occurs as the first statement in a class, method, module or function definition. It is used to provide documentation on the surrounding code.Example: a docstringCOPY

Example

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 the backslash \ operator
  • We can write multiple statements on one lineif each statement is terminated by a semicolon ; operator
  • Indentation defines scope for a code block
  • Comments are prefixed with an octothorp # operator 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

PreviousKeywords, identifiers and operandsNextConsole input & output