githubEdit

Python Syntax

Python syntax compared to other programming languages

  • Python was designed for readability, and has some similarities to the English language with influence from mathematics.

  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.

  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Indentation

Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important.

Python uses indentation to indicate a block of code.

if 5 > 2:
    print("Five is greater than two!")

Python will give you an error if you skip the indentation.

Statements and New Lines

Most statements end at the newline.

name = "Ada"
print(name)

To continue a statement on multiple lines, wrap it in parentheses:

total = (
    10
    + 20
    + 30
)

Comments

Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

Docstrings

Python also has extended documentation capability, called docstrings.

Docstrings can be one line, or multiline. Docstrings are also comments:

Python uses triple quotes at the beginning and end of the docstring:

Common Pitfalls

  • Mixing tabs and spaces (use spaces only).

  • Forgetting indentation after if, for, while, def, or class.

  • Adding extra indentation where it does not belong.

References

Next | Previous

Last updated