COMP1010

Reference - Code Style


Why is it Important?

  • What would it be like to read a book with no capital letters?
  • Or no full stops?
  • Code style does not change the functionality of the program, but makes it more readable (and therefore more debuggable and maintainable) by yourself and other people.

Variable Names and Function Names

  • Meaningful
  • No capital letters
  • Use underscores to separate words (snake_case)
  • You may use i as a variable name for a counter

Examples of Variable Names

CorrectIncorrect
assignment_1_gradeAssignmentOneGrade
product_costx

Indentation:

  • Not tabs - spaces.
  • 4 spaces per indentation level is ideal
  • 2, 3 or 4 spaces are acceptable, but they must be consistent.

Line length:

  • Line length should not exceed 79 characters.
  • Reasoning
  • If you need help (eg your line of code is longer than this, and you need to put it over 2 lines, but then the code breaks), post your specific example on the forums and we can show you how to do this.

Functions:

  • Don't leave chunks of code floating around your file.
  • When in doubt, put your code in a (well-named) function, and call it at the right time.

Constants:

  • Variables which do not change in the course of the program.
  • May be declared outside of functions, but must be done in one section, under the import statements.
  • Must be all capital letters and underscores.

File Structure:

  • Imports
  • Constants
  • Functions
  • Main function
if __name__=="__main__":
    main()