Creating and Testing Programs: Basic Debugging

Writing Larger Programs

  • Planning is crucial for larger, more complex programs.
  • Software engineering deals with processes for constructing large software.

Commenting

  • Definition: Descriptive text in code, mostly not executed, purely for human understanding.
  • Purpose: Helps others and future-you understand code's purpose, variable definitions, clarifies computations, references external sources, and visually separates code sections.
  • Python Syntax: Use новую # for single-line comments.
  • Best Practices: Describe purpose of lines/sections, define variables, clarify complex computations. Avoid obvious restatements or irrelevant information.
  • Triple-quoted strings (""" or '''): Can act as multi-line comments if not assigned, but generally not preferred for this purpose.
  • Whitespace: Blank lines and spaces improve readability and visually separate code.

Program Design

  • First Step: Always think about the problem before coding.
  • Approach: Consider major program stages, list them in order as pseudocode (often in comments), then fill in code.
  • Benefit: Saves time later by planning upfront.

Testing and Debugging

  • Testing: Essential to confirm a program works; never assume functionality without testing.
  • Ideal Practice: Write tests before writing code to clarify expectations and provide immediate verification.
  • How to Write Tests:
    • Typical Cases: Ensure basic functionality.
    • Edge/Corner Cases: Test boundaries and special conditions (e.g., first/last days, minimum/maximum values).
  • Implementing Tests: Use print statements to inspect variable values at various points.
  • Debugging: The process of finding where a program is failing, determining the error, and fixing it.
    • Historical Context: The term "bug" originated from an actual moth found in a relay.
    • Common Error Example: TypeError: can only concatenate str (not "int") to str indicates an attempt to perform arithmetic on a string; requires converting input (e.g., float(input())).
  • Incremental Development (Pyramid Style): Write small pieces of code, test them thoroughly, and ensure they work before adding more. This provides a continuously stable software state, unlike the Arch style where the whole structure is unstable until complete.