Dealing with SyntaxErrors,Runtime Errors, and ScientificDebuggingPython Programming - Lecture 4
2.
Introduction to Errorsin Python• - Errors are mistakes in code that prevent execution.• - Even experienced programmers make errors.• - Debugging is the process of identifying and fixingerrors.• 🔹 Types of Errors:• Syntax Errors – Code structure mistakes.1 ️1️⃣• Runtime Errors – Errors during execution.2️⃣• Logical Errors – Incorrect output without crashing.3 ️3️⃣
3.
Syntax Errors inPython• ❌ Syntax errors occur when Python encountersincorrect code structure.• ✅ Fixing Syntax Errors:• - Check for missing colons, parentheses, orincorrect indentation.• - Use an IDE with syntax highlighting.
4.
Example of SyntaxErrors• 🔴 Missing Colon (:) in If Statement:• ```• age = 18• if age >= 18 # SyntaxError: Missing colon• print("You are an adult")• ```• 🔴 Unmatched Parentheses:• ```• print("Hello World # SyntaxError: Missing closing quote• ```
5.
Runtime Errors inPython• ⚠️Runtime errors occur **during programexecution**.• ✅ Fixing Runtime Errors:• - Always check for invalid operations (e.g.,division by zero).• - Ensure variables are defined before use.
6.
Example of RuntimeErrors• 🔴 Division by Zero:• ```• num = 5• print(num / 0) # ZeroDivisionError• ```• ✅ Fix:• ```• if num != 0:• print(num / 2)• else:• print("Cannot divide by zero")• ```
7.
Logical Errors inPython• 🔸 Logical errors do not crash the program, butthey produce incorrect output.• ✅ How to Identify Logical Errors:• - Use `print()` statements to track variablevalues.• - Debug with small test cases before runninglarge programs.
8.
Example of LogicalErrors• 🔴 Incorrect Formula for Average Calculation:• ```• a, b, c = 10, 20, 30• average = a + b + c / 3 # Wrong formula• print("Average:", average)• ```• ✅ Correct Formula:• ```• average = (a + b + c) / 3• print("Average:", average)• ```
9.
Debugging Techniques inPython• ✅ Common Debugging Methods:• 1. Using `print()` statements.• 2. Using Python's built-in debugger (`pdb`).• 3. Using an IDE with debugging tools.
10.
Example of Debuggingwith print()• ```• x = 10• print("Value of x:", x) # Debugging usingprint()• ```
11.
Example of Debuggingwith pdb• ```• import pdb• def add(a, b):• pdb.set_trace() # Debugging starts here• return a + b• result = add(5, 10)• print("Result:", result)• ```
12.
Summary and KeyTakeaways• - **Syntax errors**: Code structure mistakes,easily fixed.• - **Runtime errors**: Happen duringexecution (e.g., division by zero).• - **Logical errors**: Cause incorrect resultswithout crashing.• - Debugging techniques: `print()`, `pdb`, andusing an IDE for error detection.
13.
Activity - Fixthe Errors• ❓ Identify and fix the errors in the followingcode:• ```• num = input("Enter a number: ")• print("The square is: " + num * num)• ```• ✅ Hint: Fix data type errors.