🔍

CS50's Introduction to Programming with Python: Debugging

Jul 10, 2024

CS50's Introduction to Programming with Python

Lecture: Debugging

Lecturer: David Malan

Key Topics:

  • Types of Bugs

    • Syntax Errors: Code doesn't run due to mistakes in the code syntax.
    • Logical Bugs: Code runs but doesn't produce the intended output.
  • Initial Example: Mario Pyramid

    • Goal: Print a textual pyramid using hashes (#).
    • Initial Code: def main(): height = int(input("Height: ")) pyramid(height) def pyramid(n): for i in range(n): print("#" * i) if __name__ == "__main__": main()
    • Expected Outcome: Pyramid of given height (e.g., height of 3).
    • Initial Issue: Produces: # ##
    • Cause: For loop starts at 0, leading to an unintended blank first line.

Debugging Techniques

  1. Print Statements:

    • Purpose: Quick way to check values of variables.
    • Example in Code: for i in range(n): print(i, end=" ") print("#" * i)
    • Output with Debug Print: 0 1 # 2 ##
    • Realization: The issue is the loop starting at 0.
  2. Breakpoints and Debuggers:

    • Definition: A breakpoint pauses the execution of the program at a specific line for inspection.
    • Using VS Code Debugger:
      • Set Breakpoint: Click to the left of the line number in the editor.
      • Step Into: Goes inside function calls.
      • Step Over: Executes the line, but doesn't dive into functions.
      • Continue: Runs the program until the next breakpoint or the end.
    • Example Use:
      • Setting breakpoint at the start of the main() function.
      • Stepping through to identify the value of i.
      • Confirming variable values via the debug panel.
  3. Making Corrections and Re-running: Correcting the Logic

    • Fix: Adjust the print statement to add 1 to i.
    • Corrected Code: def pyramid(n): for i in range(n): print("#" * (i + 1))
    • Result: Desired outcome of: # ## ###

Summary

  • Importance of Debugging: In the absence of a teacher or peer, tools like print statements and debuggers are essential to diagnosing issues in code.
  • When to Use Each Tool:
    • Print Statements: Quick and simple checks in small code sections.
    • Debugger: Stepping through complex or large codebases, inspecting variables, and understanding control flow.