StackTips

Syntax, Indentation, and Comments

Indentation refers to the space used at the beginning of a code to improve readability. Unlike any other programming language, indentation in python is very important as it uses indentation to indicate a block of code.

For example, if we're writing a conditional statement using if statement, here's how we use spaces to indent the code.

if True:
    print("True")
else:
    print("False")
True

If you're familiar with any other programming language like Java, or .NET, they use curly braces to indicate a code block. However, for Python you do not require curly braces, instead you're required to use indent your code adequately.

Here are examples of broken syntax in Python:

if True:
print("True")
else:
print("False")
if True:
    print("True")
        print("True")
            print("True")

For all the same reasons, code in Python needs to be perfectly indented or else it will not run.

Comments

At some point down the road, you will want to leave comments in your code, either for yourself in the future, or for another developer working on the same project as you. Here is how comments in Python look like:

# First comment
print("Hello world!") # second comment
Hello world!

Fairly straightforward! Comments in Python start with the # character and the following is the comment itself. Unlike most programming languages, Python does not support multi-line comments. However, nothing technically stops you from doing this:

# This
# is
# a
# multi-line
# comment
print("Hello world!")
Hello world!

This works but keep in mind that comments in general should be short anyway, so using multi-line comments should be done sparingly, if at all.