Internal documentation
Formatting: Indenting and white space
|
Indentation and spacing are crucial in Python for structuring code and defining blocks of code. In Python, indentation is used to denote blocks of code, such as those within loops, conditional statements and function definitions. Unlike many other programming languages where braces or keywords are used to delineate code blocks, Python relies solely on indentation for this purpose. Consistency in indentation and spacing throughout your code is essential for readability and maintainability. It ensures that code is easy to understand for both the original author and others who may read or work on the code in the future. Inconsistent indentation can lead to syntax errors and make code difficult to follow, debug and modify. Use a code editor such as VS Code for consistent spacing. It’s important to set up your editor to use the desired indentation style automatically. This helps ensure that you stick to the chosen convention consistently across all your Python code. Use indenting to group code and comments logically: Indent blocks of code: In Python, each nested statement should be indented exactly one level deeper than the enclosing block's indentation level. This is achieved by adding an additional level of indentation for each nested block. Your code editor will probably use thin vertical lines to indicate matching brackets. In most code editors, you can select multiples lines of code and indent (using Tab) or un-indent (using Shift + Tab) all the selected lines together. White spaceBlank lines and spaces are referred to as white space, although depending on your code editor theme, it might actually be black space. White space is used to make code more readable and easier to maintain, and to group sections of code logically. Blank linesPlace a blank line between the end of each Python function and the start of the next function's comment. Place a blank line before and after blocks of code such as for loops, while loops, conditional statements, groups of variable declarations and lines of code that logically belong together. Use blank lines in this way inside functions, loops, conditionals and other blocks of code. You should not have more than one blank line in a row. SpacingPut spaces on either side of operators ( There should be one space after control structure keywords such as There should be no spaces after function names in function declarations and function calls. There should be no spaces after opening brackets and before closing brackets. Extra spaces can be used to line up similar statements vertically. |