Learning Python

Python syntax

Indentation

Python depends on indentation to follow the correct flow of execution. In the example below we see that there is a possible error as Hello Jack. is being printed before anything else. Many will assume it will be printed after Hello John. as it is directly after it, but indentation wise it isn’t part of the main function.

#!/usr/bin/env python3

def main():
    if 1 > 2:
        print("Hello World.")
    print("Hello John.")
print("Hello Jack.")


if __name__ == "__main__":
    main()

Output:

Hello Jack.
Hello John.

If we try to correct this error by adding a space before the print statement, then Python still gives an error as indentation doesn’t match all other levels. Python is very similar like YAML and all the indentation need to be the same. See PEP 8 — Style Guide for Python Code for a complete set of rules about indentation.

#!/usr/bin/env python3

def main():
    if 1 > 2:
        print("Hello World.")
    print("Hello John.")
 print("Hello Jack.")


if __name__ == "__main__":
    main()

Output:

  File "/workspaces/python-examples/hello.py", line 7
    print("Hello Jack.")
                        ^
IndentationError: unindent does not match any outer indentation level

Comments

Any line that starts with # will be ignored by Python.

#!/usr/bin/env python3

def main():
    if 1 > 2:
        print("Hello World.")
    print("Hello John.")
    # print("Hello Jack.")


if __name__ == "__main__":
    main()

Output:

Hello John.

Multiline comments can be done by starting every line with the #-sign.

#!/usr/bin/env python3

def main():
    if 1 > 2:
        print("Hello World.")
    print("Hello John.")
    # print("Hello Jack.")
    # print("Hello James.")


if __name__ == "__main__":
    main()

Output:

Hello John.

For multiline comments Python also supports comments between triple quotes as in the example below.

#!/usr/bin/env python3

def main():
    if 1 > 2:
        print("Hello World.")
    print("Hello John.")
    """
    print("Hello Jack.")
    print("Hello James.")
    """


if __name__ == "__main__":
    main()

Output:

Hello John.