and Runtime Errors
Errors are an unavoidable part of programming. Python provides tools to identify and manage errors, ensuring that your
programs are reliable and intuitive. This guide focuses on Syntax Errors, Semantic (Logical) Errors, and Runtime Errors,
along with Exception Handling.
Types of Errors in Python
Python errors can be broadly categorized into three types:
Before program
Syntax Error Yes, must fix manually Python parser
execution
Semantic During program Programmer’s
Yes, requires debugging
Error runtime logic
Runtime During program Yes, can be handled with Python
Error runtime try-except interpreter
1. Syntax Errors (Parsing Errors)
What Are They? Syntax errors occur when Python’s grammar rules are violated. For example, missing colons, mismatched
parentheses, or spelling mistakes in keywords.
Detected before the program runs (during parsing).
Python won’t execute the code until these errors are fixed.
Examples of Syntax Errors:
# Missing colon (:) after the loop:
for i in range(5) # SyntaxError: Missing ":"
print(i)
# Mismatched parentheses:
print("Hello World" # SyntaxError: Missing closing parenthesis ")"
What Happens When They Occur?
Python stops execution and displays an error message with:
Error type (SyntaxError)
Description of the violation
Line number and a visual pointer ( ^ ) to where the issue occurred.
Page 1 of 6
, Fix: Carefully read the error message and correct the code to conform to Python’s rules.
2. Semantic Errors (Logical Errors)
What Are They? Semantic errors occur when the code is written correctly (no syntax issues), but the logic or meaning is
incorrect.
Examples of Semantic Errors:
# Example 1: Incorrect formula implementation
radius = 5
area = 2 * 3.14 * radius # Semantic Error: Incorrect formula for area of a circle
print("Area:", area)
# Example 2: Wrong variable used
x = 10
y = 20
result = x * x # Semantic Error: Multiplied x with itself instead of x with y
print(result)
What Happens When They Occur?
Python executes the code without crashing.
Output is unintended or incorrect, which is harder to detect.
Requires testing and debugging to identify the logical flaw.
Fix: Check the logic step-by-step using print statements, debugging tools, or code reviews.
3. Runtime Errors
What Are They? These occur when Python encounters an error while the program is running, disrupting the normal flow.
Common causes of runtime errors:
Dividing by zero.
Accessing out-of-range elements in a list.
Using an undefined variable.
Attempting operations on incompatible data types.
Examples of Runtime Errors:
# Division by zero:
x = 10
Page 2 of 6