[go: up one dir, main page]

0% found this document useful (0 votes)
3 views53 pages

Lecture 28 - Programming Styles and Writing Good Code

The lecture focuses on programming styles and good coding practices, emphasizing the importance of readability, maintainability, and consistency in code. Key principles include following naming conventions, proper code layout, and effective commenting, as outlined in PEP 8. The session aims to equip students with the skills to write clean, understandable, and well-documented Python code.

Uploaded by

kienduong160
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views53 pages

Lecture 28 - Programming Styles and Writing Good Code

The lecture focuses on programming styles and good coding practices, emphasizing the importance of readability, maintainability, and consistency in code. Key principles include following naming conventions, proper code layout, and effective commenting, as outlined in PEP 8. The session aims to equip students with the skills to write clean, understandable, and well-documented Python code.

Uploaded by

kienduong160
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Lecture 28 - Programming

Styles and Writing Good Code


Good coding practices
Professor: Kok-Seng Wong
Teaching Assistant: Nguyen Tran Huu Thinh (Lucaz Nguyen)
WHY IS READABILITY SO IMPORTANT?

Code is read much more often


than it is written.
— Guido van Rossum (founder of Python)

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

KEY PRINCIPLES: writing clean, readable, and maintainable code.


5
PYTHON ENHANCEMENT PROPOSALS (PEP
8)
1. Naming convention
2. Code layout
3. Indentation
4. Comments
5. Whitespace in Expression and Statements
6. Programming Recommendations

Python Software Foundation. (2001). PEP 8 -- Style Guide for Python Code. Python.org. https://peps.python.org/pep-0008/
6
NAMING CONVENTION (1)

Snake Case (snake_case):


• Used for: Variables, functions, methods,
modules, file names.
• Example: user_name, calculate_area,
read_file, my_module.py
Pascal Case (PascalCase):
• Used for: Class names
• Example: Point, BankAccount, UserInterface
[source]
7
NAMING CONVENTION (2)

Underscore Prefix (_prefix):


• Used for: "Private" variables and methods
• Example: _internal_state, _calculate_total

ALL_CAPS:
• Used for: Global constants.
• Example: DEBUG, VERSION, MATH_PI

Avoid using singe letter l, o, and I as variable name:


l = 10 #can be misinterpreted as 1
8
DESCRIPTIVE VARIABLE NAMES

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

parentheses, brackets, or braces

backslashes

15
INDENTATION
“There should be one—and preferably only one—obvious way to do it.”
— The Zen of Python

• Use 4 consecutive spaces to indicate indentation.


• Indentation should be consistent throughout the code.
• Prefer spaces over tabs.

16
WHERE TO PUT THE CLOSING BRACE?
• The first non-whitespace character of the previous line

• The first character of the line that starts the construct

17
COMMENTS
“If the implementation is hard to explain, it’s a bad idea.”
— The Zen of Python

(a) Single-line Comments (b) Inline Comments

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

• Avoid wildcard import

29
TESTING (WRITE UNIT TESTS)
• Verify code correctness and prevent regressions as you make changes.

[source]
30
PROGRAMMING RECOMMENDATIONS

“Simple is better than complex.”


— The Zen of Python

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

Also change the


values in y assign p to
a new list

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)

PEP 8 Violation Code

Reformatted using black


43
CODE FORMATTING

[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

You might also like