Creating and Testing Programs, Basic Debugging
Lecture 5: Creating and Testing Programs, Basic Debugging
Writing Larger Programs
Importance of Planning: As programs grow in size and complexity, meticulous planning before coding becomes crucial.
Software Engineering: This computer science subfield focuses on processes for constructing extensive software. While not building large-scale software in this course, fundamental principles of good software construction are applicable.
Key Principles: The lecture will cover practical principles for managing program size and complexity.
Commenting
Definition: Comments are descriptive textual notes embedded directly into the program's code.
Execution: For the most part, comments are not executed by the computer; they are solely for human comprehension.
Purpose: Comments aid understanding for:
Other developers who read your code.
Your future self, when revisiting the code.
Maintaining clarity within large, intricate programs.
Python Comment Syntax:
Use the hash symbol (
#) to initiate a comment.Everything following the
#on that line is ignored by the Python interpreter.
Effective Use of Comments: Comments should be used to:
Describe purpose: Explain a line or section of code.
Example:
python # Find the largest factor of x factor = x - 1 while (x % factor) != 0: factor -= 1
Define variables: Clarify the role of a particular variable.
Example:
python total = 0 # will hold the total cost of all items sold sum -= odd_sum # sum now holds sum of all even numbers length = dist * sin(angle * pi / 180) # angle is in degrees
Clarify computations: Provide context for complex or non-obvious calculations.
Example:
python # Perform first-order simulation with constant acceleration new_state = euler(x0, v0, a, t)
Reference external sources: Link to documentation, algorithms, or constants.
Example:
python NA = 6.02214076e23 # Avogadro’s Number # Kruskal’s Algorithm as described in # Corman, Leiserson, Rivest, Stein, “Introduction to # Algorithms” 3rd edition.
Separate code sections: Create visual breaks to organize code.
Example:
python ##### Get user input #####
Ineffective Use of Comments: Avoid using comments to:
Restate obvious code: Don't explain what is self-evident from the code itself.
Example of what not to do:
python numAnimals = 3 # set the number of animals to 3 counter += 1 # increase counter by 1
Include irrelevant information: Comments should be pertinent to the code.
Exception: Header information (e.g., author, date created, modifications) is a valid, required exception.
#I am so tired of writing this code (irrelevant) dist_km = dist_mi * km_per_mi ### taxestimator.py # Author: Stan Lee # Date Created: 1/1/2020 # Modified: Jane Doe 2/2/2020
**Triple-Quoted Strings as