Lecture 28 - Programming Styles and Writing Good Code
Lecture 28 - Programming Styles and Writing Good Code
2
LEARNING OUTCOMES
Upon the completion of this lecture, students will be able to:
• write programs that are not only correct but also
understandable with Python programming style.
• explain the important of writing good code in
programming.
• produce consistent/good code to make it easy for people to
understand how a program works.
3
KEY PRINCIPLES FOR GOOD CODING STYLE
1. Readability
2. Maintainability
3. Consistency
[source]
4
THE ZEN OF PYTHON (PEP 20)
Zen (Zen Buddhism)
• Simplicity
• Clarity
• Mindful approach
Python Software Foundation. (2001). PEP 8 -- Style Guide for Python Code. Python.org. https://peps.python.org/pep-0008/
6
NAMING CONVENTION (1)
ALL_CAPS:
• Used for: Global constants.
• Example: DEBUG, VERSION, MATH_PI
9
AVOID ABBREVIATIONS
10
NAMING CONVENTION SUMMARY
• Descriptive names
• Avoid abbreviations
• Lowercase for variables
• Uppercase for classes
11
CODE LAYOUT - BLANK LINES (1)
• Surround top-level functions and classes with two blank lines.
12
CODE LAYOUT - BLANK LINES (2)
• Surround method definitions inside classes with a single blank line
13
CODE LAYOUT - BLANK LINES (3)
• Use blank lines sparingly inside functions to show clear steps
14
MAXIMUM LINE LENGTH AND LINE BREAKING
• PEP 8 suggests lines should be limited to 79 characters
backslashes
15
INDENTATION
“There should be one—and preferably only one—obvious way to do it.”
— The Zen of Python
16
WHERE TO PUT THE CLOSING BRACE?
• The first non-whitespace character of the previous line
17
COMMENTS
“If the implementation is hard to explain, it’s a bad idea.”
— The Zen of Python
Key points:
• Limit the line length of comments and docstrings to 72 characters.
• Use complete sentences, starting with a capital letter.
• Make sure to update comments if you change your code.
18
COMMENTS TYPE
Single-line comments
• Use # to start a comment.
• Explain a specific line or section of code.
Inline Comments
Multi-line Comments
• Use triple quotes (""" or '’’)
• Provide detailed explanations
19
BLOCK COMMENTS
Rules:
• Indent block comments to the same level as the code they describe.
• Start each line with a # followed by a single space.
• Separate paragraphs by a line containing a single #.
20
DOCUMENTATION (DOCSTRINGS)
Docstrings
• String literals placed within functions, classes, or modules.
• Describe their purpose, parameters, return values, and usage.
TODO comments
• Remind you of tasks that
need to be completed later.
21
EXPLAINING THE WHY
22
QUESTION: ANY IDEA?
(b)
(a)
23
COMMENTS AND DOCUMENTATION
• Write clear and concise comments
• Focus on explaining the why, not just the what
• Update comments when code changes
• Use docstrings for formal documentation (modules, functions,
classes, and methods)
• Avoid over-commenting
• Use comments for non-obvious code blocks or tricky logic
24
WHITESPACE AROUND BINARY OPERATORS
“Sparse is better than dense.”
— The Zen of Python
Single space on either side:
• Assignment operators (=, +=, -=, and so forth)
• Comparisons (==, !=, >, <. >=, <=) and (is, is not, in, not in)
• Booleans (and, not, or)
25
CONSISTENCY
• PEP 8 style guide: Adhering to PEP 8 ensures consistency across
codebases and improves readability for Python developers.
• Consistent indentation: Use 4 spaces per indentation level to
visually represent code blocks.
• Consistent naming conventions: Follow snake_case for
variables, camelCase for classes, and PascalCase for constants.
26
ERROR HANDLING
• Graceful error handling: Use try-except blocks to handle
potential errors and provide informative messages:
27
MODULARITY
• Break down large tasks: Create well-defined functions and classes
to encapsulate specific tasks, improving code organization and
reusability.
[source]
28
IMPORT
• Separate lines and specific order
29
TESTING (WRITE UNIT TESTS)
• Verify code correctness and prevent regressions as you make changes.
[source]
30
PROGRAMMING RECOMMENDATIONS
31
TRUTH VALUE CHECKING
Don’t compare Boolean values to True or False using the equivalence operator
32
EMPTY SEQUENCES ARE FALSY
Use the fact that empty sequences are False in if statements
33
IS NOT VS NOT ... IS???
Use is not rather than not ... is in if statements
34
NONE CHECKING
Don’t use if x: when you mean if x is not None:
35
SINGLE LINE STATEMENTS
36
MULTILINE STATEMENTS
37
MODIFYING THE VALUES IN A LIST
x and y are
referring to the
same list object
Output: Output:
38
AVOID USING DEEP NESTING
39
WHEN TO IGNORE PEP 8
NEVER
• Clean, professional, and readable code
• Benefit collaborators and potential employers
Inconvenient cases:
• If complying with PEP 8 would break compatibility with existing software
• If code surrounding what you’re working on is inconsistent with PEP 8
• If code needs to remain compatible with older versions of Python
40
TIPS AND TRICKS – LINTERS
41
TIPS AND TRICKS – LINTERS
42
AUTOFORMATTERS (BLACK)
[source]
44
PEP 8 VIOLATIONS DETECTION
45
IN-CLASS PRACTICE: PEP 8 VIOLATIONS
46
PEP 8 VIOLATIONS DETECTION
47
PEP 8 CORRECTION
48
IN-CLASS PRACTICE: CODING
Question:
• Create a Python function named is_prime that checks whether a given
positive integer is a prime number.
• The function is_prime should take an integer as its argument and return
True if the number is prime, and False otherwise.
Requirements:
• Use PEP 8 style guide, write docstrings for the function.
• Add a test function to test the is_prime function with different inputs.
• Handle the possible exceptions that may arise in the is_prime function.
49
EXAMPLES IN REAL-WORLD APPLICATIONS
• Web development: Consistent style across large codebases
improves collaboration and understanding among developers.
• Data science: Clear and well-documented code facilitates
reproducibility and sharing of analyses.
• Machine learning: Modularity and testing enable experimentation
and debugging of complex algorithms.
50
REMEMBER
• Good coding style is not just about aesthetics; it's a practical
investment in code quality, maintainability, and collaboration.
• Practicing these habits early on will make you a more efficient and
effective Python developer.
51
RESOURCES 1
• PEP 8 document (https://peps.python.org/pep-0008/)
• PEP 8 blog post (https://realpython.com)
• The Missing Semester of Your CS Education (MIT)
52
RESOURCES 2
• Martin, R. C. (2008). Clean Code: A Handbook of Agile Software Craft
smanship. Prentice Hall
• McDowell, G. L. (2015). Cracking the Coding Interview: 189 Progra
mming Questions and Solutions. CareerCup
• LeetCode: The World's Leading Online Programming Learning Platf
orm (https://leetcode.com/)
53